Filtering rows with WHERE in SQL
Topic 3 of 45 · 9 minFree lessonTables can hold millions of rows, and you rarely want them all. WHERE keeps only the rows that match a condition you write. Everything else is left out of the answer.
Keeping the rows that match
Put WHERE after the table's name, followed by a condition. Here, only products in the herbs category come back.
SELECT name, category, priceFROM productsWHERE category = 'herbs';Text values go in single quotes: 'herbs'. The = means "is equal to".
Comparing numbers
Numbers don't need quotes. You can compare them with < (less than), > (more than), <= and >=.
SELECT name, priceFROM productsWHERE price < 8;Only products cheaper than 8 come back. A product costing exactly 8 isn't included: for that you'd write price <= 8.
Not equal
<> means "is not equal to". PostgreSQL also accepts !=, which means the same.
SELECT id, ordered, statusFROM ordersWHERE status <> 'delivered';Comparing dates
Dates are written in quotes as year-month-day: '2025-03-01'. Comparing them works like comparing numbers, where later dates count as bigger.
SELECT name, joinedFROM customersWHERE joined >= '2025-01-01';These are the customers who joined on or after the first of January, 2025.
Text must match exactly
Text comparisons care about capitals and spaces. 'Herbs' with a capital H matches nothing, because every category is stored in lowercase.
SELECT nameFROM productsWHERE category = 'Herbs';An answer with no rows isn't an error. It means no row matched the condition.
Lisbon.SELECT name FROM customers WHERE city = "Lisbon";Use single quotes for text: 'Lisbon'.
WHERE on its own line. When a query gets longer, you can see straight away which rows it keeps.Try it yourself
Run the code in the editor and answer 8 practice questions on filtering rows with where. It's free, you only need an account.