SQLab Hub
Lesson 3 · WHERE Clause
Lesson 3 · Fundamentals

SQL WHERE Clause: Syntax, Examples & Practice

The SQL WHERE clause filters rows based on a condition. It is used with SELECT, UPDATE and DELETE statements, and only the rows that satisfy the condition are returned or affected.

📖 11 concepts 🔧 9 operators ⚡ AND/OR live demo 📝 10-question quiz ⏱ ~25 min 🗓 Updated

What Is the SQL WHERE Clause?

WHERE is how you tell a database which rows you want. The database checks your condition against every row in the table: rows where the condition is true are kept, and rows where it is false — or unknown, because of a NULL value — are skipped. Leave WHERE out and the statement applies to every row.

  • SELECT … WHERE returns only the matching rows.
  • UPDATE … WHERE changes only the matching rows.
  • DELETE … WHERE removes only the matching rows.

Basic WHERE Syntax

SELECT column1, column2
FROM table_name
WHERE condition;

The condition is usually a column, an operator and a value — for example marks > 80.

A Simple WHERE Example

SELECT *
FROM students
WHERE marks > 80;
students table — 5 rows
The students table before filtering
nameclassmarks
Priya1092
Aman985
Alice1088
Bob842
Karan1076
All rows, before filtering
📊 Result of the query
Rows returned by the WHERE query
nameclassmarks
Priya1092
Aman985
Alice1088
✓ 3 rows — only students with marks > 80

The query reads the students table and keeps only the rows where marks is greater than 80. Priya, Aman and Alice are returned; Bob (42) and Karan (76) are filtered out. The * means "all columns", so WHERE decides which rows appear, not which columns.

Think of WHERE as a Filter

When you open Instagram, you don't want to see everything — you want only reels, only posts from friends, only travel content. That filtering is exactly what WHERE does in SQL: "don't return everything — return only the rows that match this condition."
All posts (no filter)
Reel 🎬
Post 🖼
Reel 🎬
Story 📸
Reel 🎬
WHERE type = 'reel'
Reel 🎬
Post 🖼
Reel 🎬
Story 📸
Reel 🎬

WHERE with UPDATE and DELETE

WHERE works the same way when you change data: it picks the rows the statement is allowed to touch.

-- Change only the rows that match
UPDATE students
SET class = 11
WHERE class = 10;

-- Remove only the rows that match
DELETE FROM students
WHERE marks < 35;
Careful: an UPDATE or DELETE without a WHERE clause affects every row in the table. Run the same condition as a SELECT first to check which rows it matches.

Where Is WHERE Used in Real Systems?

E-commerce
Filter products by price range, category, or stock status
Dashboards
Fetch only this month's data or active user records
Banking
Show only pending transactions above ₹10,000
Healthcare
Filter patients by age group or diagnosis code
Apps & APIs
Return only a user's own records from the database
Analytics
Segment data by region, date range, or cohort

SQL WHERE Clause Syntax

The exact structure SQL expects — get this right every time

Every WHERE condition follows the same pattern: a column, an operator, and a value.

SELECT column1, column2
FROM table_name
WHERE column_name operator value;
  • SELECT comes first — pick which columns (new to SELECT? start with the BIG 6 SQL clauses)
  • FROM comes second — pick which table
  • WHERE comes third — define the filter condition
  • A condition follows the pattern: column operator value
  • Text values need single quotes: 'Delhi', 'Active'
  • Numbers and booleans need no quotes: 80, 10, true (see SQL data types)

Multiple Conditions Syntax

-- Both conditions must be true (AND)
SELECT *
FROM students
WHERE class = 10 AND marks > 75;

-- Either condition can be true (OR)
SELECT *
FROM students
WHERE city = 'Delhi' OR city = 'Mumbai';
Quick memory trick: Think of WHERE as answering the question "Which rows do I want?" Every WHERE condition is just an answer to that question using a column, an operator, and a value.

Where WHERE Goes: SQL Clause Order

Students get this wrong constantly. WHERE always comes after FROM — never before it. SQL expects clauses in a specific order and throws a syntax error if you mix them up.
❌ Wrong order
SELECT *
WHERE marks > 80
FROM students;
✗ Syntax Error — SQL doesn't understand this
✅ Correct order
SELECT *
FROM students
WHERE marks > 80;
✓ Works perfectly
The full clause sequence
SELECT FROM WHERE GROUP BY HAVING ORDER BY

