sql
  1. sql-where-clause

SQL WHERE Clause

The SQL WHERE clause is used to filter the rows from a table based on a specified condition or conditions. The WHERE clause is often used in conjunction with the SELECT statement, but it can also be used with the UPDATE, DELETE, and other statements that modify data in a table.

Syntax

The basic syntax of the WHERE clause is as follows:

SELECT column1, column2, ...
FROM table_name
WHERE condition;

The WHERE keyword is followed by a condition that specifies which rows should be returned. The condition is typically a comparison between one or more columns and a constant value, but it can also be a combination of multiple conditions using logical operators such as AND, OR, and NOT.

Example

Consider the following example table:

students
+----+-------+--------+
| id | name  |  grade |
+----+-------+--------+
| 1  | Alice |   85   |
| 2  | Bob   |   75   |
| 3  | Charlie |  90  |
| 4  | David |   80   |
+----+-------+--------+

To select only those students whose grade is above 80, we can use the following SQL query:

SELECT name, grade
FROM students
WHERE grade > 80;

Output

+-------+--------+
| name  | grade  |
+-------+--------+
| Alice |   85   |
| Charlie |  90  |
+-------+--------+

Explanation

In the above example, we are selecting only the name and grade columns from the students table where the grade is greater than 80. The output only includes the rows which satisfy this condition.

Use

The WHERE clause is particularly useful in scenarios where we want to filter out specific rows from a table based on certain conditions. For example, we might want to retrieve only the sales data for a particular region or only the customer data for a certain age group.

Important Points

  • The WHERE clause always follows the FROM clause in a SQL statement.
  • The condition in the WHERE clause must evaluate to either true or false for each row in the table.
  • Multiple conditions can be combined using logical operators such as AND and OR.

Summary

The WHERE clause is a fundamental part of SQL that allows us to filter out specific rows from a table based on certain conditions. Whether we are querying data or modifying it, the WHERE clause is a powerful tool that helps us achieve our goals efficiently and effectively.

Published on: