Twelve Small Wins When Writing WHERE Clauses

The WHERE clause decides which rows a query touches, so small mistakes in it have big effects. These twelve tips each fix a common beginner slip, with a short reason.

Tips

1. Use brackets when mixing AND and OR. WHERE (city = 'Leeds' OR city = 'York') AND age > 18. Why: AND is evaluated before OR, so without brackets the meaning changes.

2. Use IS NULL, not = NULL. WHERE phone IS NULL. Why: = NULL is never true, because NULL means unknown.

3. Remember NULL hides from comparisons. WHERE age <> 30 skips rows where age is NULL. Why: unknown values are neither equal nor unequal.

4. Use IN for lists. WHERE status IN ('new', 'paid'). Why: shorter and clearer than chains of OR.

5. Know that BETWEEN includes both ends. WHERE age BETWEEN 18 AND 30 includes 18 and 30. Why: people often assume it excludes the end.

6. Use half-open ranges for dates. WHERE placed_at >= '2026-03-01' AND placed_at < '2026-04-01'. Why: it includes the whole last day, whatever the time of day.

7. Use LIKE with care. 'Ann%' means "starts with Ann"; '%ann%' means "contains ann". Why: knowing the wildcards prevents surprising matches.

8. Check case sensitivity. Whether 'ann' matches 'Ann' depends on the database and settings. Why: SQLite's LIKE ignores case for plain English letters by default, PostgreSQL's LIKE does not (it has ILIKE), and MySQL depends on collation.

9. Compare like with like. Compare numbers with numbers and text with text. Why: mixing them can cause odd results or slow queries.

10. Keep the column on its own side. Prefer WHERE price > 100 / 1.2 style rewrites over WHERE price * 1.2 > 100 when you can. Why: a plain column is easier for the database to match against an index later.

11. Use placeholders for values from users. WHERE email = ?. Why: it prevents SQL injection.

12. Test the WHERE with SELECT before UPDATE or DELETE. Why: you see exactly which rows will be affected.

Quick reference

GoalWrite
Missing valueIS NULL
One of several valuesIN (...)
Inclusive rangeBETWEEN a AND b
Date range>= start AND < next_start
Starts withLIKE 'abc%'
Mix of AND and ORBrackets around the OR part

A practice exercise

Take a sample table and write a query for each row of the quick reference. Then deliberately break one, for example remove the brackets in tip 1, and compare the results. Seeing the difference fixes the rule in memory.

Where next

Training notes on filtering and sorting with WHERE and ORDER BY go into more detail, and NULL explained covers tips 2 and 3 thoroughly.

A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.