WHERE is written third. It comes after FROM — including any SQL JOINs that combine tables — and before GROUP BY, HAVING and ORDER BY. That is why WHERE filters individual rows before any grouping or sorting happens.

SQL WHERE Clause Examples

Filtering numbers, text and dates — the three things you'll do most

WHERE with Numbers

Numeric values are written without quotes and work with every comparison operator.

School"Show only class 10 students"

SELECT *
FROM students
WHERE class = 10;
Result
nameclass
Priya10
Alice10
Karan10
✓ 3 rows returned

Shopping"Show products cheaper than ₹500"

SELECT *
FROM products
WHERE price < 500;
Result
productprice
Pencil₹10
Notebook₹120
Bag₹450
✓ 3 rows returned

WHERE with Text

Text values go inside single quotes. The match is exact — 'Delhi' does not match 'New Delhi'. For partial matches, use the SQL LIKE operator.

Cities"Show students who live in Delhi"

SELECT *
FROM students
WHERE city = 'Delhi';
Result
namecity
PriyaDelhi
KaranDelhi
✓ 2 rows returned

WHERE with Dates

Dates are written as quoted strings in 'YYYY-MM-DD' format and can be compared like numbers — earlier dates are "less than" later ones. To extract a year or month before filtering, see SQL date functions.

Orders"Show orders between January and June 2026"

SELECT *
FROM orders
WHERE order_date BETWEEN
  '2026-01-01' AND '2026-06-01';
Result
order_idorder_date
0012026-02-14
0022026-04-01
0032026-05-30
✓ 3 rows returned

SQL WHERE Operators

Your tools for filtering — pick an operator, or expand any of them below

Operators are the controls for WHERE — they tell SQL exactly how to compare a column with a value. These 9 operators cover virtually every WHERE filtering scenario you'll encounter.

Equal to (=)

Returns rows where the column exactly matches the value.

SELECT *
FROM students
WHERE class = 10;
nameclass
Priya10
Aman10
✓ 2 matching rows

Not equal to (!= or <>)

Returns rows that do not match the value. <> is the standard SQL spelling; != works in almost every database too.

SELECT *
FROM students
WHERE class != 10;
nameclass
Alice9
Bob8
✓ 2 matching rows

Greater than (>)

Returns rows where the column is strictly larger than the value. A row with exactly 80 marks is not included.

SELECT *
FROM students
WHERE marks > 80;
namemarks
Priya92
Aman85
✓ 2 matching rows

Less than (<)

Returns rows where the column is strictly smaller than the value.

SELECT *
FROM students
WHERE marks < 50;
namemarks
Bob42
✓ 1 matching row

Greater than or equal to (>=)

Like >, but the boundary value itself is included — a student with exactly 80 marks matches.

SELECT *
FROM students
WHERE marks >= 80;
namemarks
Priya92
Aman80
✓ 2 matching rows

Less than or equal to (<=)

Returns rows where the column is at most the value, boundary included.

SELECT *
FROM products
WHERE price <= 500;
productprice
Pencil10
Book250
✓ 2 matching rows

BETWEEN (range)

Matches values inside a range. BETWEEN is inclusive: marks BETWEEN 70 AND 90 means the same as marks >= 70 AND marks <= 90. It works with numbers, dates and text.

SELECT *
FROM students
WHERE marks BETWEEN 70 AND 90;
namemarks
Alice75
Aman85
✓ 2 matching rows

LIKE (pattern match)

Matches text against a pattern instead of an exact value. % stands for any number of characters, so 'A%' means "starts with A". The WHERE with LIKE section below covers every wildcard.

SELECT *
FROM students
WHERE name LIKE 'A%';
name
Alice
Aman
✓ 2 matching rows

IN (list of values)

Matches any value in a list — a shorter way to write several OR conditions on the same column. NOT IN, subqueries and NULL pitfalls are covered in the SQL WHERE IN operator lesson.

SELECT *
FROM students
WHERE class IN (9, 10);
nameclass
Alice9
Priya10
✓ 2 matching rows
Tip: Missing values need their own operators — IS NULL and IS NOT NULL — explained in WHERE and NULL values below.

