WHERE clause in SQL
The WHERE clause in SQL is used to filter records that meet a specified condition. It is used to extract only those records that fulfill a given criterion. WHERE clause is generally used in SELECT, UPDATE, DELETE statement etc.
The following are some conditional operators which can be used in the WHERE clause:
Operator | Description |
---|---|
= | equal |
> | greater than |
< | less than |
>= | greater than or equal |
<= | less than or equal |
<> or != | not equal to |
BETWEEN | Between an inclusive range |
LIKE | Search for a pattern |
IN | To specify multiple possible values for a column |
Example: Let’s create an employees table.
SQL
CREATE TABLE Employees ( EmployeeID INT, Name VARCHAR(20), Age int, Salary VARCHAR(10), Department VARCHAR(25), Gender VARCHAR(1) );
Load the data into the Employees table.
SQL
insert into Employees values (1, ‘Ashish’, 24, ‘25000’, ‘Electrical’, ‘M’), (2, ‘Kirshan’, 32, ‘30000’, ‘Electrical’, ‘M’), (3, ‘Anjali’, 20, ‘25000’, ‘Electronics’, ‘F’), (4, ‘Manjulika’, 30, ‘15000’, ‘Electrical’, ‘F’), (5, ‘Katrina’, 37, ‘18000’, ‘Computer’, ‘F’), (6, ‘Esha’, 37, ‘20000’, ‘Computer’, ‘F’), (7, ‘Ankita’, 20, ‘9000’, ‘Electronics’, ‘M’), (8, ‘Meenakshi’, 30, ‘15000’, ‘Computer’, ‘F’), (9, ‘Alia’, 37, ‘16000’, ‘Electronics’, ‘F’);
By executing the following query we can see the data in the table:
SQL
SELECT * FROM Employees;
The above query returned the following result:
Table: Employees
EmployeeID | Name | Age | Salary | Department | Gender |
---|---|---|---|---|---|
1 | Ashish | 24 | 25000 | Electrical | M |
2 | Kirshan | 32 | 30000 | Electrical | M |
3 | Anjali | 20 | 25000 | Electronics | F |
4 | Manjulika | 30 | 15000 | Electrical | F |
5 | Katrina | 37 | 18000 | Computer | F |
6 | Esha | 37 | 20000 | Computer | F |
7 | Ankita | 20 | 9000 | Electronics | M |
8 | Meenakshi | 30 | 15000 | Computer | F |
9 | Alia | 37 | 16000 | Electronics | F |
Basic WHERE Clause Select employees with a salary greater than 20,000.
SQL
SELECT *
FROM Employees
WHERE Salary > 20000;
FROM Employees
WHERE Salary > 20000;
The result of the above query is shown below:
EmployeeID | Name | Age | Salary | Department | Gender |
---|---|---|---|---|---|
1 | Ashish | 24 | 25000 | Electrical | M |
2 | Kirshan | 32 | 30000 | Electrical | M |
3 | Anjali | 20 | 25000 | Electronics | F |