Hone

Lessons · SQL · AND narrows the rows

Both conditions at once

WHERE a AND b keeps only rows where both are true. A row that fails either one, or where either is NULL, is out.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Customers in London who joined this year, orders that are paid and over a limit: nearly every real filter is two conditions joined with AND.

How to think about it

Write each condition so it is true on its own for the rows you want, then join them with AND. Remember that a NULL in either side makes the whole test not-true, so those rows drop out too.

Worked example

SELECT name FROM customers
What to show.
WHERE city = 'London' AND active = 1;
Both must hold: in London, and active. A NULL city fails the first test and the row is out.

Your turn

Paid orders over 100.

SELECT id FROM orders WHERE status = 'paid'  amount > 100;

The trap

AND binds tighter than OR. a OR b AND c means a OR (b AND c); put parentheses around the OR when you mean (a OR b) AND c.

Practise AND narrows the rows on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.