
For an instructor lead, in-depth look at learning SQL click below.
Welcome, today we will learn how to retrieve records from a SQL table based on certain conditions. SQL, or Structured Query Language, has a feature known as the WHERE clause, that allows us to specify conditions to limit the results returned by a SELECT statement.
Basic SQL WHERE clause
The WHERE clause in SQL is used to filter records that fulfill a specified condition. It comes after the FROM clause.
|
1 2 3 4 5 |
SELECT column1, column2, ... FROM table_name WHERE condition; |
Let’s assume we have a table called Employees with the following data:
|
1 2 3 4 5 6 7 8 9 10 |
+----+-------+-------+ | ID | Name | Age | +----+-------+-------+ | 1 | John | 25 | | 2 | Adam | 29 | | 3 | Sarah | 30 | | 4 | Mike | 28 | +----+-------+-------+ |
For example, if we want to retrieve all employees that are over 28 years old, our SQL query would be:
|
1 2 3 4 5 |
SELECT * FROM Employees WHERE Age > 28; |
Using AND and OR Operators
In SQL, you can use the AND and OR operators to combine multiple conditions. The AND operator displays a record if both the first condition AND the second condition are true. The OR operator displays a record if either the first condition OR the second condition is true.
For instance, to fetch employees who are either 25 years old or named Adam, we would write:
|
1 2 3 4 5 |
SELECT * FROM Employees WHERE Age = 25 OR Name = 'Adam'; |
Combining AND and OR
You can also combine the AND and OR operators. For instance, to fetch employees who are over 25 and are either named Adam or John, we would write:
|
1 2 3 4 5 |
SELECT * FROM Employees WHERE Age > 25 AND (Name = 'Adam' OR Name = 'John'); |
SQL is a powerful tool that can manipulate and manage data efficiently. The WHERE clause is just one of the tools at your disposal when executing queries in SQL with conditions. Make sure to practice these examples on your own to get accustomed to how they work.
