SQL WHERE Clause
- The WHERE clause is used to explicitly filter out only those records that meet the conditions specified by you. This saves time, effort and complexity.
- Using the WHERE clause makes specified data aggregation a lot easier
- In fetching these relational data items, the WHERE clause in SQL is used. This is responsible for selecting only those data items that correspond to the mentioned conditions.
- This is done to specifically filter out particular columns.
Syntax:
SELECT column_ name
FROM table_ name
WHERE condition;
- Operators in the WHERE Clause help you to specify the various conditions that you would like to query from a database.
Operators used in WHERE to select desired columns for a record are:
Examples of WHERE Clause Operators:
Let's consider an EMPLOYEES table containing information on employees working in a firm distributed across India.
ID | NAME | AGE | ADDRESS | SALARY |
---|---|---|---|---|
1 | Shweta | 25 | Mumbai | Rs 12000 |
2 | Raj | 26 | Goa | Rs 25000 |
3 | Abhi | 30 | Karnataka | Rs 18000 |
4 | Roshani | 32 | Kerala | Rs 15000 |
Example:
1. Where Clause with the EQUAL Operator:
This is used to display only those records which have values equal to the values specified.
Example:
SELECT ID, NAME
FROM EMPLOYEES
WHERE AGE=32;
- Above, the code is used to fetch the ID and NAME values for those employees wherein the age of the employee is equal to 32
Output:
From the table, you can see that employee Roshani meets the given criteria.
2. WHERE Clause with the LESS THAN and GREATER THAN Operators:
These shall be used to display only those records that have values lesser than and greater than the values specified respectively.
Example:
SELECT ID, NAME
FROM EMPLOYEES
WHERE SALARY <20000;
- Above, the code is used to fetch the ID and NAME values for those employees wherein the salaries of the employees are less than Rs. 20000.
Output:
From the table, you can see that employees Seema Kapoor and Abhi Kumar meet the given criterion.