In this tutorial, we aim at helping you understand how to use the SQL WHERE clause to filter data based on specific conditions. The WHERE clause is a powerful tool that can significantly enhance your data retrieval capabilities in SQL.
By the end of this tutorial, you will be able to:
- Understand the concept of the WHERE clause in SQL
- Apply the WHERE clause in SQL queries to filter data
- Use logical operators with the WHERE clause
Prerequisites: Basic knowledge of SQL and its syntax.
The WHERE clause is used in SQL to filter records. It is used to extract only those records that fulfill a specified condition.
Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE condition;
You can use logical operators like =, <>, >, <, >=, <= along with WHERE clause to filter the results. Let's understand this with examples.
Consider a table called Employees
with the following data:
EmpId | EmpName | EmpAge | EmpSalary |
---|---|---|---|
1 | John | 35 | 5000 |
2 | Smith | 40 | 6000 |
3 | David | 30 | 7000 |
4 | Sara | 20 | 8000 |
If you want to fetch records of the employee with EmpId = 1, the SQL query would look like this:
SELECT *
FROM Employees
WHERE EmpId = 1;
This will return the following output:
EmpId | EmpName | EmpAge | EmpSalary |
---|---|---|---|
1 | John | 35 | 5000 |
If you want to fetch records of employees with EmpSalary more than 6000, the SQL query would look like this:
SELECT *
FROM Employees
WHERE EmpSalary > 6000;
This will return the following output:
EmpId | EmpName | EmpAge | EmpSalary |
---|---|---|---|
3 | David | 30 | 7000 |
4 | Sara | 20 | 8000 |
In this tutorial, we learned about the SQL WHERE clause, its purpose, and how to use it with different operators to filter data. Continue practicing with different operators and conditions to grasp the concept better.
Solutions:
SELECT *
FROM Employees
WHERE EmpAge < 35;
SELECT *
FROM Employees
WHERE EmpName <> 'John';
Keep experimenting with different conditions and operators to gain more confidence and proficiency with the WHERE clause.