Where clause
In this tutorial, we are going to explore one of the fundamental concepts in SQL, the WHERE clause. The WHERE clause is used to filter records and is an essential part of most database operations.
What is the WHERE Clause?
The WHERE clause in SQL is used to filter the results of a SELECT, UPDATE, or DELETE statement. It specifies a condition that the records must meet to be selected or affected by the command. In simpler terms, the WHERE clause is used to extract only those records that fulfill a specific criterion.
Syntax of WHERE Clause
The basic syntax of the WHERE clause can be represented as:
SELECT column1, column2, ...
FROM table_name
WHERE condition;
In the above SQL statement, column1, column2, ...
are the names of the fields of the table from where you want to select data. The table_name
is the name of the table from where you want to fetch the data. The condition
is the criterion that a record must meet to be selected.
Using the WHERE Clause
Let's consider an example. We have a table named Customers
with the following data:
ID | Name | City | Country |
---|---|---|---|
1 | John | Paris | France |
2 | Sarah | Rome | Italy |
3 | Lucy | Madrid | Spain |
Now, if we want to select all the customers who are from the city 'Paris', we would use the WHERE clause as follows:
SELECT * FROM Customers
WHERE City='Paris';
The result would be:
ID | Name | City | Country |
---|---|---|---|
1 | John | Paris | France |
Using Comparison Operators in WHERE Clause
We can also use comparison operators in the WHERE clause to compare numeric values. The commonly used comparison operators are:
=
Equal<>
Not equal. Note: In some versions of SQL this operator may be written as!=
>
Greater than<
Less than>=
Greater than or equal<=
Less than or equal
For instance, if we have a Orders
table:
OrderID | CustomerID | Quantity |
---|---|---|
1 | 3 | 5 |
2 | 1 | 3 |
3 | 2 | 8 |
4 | 1 | 1 |
And we want to find orders with Quantity greater than 5, we can use the following SQL statement:
SELECT * FROM Orders
WHERE Quantity>5;
The result would be:
OrderID | CustomerID | Quantity |
---|---|---|
3 | 2 | 8 |
Conclusion
The WHERE clause is a powerful tool in SQL, allowing you to filter data and extract only the records that meet certain criteria. It's used in conjunction with SQL commands like SELECT, UPDATE, or DELETE to perform operations on data that meet specific conditions.
In the next sections, we will continue to explore other essential SQL concepts. With each tutorial, you'll gain a better understanding of how to use SQL to interact with databases effectively.