Phase 1 · Reading data: SELECT, WHERE and sorting · Topic 1.2

WHERE: keeping only the rows you want

Must know

WHERE keeps only the rows for which a condition is true, using comparisons such as =, <>, <, > and the words AND, OR and NOT.

Not started

Step 1 Understand it

Why you need it. hold every ever stored, and you almost always want a slice: one department, orders over £100, everyone hired this year. is how you say which rows count.

New words in this topic (tap one to see what it means)

Watch it happen

AnimationWHERE keeps the rows where the condition is true
Read the animation as text
  1. WHERE checks a condition against every row and keeps only the rows where it is true.
  2. First test, dept_id = 1, on each row. For Gus it is unknown (?): NULL = 1 is neither true nor false.
  3. Second test, salary < 90000. Asha passes the first test but fails this one.
  4. AND needs both to be true. Only Ben, Chen and Hana have two ticks. Everyone else is dropped — including Gus, whose "unknown" is not true.
  5. The result: Ben, Chen, Hana. SELECT and ORDER BY then work only on these rows.

Picture it

flowchart LR
  R["every row of employees"] --> C{"dept_id = 1<br/>AND salary under 90000?"}
  C -->|"true"| K["kept:<br/>Ben, Chen, Hana"]
  C -->|"false or unknown"| D["dropped:<br/>Asha and the rest"]
WHERE is a filter: each row is tested one at a time. Only rows where the condition is true go through. False and unknown are both dropped.

The idea

A condition is a statement about a row that is either true or false, like salary > 60000. The checks it against every row and keeps the rows where it is true. You can combine conditions: needs both to be true, OR needs at least one, and NOT flips true and false. are =, <> (not equal; != also works), <, <=, > and >=. Text values go in single quotes.

The shape of it

sql
SELECT columns
FROM table_name
WHERE condition AND (other OR another);

Words in lower case are the parts you fill in.

How it works, step by step

  1. takes every row of employees.
  2. WHERE checks the condition dept_id = 1 AND salary < 90000 on each row.
  3. Asha: department 1 is true, but 95000 < 90000 is false. Both must be true for AND, so Asha is dropped.
  4. Ben, Chen and Hana pass both tests, so they are kept. Everyone outside department 1 fails the first test.
  5. then picks the from the rows that are left.
  6. AND is worked out before OR, just as × comes before + in maths. Use brackets whenever you mix them.

Analogy

A bouncer with a list of rules. Every row walks up to the door; if it passes the rules, it gets in. "Over 18 AND on the guest list" is stricter than "over 18 OR on the guest list".

Where the analogy breaks

A bouncer answers yes or no. has a third answer, unknown, which comes from — and WHERE treats unknown the same as no. The NULL lesson next in this phase shows why that matters.

Worked examples

Two conditions with AND

sql
SELECT name, salary
FROM employees
WHERE dept_id = 1 AND salary < 90000
ORDER BY name;

3 rows

namesalary
Ben70000
Chen70000
Hana80000

Asha is in department 1 but fails the salary test, and AND needs both tests to pass.

OR inside brackets

sql
SELECT name, dept_id, salary
FROM employees
WHERE (dept_id = 2 OR dept_id = 3) AND salary > 50000
ORDER BY name;

2 rows

namedept_idsalary
Dara260000
Fatima352000

Read it as: in department 2 or 3, and also earning over 50000. Eli is in department 2 but earns 45000.

The same without brackets — a different answer

sql
SELECT name, dept_id, salary
FROM employees
WHERE dept_id = 2 OR dept_id = 3 AND salary > 50000
ORDER BY name;

3 rows

namedept_idsalary
Dara260000
Eli245000
Fatima352000

AND is worked out first, so this means: department 2 (any salary), or department 3 with a salary over 50000. Eli sneaks in. Brackets remove the doubt.

Must-know points

  • WHERE runs on each row, before any grouping, and keeps only rows where the condition is true.
  • Comparisons: =, <> (or !=), <, <=, >, >=. One = sign, not two.
  • AND needs both sides true; OR needs at least one; NOT flips the answer.
  • AND binds tighter than OR. Put brackets around every OR that is mixed with AND.
  • Text goes in single quotes and must match exactly: 'Sales' is not 'sales' in most databases.

