π± BasicsbeginnerCommonly used
How to filter rows with WHERE in SQL
Filter query results to only return rows that match a condition.
Table schema used in examplesβ A users table
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT,
email TEXT,
age INTEGER,
country TEXT,
active BOOLEAN
);Filter by exact valueAll databases
SELECT name, email
FROM users
WHERE country = 'Kenya';Returns only rows where country equals "Kenya". String values use single quotes.
Filter by numberAll databases
SELECT name, age
FROM users
WHERE age >= 18;Returns users aged 18 or older. Numeric comparisons do not use quotes.
Multiple conditions with ANDAll databases
SELECT name, age, country
FROM users
WHERE country = 'Kenya'
AND age >= 18
AND active = true;All conditions must be true for a row to be included.
Either condition with ORAll databases
SELECT name, country
FROM users
WHERE country = 'Kenya'
OR country = 'Nigeria';Returns rows where either condition is true.
For many OR conditions on the same column, use IN instead.
Negate with NOTAll databases
SELECT name, country
FROM users
WHERE NOT country = 'Kenya';Returns rows where the condition is false. Equivalent to country != 'Kenya'.
Not equalAll databases
SELECT name, country
FROM users
WHERE country != 'Kenya';
-- or
WHERE country <> 'Kenya';Both != and <> mean "not equal". Both work in most databases.
Common Mistakes
- βUsing = NULL instead of IS NULL (NULL comparisons always use IS NULL)
- βForgetting operator precedence β AND is evaluated before OR. Use parentheses to be explicit.
- βUsing double quotes for strings β use single quotes for string values