Using AND and OR with WHERE

Combine conditions — this is where SQL WHERE gets really powerful

AND requires both conditions to be true. OR returns rows where any condition is true. Open each example below and compare the results.
🔗 AND — both conditions must be true
Query
SELECT *
FROM students
WHERE class = 10
  AND marks > 80;
Result (2 rows)
nameclassmarks
Priya1092
Alice1085
✓ 2 students in class 10 with marks > 80
🔀 OR — any condition can be true
Query
SELECT *
FROM students
WHERE class = 10
  OR class = 9;
Result (4 rows)
nameclassmarks
Priya1092
Alice1085
Aman978
Bob965
✓ 4 students in class 9 or 10
AND

Both conditions must be true

Narrows down results — fewer rows returned

OR

Any condition can be true

Expands results — more rows returned

Combining AND + OR — Use Parentheses

When you mix AND and OR, SQL evaluates AND first (higher precedence). Always use parentheses to make your intent explicit.
❌ Ambiguous — AND runs first
SELECT *
FROM users
WHERE is_premium = 1
  AND city = 'Houston'
  OR city = 'Austin';
-- Returns: (premium AND Houston) OR anyone in Austin: 13 users
✅ Clear — parentheses control order
SELECT *
FROM users
WHERE is_premium = 1
  AND (city = 'Houston'
    OR city = 'Austin');
-- Returns: premium users in Houston or Austin: 7 users

Checking one column against several values? city IN ('Houston', 'Austin') says the same thing as the OR above with less typing — see filtering multiple values with WHERE IN.

WHERE and NULL Values

The most misunderstood part of SQL WHERE — NULL is not zero

NULL means "no value" or "missing data." It is not zero, not an empty string, not false. It is the absence of any value. And this changes how WHERE works completely.

The Golden Rule: Never Use = NULL

Critical mistake: WHERE column = NULL always returns 0 rows. NULL cannot be compared with =. Use IS NULL instead.
❌ Always returns 0 rows
SELECT *
FROM employees
WHERE manager_id = NULL;
-- NULL = NULL is NULL, not TRUE
-- So no rows match
✅ Correct — use IS NULL
SELECT *
FROM employees
WHERE manager_id IS NULL;
-- Returns employees with
-- no assigned manager

IS NOT NULL — Finding Rows That Have a Value

-- Employees who have a manager
SELECT first_name, last_name, manager_id
FROM employees
WHERE manager_id IS NOT NULL;   -- 110 of 120 employees

-- Orders that have shipped
SELECT id, status, shipped_date
FROM orders
WHERE shipped_date IS NOT NULL; -- 103 of 200 orders

Why Does = NULL Fail?

The three-valued logic: SQL uses TRUE, FALSE, and NULL (unknown). The expression NULL = NULL evaluates to NULL — not TRUE. WHERE only returns rows where the condition is TRUE. So WHERE column = NULL effectively matches nothing, because the result is always NULL.

Real Business Examples

-- Orders that haven't been shipped yet
SELECT id, total
FROM orders
WHERE shipped_date IS NULL;     -- 97 orders

-- Employees with no manager (the top of the org chart)
SELECT first_name, last_name, department
FROM employees
WHERE manager_id IS NULL;       -- 10 employees
IS NULL

Column has no value

Missing data, optional fields left blank

IS NOT NULL

Column has a value

Required data that was filled in

Filtering NULLs out is one option; replacing them with a default value is another. That is what the COALESCE function is for.

WHERE vs HAVING

One of the most common SQL interview questions — know this cold

Both WHERE and HAVING filter data, but they operate at different stages of query execution. WHERE filters individual rows. HAVING filters groups after aggregation. Getting this wrong is a classic SQL interview mistake.

Side-by-Side Comparison

WHERE compared with HAVING
FeatureWHEREHAVING
FiltersIndividual rowsGrouped results
Position in queryBefore GROUP BYAfter GROUP BY
Runs atRow-level (pre-aggregation)Group-level (post-aggregation)
Can use aggregates?✗ No (COUNT, SUM, AVG…)✓ Yes
Requires GROUP BY?✗ No✓ Yes
ExampleWHERE marks > 50HAVING COUNT(*) > 5

WHERE — Filter Before Grouping

