AND, OR, and NOT

Basic SQL
≈ 1 min read

Several conditions can be combined

When one comparison is not enough, conditions are combined with logical operators. AND requires both parts to be satisfied, OR requires at least one, and NOT negates a condition.

SELECT name, price
FROM products
WHERE price >= 1000
  AND available = TRUE;

Only available products priced at 1000 or more appear in the result. If either part of the condition is not satisfied, the row is excluded.

Parentheses make logic explicit

SELECT name
FROM products
WHERE (category = 'book' OR category = 'course')
  AND available = TRUE;

The parentheses make it explicit that either of the two categories is acceptable first, and then availability is additionally required for those rows.

Do not rely on memory of operator precedence. AND normally has higher precedence than OR. When an expression mixes them, parentheses almost always make the intention clearer and reduce the risk of mistakes.