WHERE
In real life, when you search for something, you rarely want everything.
For example:
- From a phone contact list, you search only one name
- From an online store, you filter only laptops under ₹50,000
- From student records, you look for students who passed
Databases work in the same way.
A database table may contain thousands or millions of records, but most of the time we need only specific data, not the entire table.
This is where filtering records becomes important.
What Is Filtering in SQL?
Filtering means selecting only those rows (records) that match a specific condition.
SQL provides the WHERE clause to apply such conditions.
The WHERE clause is used to filter records based on given conditions.
What Is the WHERE Clause?
The WHERE clause is used in SQL to restrict the data returned by a query.
Instead of fetching all rows from a table, the WHERE clause allows you to:
- Select specific records
- Apply conditions
- Get meaningful results
Syntax
SELECT column1, column2FROM table_nameWHERE condition;Explanation
- SELECT - specifies the columns to display
- FROM - specifies the table
- WHERE - applies the condition
- condition - decides which rows to include
Example: Students Table
| id | name | age | city |
|---|---|---|---|
| 1 | Rahul | 20 | Delhi |
| 2 | Neha | 22 | Mumbai |
| 3 | Amit | 20 | Delhi |
| 4 | Priya | 21 | Pune |
Example - 1: Filter Records Using WHERE
Query: Select students who are 20 years old
SELECT *FROM studentsWHERE age = 20;Output
id name age city 1 Rahul 20 Delhi 3 Amit 20 Delhi
Only records matching the condition are returned.
Example - 2: Filtering Using Text Values
Query: Select students from Delhi
SELECT name, ageFROM studentsWHERE city = 'Delhi';Explanation
- Text values are written inside single quotes
- Only students whose city is Delhi are selected
Common Comparison Operators Used with WHERE
| Operator | Meaning |
|---|---|
| = | Equal to |
| != or <> | Not equal to |
| > | Greater than |
| < | Less than |
| >= | Greater than or equal to |
| <= | Less than or equal to |
Example - 3: Using Comparison Operations
Query: Select students older than 20
SELECT *FROM studentsWHERE age > 20;Important Points About WHERE Clause
- WHERE clause filters rows, not columns
- It works with:
1. Numbers
2. Text
3. Dates
- Conditions are evaluated row by row
- Without WHERE, all records are returned
WHERE Clause with SELECT, UPDATE, DELETE
- SELECT - filters displayed data
- UPDATE - filters rows to update
- DELETE - filters rows to delete
Using WHERE incorrectly can update or delete all records, so it must be used carefully.
Two Minute Drill
- WHERE clause is used to filter records
- It limits rows returned by a query
- Works with numbers, text and conditions
- Always written after FROM
- Conditions decide which rows are selected
- Text values use single quotes
- Without WHERE, all records are selected