-- Step 1: WHERE removes rows with marks ≤ 50
-- Step 2: GROUP BY groups remaining rows by class
-- Step 3: AVG() is calculated on the filtered rows
SELECT class, AVG(marks) AS avg_marks
FROM students
WHERE marks > 50
GROUP BY class;

HAVING — Filter After Grouping

-- Step 1: GROUP BY groups ALL rows by class
-- Step 2: COUNT(*) counts each group
-- Step 3: HAVING removes groups with fewer than 5 students
SELECT class, COUNT(*) AS total_students
FROM students
GROUP BY class
HAVING COUNT(*) >= 5;

Using Both Together

-- WHERE filters failing students first (marks > 40)
-- GROUP BY groups passing students by class
-- HAVING keeps only classes with 5 or more students
SELECT class, COUNT(*) AS passing_students
FROM students
WHERE marks > 40
GROUP BY class
HAVING COUNT(*) >= 5;
Memory trick: WHERE is a bouncer at the door — checks every row before they enter. HAVING is a judge after the show — evaluates groups after they've formed. To go deeper, learn how GROUP BY builds those groups, which aggregate functions HAVING can test, and then learn SQL HAVING in its own lesson.

SQL WHERE Clause with LIKE

Pattern matching — search text columns with wildcards

LIKE lets you search for patterns instead of exact values. Instead of knowing the full name, you can say "give me everything that starts with A" or "everything that contains the word phone."

The Two Wildcards

LIKE wildcards and example patterns
WildcardMeaningExample PatternMatches
%Any sequence of characters (including none)'A%'Alice, Aman, Arjun
_Exactly one character'_a%'Rahul, Manish, Karan
%x%Contains x anywhere'%ith%'Smith, Prithvi, Rithesh
%xEnds with x'%son'Johnson, Anderson
x%Starts with x'De%'Delhi, Denver, Dean

LIKE Examples

-- First names starting with 'A'
SELECT first_name, last_name FROM users WHERE first_name LIKE 'A%';
-- 14 users: Anthony, Angela, Amy, Andrew, Amanda, Ashley ...

-- Last names ending with 'son'
SELECT first_name, last_name FROM users WHERE last_name LIKE '%son';
-- 14 users: Jackson, Wilson, Robinson, Johnson, Anderson, Nelson ...

-- Email addresses from Gmail
SELECT first_name, email FROM users WHERE email LIKE '%@gmail.com';
-- 28 users

-- Product names containing 'phone'
SELECT name FROM products WHERE name LIKE '%phone%';
-- Magnetic Phone Mount Pro, Noise-Cancelling Headphones

-- First names whose second letter is 'a'
SELECT first_name FROM users WHERE first_name LIKE '_a%';
-- 41 users: Barbara, Carol, David, James, Karen, Laura ...

NOT LIKE — Exclude Patterns

-- Find all products that are NOT electronics
SELECT * FROM products
WHERE category NOT LIKE '%electronics%';

-- Exclude test accounts
SELECT * FROM users
WHERE email NOT LIKE '%test%'
  AND email NOT LIKE '%example%';
Performance tip: LIKE 'term%' (prefix match) is fast and can use a database index. LIKE '%term%' (contains) performs a full table scan — use it carefully on large tables. Case sensitivity, escaping wildcards and more patterns are covered in the full SQL LIKE operator lesson.

Common SQL WHERE Mistakes

Avoid these — every SQL beginner makes them at least once

These are the six most common SQL WHERE mistakes that beginners make. Recognising them now saves hours of debugging later.
Mistake 1

WHERE before FROM

❌ Wrong
SELECT *
WHERE marks > 80
FROM students;
✅ Correct
SELECT *
FROM students
WHERE marks > 80;

SQL requires a strict clause order. WHERE must come after FROM, not before it.

Mistake 2

Using = NULL instead of IS NULL

❌ Wrong
SELECT *
FROM employees
WHERE manager_id = NULL;
✅ Correct
SELECT *
FROM employees
WHERE manager_id IS NULL;

NULL = NULL evaluates to NULL (unknown), not TRUE. Always use IS NULL.

Mistake 3

AND when OR is needed for the same column

❌ Wrong
SELECT *
FROM students
WHERE city = 'Delhi'
  AND city = 'Mumbai';
