Loading
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, column2
FROM table_name
WHERE 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

idnameagecity
1Rahul20Delhi
2Neha22Mumbai
3Amit20Delhi
4Priya21Pune


Example - 1: Filter Records Using WHERE

Query: Select students who are 20 years old

SELECT *
FROM students
WHERE age = 20;


Output

idnameagecity
1Rahul20Delhi
3Amit20Delhi


Only records matching the condition are returned.


Example - 2: Filtering Using Text Values

Query: Select students from Delhi

SELECT name, age
FROM students
WHERE city = 'Delhi';

Explanation

  • Text values are written inside single quotes
  • Only students whose city is Delhi are selected


Common Comparison Operators Used with WHERE

OperatorMeaning
=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 students
WHERE 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