SQL Where
The WHERE clause in SQL is used to filter records from a table based on specific conditions. It helps retrieve only the data you need, making your queries more efficient and relevant.
What is the WHERE Clause?
Syntax:
Common Operators Used with WHERE
EMPLOYEES Table
Example: Using = (Equal To)
Output:
Example: Using < (Less Than)
Output:
- It filters records that meet the given condition(s).
- It can be used with any SELECT, UPDATE, DELETE, or INSERT query.
- It simplifies data aggregation by narrowing down the results.
- Conditions are specified using comparison operators (like =, >, <, etc.).
Syntax:
SELECT column_name
FROM table_name
WHERE condition;
- column_name: Name of the column(s) to retrieve.
- table_name: Name of the table to query from.
- condition: Logic used to filter data (e.g., AGE > 25).
Common Operators Used with WHERE
Operator | Description |
---|---|
= | Equal to |
<> or != | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
AND, OR | Combine multiple conditions |
LIKE | Pattern matching |
IN | Matches any in a list |
EMPLOYEES Table
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: Using = (Equal To)
SELECT ID, NAME
FROM EMPLOYEES
WHERE AGE = 32;
Output:
ID | NAME |
---|---|
4 | Roshani |
Explanation: Fetches employees where the AGE is exactly 32.
Example: Using < (Less Than)
SELECT ID, NAME
FROM EMPLOYEES
WHERE SALARY < 20000;
Output:
ID | NAME |
---|---|
1 | Shweta |
3 | Abhi |
4 | Roshani |
Explanation: Returns employees with a salary less than Rs 20,000.
Key Point
- The WHERE clause is essential for filtering specific rows.
- Combine multiple conditions with AND or OR for advanced filtering.
- Use it to improve query performance and extract only what is needed.