✅ Correct
SELECT *
FROM students
WHERE city = 'Delhi'
  OR city = 'Mumbai';

A column can't equal two different values simultaneously. AND here returns 0 rows.

Mistake 4

Forgetting quotes around text values

❌ Wrong
SELECT *
FROM students
WHERE name = Priya;
✅ Correct
SELECT *
FROM students
WHERE name = 'Priya';

Without quotes, SQL reads Priya as a column name, not a text value — causing an error.

Mistake 5

Using WHERE with aggregate functions

❌ Wrong
SELECT class, COUNT(*)
FROM students
WHERE COUNT(*) > 10
GROUP BY class;
✅ Correct
SELECT class, COUNT(*)
FROM students
GROUP BY class
HAVING COUNT(*) > 10;

WHERE runs before GROUP BY, so it cannot see aggregate results. Filter groups with HAVING instead.

Mistake 6

Missing parentheses with mixed AND + OR

❌ Wrong
WHERE is_premium = 1
  AND city = 'Houston'
  OR city = 'Austin'
✅ Correct
WHERE is_premium = 1
  AND (city = 'Houston'
    OR city = 'Austin')

AND has higher precedence than OR. Without parentheses, the logic is applied in the wrong order.

Practice SQL WHERE Queries

Learn → Practice — write the queries yourself

These five exercises use the tables in the SQLabHub SQL Playground (products, employees, orders and users). Write each query yourself first, run it, then compare it with the solution.

  1. 1Find every product that costs less than 50.

    Show solution
    SELECT name, price
    FROM products
    WHERE price < 50;
  2. 2List employees whose salary is between 50000 and 80000.

    Show solution
    SELECT first_name, last_name, salary
    FROM employees
    WHERE salary BETWEEN 50000 AND 80000;
  3. 3Show orders that have not been shipped yet.

    Show solution
    SELECT id, order_date, status
    FROM orders
    WHERE shipped_date IS NULL;
  4. 4Find users with a Gmail address.

    Show solution
    SELECT first_name, email
    FROM users
    WHERE email LIKE '%@gmail.com';
  5. 5List products rated 4 or higher that are also priced under 100.

    Show solution
    SELECT name, price, rating
    FROM products
    WHERE rating >= 4
      AND price < 100;

📝 Quiz — SQL WHERE Clause

Test your understanding · 0/10 answered

Question 1 of 10

What does the WHERE clause do in SQL?

Question 2 of 10

Which SQL query correctly shows students with marks greater than 80?

Question 3 of 10

You want students in class 9 OR class 10. Which query is correct?

Question 4 of 10

Which operator would you use to find all product names starting with "A"?

Question 5 of 10

You want orders placed between Jan 1 and June 30, 2026. Which clause works?

Question 6 of 10

What happens if you use AND instead of OR — "WHERE class=10 AND marks>90"?

Question 7 of 10

Which query correctly finds employees with no manager (NULL manager_id)?

Question 8 of 10

You grouped students by class and want only classes with more than 5 students. Which clause do you use?

Question 9 of 10

Which LIKE pattern finds product names that contain "phone" anywhere?

Question 10 of 10

What is wrong with: WHERE city = 'Delhi' AND city = 'Mumbai'?

SQL WHERE Interview Questions

Beginner to intermediate — with model answers

