SQL · Module 4 · Lesson 21 min read

Filtering with WHERE

Syntax

SQL
SELECT columns FROM table WHERE condition;

Only rows where the condition is true are returned (false and NULL are both filtered out).

Comparison operators

OperatorMeaning
=equal
<> or !=not equal
<, >less than, greater than
<=, >=less/greater than or equal

Comparing different types

  • Numbers: amount > 1000
  • Text (case-sensitive, alphabetical): city = 'Pokhara', name < 'M'
  • Dates (in quotes, ISO format): spent_on >= '2026-11-01'
  • Booleans: WHERE paid, WHERE NOT paid, WHERE paid = false

WHERE works on rows, before SELECT

  • You can't use a column alias from SELECT in WHERE (WHERE runs first — see lesson 4.7)
  • You can filter on columns you don't select

WHERE in UPDATE and DELETE

The same conditions decide which rows are changed or removed — another reason to master it.

Performance tip

Filtering on columns with an index (Unit 11) is very fast. Avoid wrapping indexed columns in functions in WHERE (WHERE lower(email) = …) unless there's a matching expression index.

Example

SQL
-- Equal
SELECT name, city FROM users WHERE city = 'Pokhara';
-- Ravi Thapa, Maya Karki

-- Not equal
SELECT title, amount FROM expenses WHERE category_id <> 7 AND user_id = 1;

-- Greater than
SELECT title, amount FROM expenses WHERE amount > 5000;
-- Running shoes 6500, Monthly groceries 5200, Paragliding 8500, Flight to Pokhara 7800

-- Dates
SELECT title, spent_on FROM expenses WHERE spent_on >= '2026-11-01' AND user_id = 3;

-- Booleans
SELECT title, amount, due_date FROM bills WHERE NOT paid;

-- Text is case-sensitive
SELECT count(*) FROM users WHERE city = 'kathmandu';   -- 0
SELECT count(*) FROM users WHERE city = 'Kathmandu';   -- 2

-- ❌ Aliases can't be used in WHERE:
-- SELECT amount * 1.13 AS with_vat FROM expenses WHERE with_vat > 5000;
-- ✅ Repeat the expression instead:
SELECT title, amount * 1.13 AS with_vat FROM expenses WHERE amount * 1.13 > 5000;