Common mistakes

  • Mixing AND and OR without brackets, and getting extra rows.
  • Writing ==. SQL uses a single = for comparing.
  • Writing WHERE dept_id = 2 OR 3. Each side of OR must be a full condition: dept_id = 2 OR dept_id = 3, or better, dept_id IN (2, 3).

In other databases

  • Text comparison: is case-sensitive ('Sales' ≠ 'sales'); and usually are not, depending on settings; in = is case-sensitive but is not.

Step 2 Go further (free, optional)

Optional. The notes above are written to be enough on their own. These free resources give a second explanation and more practice.

Step 3 Practise

Try each one yourself first: out loud, or written and run in the practice box below, which saves every query you run. Then open the answer and compare.

  1. ExplainSay what it does and when to use it, in plain words, with no notes.

    Explain the difference between AND and OR with an example from the orders table.

    Show answer

    AND needs both conditions to be true. OR needs at least one.

    WHERE status = 'delivered' AND amount > 100 returns orders that are both delivered and over £100: just 101 and 104.

    WHERE status = 'delivered' OR amount > 100 returns orders that are either: all 7 delivered orders, plus 105, which is only shipped but is over £100. That makes 8.

    So AND makes the result smaller, and OR makes it bigger.

  2. Writefrom a blank page, then run it

    Write a query for orders that are delivered and worth at least £75, showing order_id and amount, sorted by order_id.

    Show answer

    "At least £75" includes £75, so use >=. Order 108 is exactly £75; with > it would be missed.

    sql
    SELECT order_id, amount
    FROM orders
    WHERE status = 'delivered' AND amount >= 75
    ORDER BY order_id;

    4 rows

    order_idamount
    101120
    10280
    104200
    10875
  3. Predictsay it before you run it

    Which names does SELECT name FROM employees WHERE NOT dept_id = 1 ORDER BY name; return? Is Gus in the list?

    Show answer

    Dara, Eli and Fatima. Gus is not in the list.

    Gus's dept_id is NULL. dept_id = 1 is unknown for him, and NOT unknown is still unknown, not true. WHERE keeps only true rows, so he is dropped. To include him, add OR dept_id IS NULL.

    sql
    SELECT name
    FROM employees
    WHERE NOT dept_id = 1
    ORDER BY name;

    3 rows

    name
    Dara
    Eli
    Fatima
  4. Edge casesSay what happens with NULLs, ties, duplicates or no rows at all, and fix it.

    Rewrite WHERE status = 'shipped' OR status = 'pending' AND amount > 40 so it means "shipped or pending, and over £40". What did the original return?

    Show answer

    Add brackets around the OR: WHERE (status = 'shipped' OR status = 'pending') AND amount > 40.

    AND is worked out before OR, so the original really meant "shipped (any amount), or pending and over £40".

    Here both versions return only order 105. That is luck: the only shipped order is £150, and the only pending one (110) is £33. If a shipped order were £20, the original would wrongly include it. The brackets make the query say what you mean, whatever the data.

    sql
    SELECT order_id, status, amount
    FROM orders
    WHERE (status = 'shipped' OR status = 'pending') AND amount > 40
    ORDER BY order_id;

    1 row

    order_idstatusamount
    105shipped150

Practice box: write and run your answers here

Ctrl/⌘ + Enter runs it. Select part of the query to run only that part.

Step 4 Interview-ready, then prove it

Your interview answer

About 20 to 40 seconds, said out loud.

WHERE filters rows before any grouping: the database evaluates the condition for each row and keeps only those where it is true — false and unknown are both dropped. I combine conditions with AND, OR and NOT, and because AND has higher than OR, I always bracket OR conditions when mixing them, so the query says exactly what I mean.

Follow-up questions

Which is evaluated first, AND or OR?

AND. a OR b AND c means a OR (b AND c). Brackets make it explicit.

Can WHERE use a column from SELECT?

No in standard SQL, because WHERE runs before SELECT. Repeat the , or wrap the query in a or . (SQLite and MySQL are lenient about this; don't rely on it.)

Tick each check when you can do it without notes

A topic is finished when you pass all four checks, not when you have read it. Be strict: if you had to look at the notes, it is not ticked yet.

  • Explain Say what it does and when to use it, in plain words, with no notes.
  • Write Write the query from a blank page, then run it to check.
  • Predict Read a query and say which rows it returns before you run it.
  • Edge cases Say what happens with NULLs, ties, duplicates or no rows at all, and fix it.

0 of 4 checks ticked.

Saved in this browser. Back it up or move it to another device.