These are the most frequently asked SQL WHERE clause interview questions. Whether you're preparing for a data analyst role, backend developer interview, or SQL assessment — knowing these cold will give you a significant edge. For questions beyond WHERE, see the full SQL interview questions guide.
Q1: What does the SQL WHERE clause do?
WHERE filters rows returned by a SELECT query. Only rows where the condition evaluates to TRUE are included. Rows where the condition is FALSE or NULL are excluded. It is evaluated before GROUP BY, HAVING, and ORDER BY.
Q2: What is the difference between WHERE and HAVING?
WHERE filters individual rows before GROUP BY aggregation. HAVING filters groups after GROUP BY. WHERE cannot use aggregate functions like COUNT() or SUM(); HAVING can. Use WHERE for row-level filters, HAVING for group-level filters.
Q3: Can the WHERE clause use aggregate functions like COUNT() or SUM()?
No. WHERE is evaluated before GROUP BY, so aggregate results don't exist yet when WHERE runs. Use the HAVING clause after GROUP BY to filter on aggregated values.
Q4: How do you filter NULL values using WHERE?
Use IS NULL to find rows with missing values and IS NOT NULL for rows with a value. Never use = NULL — NULL comparisons return NULL (not TRUE), so WHERE column = NULL always returns zero rows.
Q5: What is the difference between AND and OR in a WHERE clause?
AND requires all conditions to be true — it narrows the result (fewer rows). OR requires at least one condition to be true — it widens the result (more rows). When combining both, use parentheses to control evaluation order since AND has higher precedence than OR.
Q6: What is the IN operator and when should you use it?
IN matches a column value against a list of values. WHERE class IN (9, 10) is equivalent to WHERE class = 9 OR class = 10 but is cleaner and easier to read, especially with more values. The WHERE IN lesson goes deeper.
Q7: What wildcards does the LIKE operator support?
% matches any sequence of characters (including zero characters). _ matches exactly one character. Examples: LIKE 'A%' (starts with A), LIKE '%son' (ends with son), LIKE '%phone%' (contains phone), LIKE '_a%' (second character is a).
Q8: What does BETWEEN do in a WHERE clause?
BETWEEN filters values within an inclusive range. WHERE marks BETWEEN 80 AND 100 includes both 80 and 100 and everything in between. It works with numbers, dates, and text. It is equivalent to WHERE marks >= 80 AND marks <= 100.
Q9: What is the correct clause order in a SQL SELECT statement?
The required order is: SELECT → FROM → WHERE → GROUP BY → HAVING → ORDER BY. WHERE must come after FROM and before GROUP BY. Placing WHERE in the wrong position causes a syntax error.
Q10: Can WHERE filter on multiple columns at the same time?
Yes. Combine conditions on different columns using AND or OR. For example: WHERE class = 10 AND marks > 80 filters by both the class column and the marks column simultaneously.

Frequently Asked Questions

What does the SQL WHERE clause do?

The WHERE clause filters rows based on a condition. Only rows where the condition is TRUE are returned by a SELECT, or changed by an UPDATE or DELETE. Rows where the condition is FALSE or NULL are skipped. In a SELECT, WHERE runs after FROM and before GROUP BY, HAVING and ORDER BY.

Can WHERE be used with UPDATE and DELETE?

Yes. In an UPDATE or DELETE statement, WHERE decides which rows are changed or removed. Without a WHERE clause the statement applies to every row in the table, so always double-check the condition — running it as a SELECT first is a safe habit.

What is the difference between WHERE and HAVING?

WHERE filters individual rows before GROUP BY. HAVING filters groups after aggregation, so it can use functions like COUNT(*) or SUM(amount) and WHERE cannot. Use WHERE to exclude rows early, and HAVING only for conditions on aggregated results. See the SQL HAVING lesson for worked examples.

How do I check for NULL values in a WHERE clause?

Use IS NULL or IS NOT NULL. Never use = NULL — it returns zero rows because any comparison with NULL evaluates to NULL (unknown), not TRUE. Example: WHERE email IS NULL finds customers with no email address on file.

Can I use a column alias in a WHERE clause?

No. WHERE is evaluated before the SELECT list, so an alias defined with AS does not exist yet when WHERE runs. Repeat the original expression in WHERE, or wrap the query in a subquery and filter on the alias in the outer query.

Is the SQL WHERE clause case-sensitive?

SQL keywords such as WHERE are not case-sensitive. Whether text comparisons like WHERE city = 'delhi' are case-sensitive depends on the database and its collation: PostgreSQL compares text case-sensitively by default, while MySQL and SQL Server are case-insensitive under their default collations.

How do I filter by multiple values in a WHERE clause?

Use the IN operator. WHERE class IN (9, 10) is shorter and easier to read than WHERE class = 9 OR class = 10, especially as the list grows. The WHERE IN lesson covers NOT IN and subqueries.

How does the LIKE operator work in a WHERE clause?

LIKE matches text against a pattern: % matches any sequence of characters and _ matches exactly one character. For example, LIKE 'A%' finds values that start with A and LIKE '%son' finds values that end with son. The SQL LIKE operator lesson has more patterns.

Where can I practice SQL WHERE clause queries?

Write and run queries in the free SQL Playground, or work through the SQL challenges for structured problems that use WHERE filters on realistic datasets.