How do AND, OR and NOT combine, and what happens if I mix them without parentheses?
SQL uses standard boolean algebra with the same precedence rules you would expect from mathematics: NOT binds tightest, then AND, then OR. So a OR b AND c is parsed as a OR (b AND c), not as (a OR b) AND c. That is exactly the reading people get wrong, and it silently returns more rows than intended.
CREATE TABLE tickets (
id INTEGER PRIMARY KEY,
title VARCHAR(160) NOT NULL,
priority INTEGER NOT NULL,
status VARCHAR(20) NOT NULL,
assigned_to INTEGER
);
INSERT INTO tickets (id, title, priority, status, assigned_to) VALUES
(1, 'Login page times out', 3, 'open', 11),
(2, 'Invoice PDF is blank', 2, 'open', 12),
(3, 'Export times out', 1, 'open', 11),
(4, 'Dark mode request', 1, 'closed', 12),
(5, 'Slow search results', 3, 'closed', 11);
-- Reads as: status = 'open' OR (priority = 1 AND assigned_to = 11)
SELECT id, title FROM tickets
WHERE status = 'open' OR priority = 1 AND assigned_to = 11
ORDER BY id;Three rows come back: tickets 1, 2 and 3. Ticket 2 leaks in because the first branch is TRUE on its own — it is open, regardless of priority or owner. Tickets 4 and 5 are excluded: ticket 4 is priority 1 but assigned to engineer 12, so the AND branch is FALSE, and ticket 5 is neither open nor priority 1.
The intended question was "tickets that are open or urgent, and that belong to engineer 11", which needs the parentheses on the other side: WHERE (status = 'open' OR priority = 1) AND assigned_to = 11. That version returns only tickets 1 and 3 — ticket 2 drops out because engineer 12 owns it, and ticket 4 drops out because it is closed and not engineer 11's.
Rule of thumb: add parentheses whenever you write both AND and OR in the same predicate, even when you are sure of the precedence. It costs nothing and it removes the need for the reader to reconstruct the parse.