Explain it simply
Explain it simply
Picture the filter panel of an online shop. Tick both "Phone" and "In stock" and you only see items that satisfy both: that is AND. Tick "Samsung" and "Apple" in the brand list and you see items matching either one: that is OR. "Hide refurbished" is NOT.
In SQL you join several conditions inside one WHERE clause with these three keywords. AND narrows the result (fewer rows survive), OR widens it (more rows survive), and NOT flips the answer of a single condition.
Problem → Why → Solution
The problem: one missing pair of parentheses changes the result
The sales team asks for "customers in Mexico or Germany, but not the ones in Mexico City". Writing the sentence down left to right gives the query below. It raises no error and returns four rows, yet both Mexico City customers are still in the result: the exclusion simply did not happen.
SELECT customer_name, city, country
FROM customers
WHERE country = 'Mexico'
OR country = 'Germany' AND NOT city = 'Mexico City';
-- Returns Ana Trujillo and Antonio Moreno (both in Mexico City!)Why do the Mexico City rows come back?
SQL groups AND before OR, so PostgreSQL reads this WHERE as country = 'Mexico' OR (country = 'Germany' AND NOT city = 'Mexico City'). The "not Mexico City" rule sticks to the Germany branch only, and every Mexico row walks straight through the first condition. Only (country = 'Mexico' OR country = 'Germany') in parentheses expresses what was asked.
Core concept: every condition yields TRUE, FALSE or NULL
A WHERE clause evaluates one boolean expression per row and keeps only the rows where it comes out TRUE. AND is TRUE when both sides are TRUE; OR is TRUE when at least one side is TRUE; NOT turns TRUE into FALSE and FALSE into TRUE. So far this is the same logic you know from any programming language.
The first difference is precedence. Without parentheses PostgreSQL applies NOT first, then AND, and OR last, much like multiplication binds tighter than addition. So a OR b AND c means a OR (b AND c), not (a OR b) AND c. Whenever a query mixes AND with OR, put parentheses around the group you mean; it protects both you and the next person who reads the query.
The second difference is NULL. In SQL a condition can be TRUE, FALSE or NULL (unknown). If country is NULL, country = 'Mexico' yields NULL, and NOT (NULL) is still NULL. Because WHERE keeps only TRUE, that row disappears from the condition and from its opposite. Also note that TRUE OR NULL is TRUE and FALSE AND NULL is FALSE: when the answer is already certain, the unknown side cannot change it.
| a and b | a AND b | a OR b |
|---|---|---|
| TRUE, TRUE | TRUE | TRUE |
| TRUE, FALSE | FALSE | TRUE |
| TRUE, NULL | NULL | TRUE |
| FALSE, NULL | FALSE | NULL |
| NULL, NULL | NULL | NULL |
One last caution: unlike most programming languages, SQL does not promise left-to-right short-circuit evaluation. PostgreSQL's planner may evaluate conditions in whatever order it likes, so never rely on the left condition to guard an expression on the right that could raise an error.
- Take one row
- Apply NOT first
- Then AND, then OR
- Keep the row only if TRUE
FALSE and NULL both drop the row; anything in parentheses is evaluated first.
General pattern
SELECT column_list
FROM table_name
WHERE (condition_a OR condition_b)
AND condition_c
AND NOT condition_d;
-- shorthand for several ORs on one column
WHERE column_name IN (value_1, value_2, value_3)Put the OR group in parentheses and attach the remaining rules with AND. One condition per line makes the WHERE easy to read and easy to comment out while debugging. When the ORs all test the same column, IN (...) says the same thing more briefly.
Example: customers in two countries, minus Mexico City
Every example runs on the six-row customers table below. Notice that Cactus Comidas has a NULL country (not recorded yet); that row causes trouble in the deeper section. The first query uses a single OR; the second wraps the OR group in parentheses and attaches AND NOT.
CREATE TABLE customers (
customer_id integer PRIMARY KEY,
customer_name text NOT NULL,
city text,
country text
);
INSERT INTO customers VALUES
(1, 'Alfreds Futterkiste', 'Berlin', 'Germany'),
(2, 'Ana Trujillo', 'Mexico City', 'Mexico'),
(3, 'Antonio Moreno', 'Mexico City', 'Mexico'),
(4, 'Around the Horn', 'London', 'UK'),
(5, 'Blauer See Delikatessen', 'Mannheim', 'Germany'),
(6, 'Cactus Comidas', 'Buenos Aires', NULL);-- Customers in either country
SELECT customer_name, city, country
FROM customers
WHERE country = 'Mexico' OR country = 'Germany'
ORDER BY customer_id;
-- Either country, but not in Mexico City
SELECT customer_name, city, country
FROM customers
WHERE (country = 'Mexico' OR country = 'Germany')
AND NOT city = 'Mexico City'
ORDER BY customer_id;Code breakdown
- OR
WHERE country = 'Mexico' OR country = 'Germany'A row survives if either condition is TRUE. The UK customer and Cactus Comidas, whose country is NULL, match neither and drop out.
- ORDER BY
ORDER BY customer_id;Without ORDER BY PostgreSQL does not promise any row order. Sorting by customer_id keeps the output stable and easy to compare; the next lesson covers ORDER BY in depth.
- Parentheses
WHERE (country = 'Mexico' OR country = 'Germany')The parentheses turn the OR group into one unit. Without them, AND would bind to the Germany condition alone and bring back the bug from the problem section.
- AND NOT
AND NOT city = 'Mexico City'NOT flips the answer of city = 'Mexico City', and AND applies that rule to the whole OR group. Writing city <> 'Mexico City' means exactly the same.
customer_name | city | country
-------------------------+-------------+---------
Alfreds Futterkiste | Berlin | Germany
Ana Trujillo | Mexico City | Mexico
Antonio Moreno | Mexico City | Mexico
Blauer See Delikatessen | Mannheim | Germany
(4 rows)
customer_name | city | country
-------------------------+----------+---------
Alfreds Futterkiste | Berlin | Germany
Blauer See Delikatessen | Mannheim | Germany
(2 rows)- Evaluate the OR group in parentheses
- Evaluate NOT city = 'Mexico City'
- Combine both results with AND
TRUE
Row is returned
FALSE or NULL
Row is filtered out
NOT and NULL: the row that vanishes
You would expect "every customer not in Mexico" to include Cactus Comidas; after all, it is not in Mexico. But its country is NULL, so NOT country = 'Mexico' evaluates to NULL and the row is dropped. When you want such rows, use IS DISTINCT FROM: it compares NULL like an ordinary value and always returns TRUE or FALSE.
-- 3 rows: Cactus Comidas (country NULL) is missing
SELECT customer_name, country
FROM customers
WHERE NOT country = 'Mexico';
-- 4 rows: NULL counts as "different from Mexico"
SELECT customer_name, country
FROM customers
WHERE country IS DISTINCT FROM 'Mexico';NOT IN and NULL
IN behaves like a chain of ORs and NOT IN like a chain of ANDs. So if the list contains a single NULL, x NOT IN (1, NULL) can never be TRUE and the query returns no rows at all. This happens most often when the list comes from a subquery.
In real projects
Where this shows up in real projects
On an e-commerce search page every filter the user picks becomes one condition in the WHERE clause: OR (usually written as IN) between categories, plus AND for the price range, in_stock and "not discontinued". When backend code assembles these filters, forgetting to wrap the OR group is the classic bug: ticking one more filter suddenly returns more rows instead of fewer.
In multi-tenant apps the same bug becomes a security hole. WHERE tenant_id = $1 AND status = 'open' OR status = 'pending' leaks every pending record from every other company. That is why many teams keep the tenant or owner check as its own top-level AND and always put user-driven filters inside parentheses. In admin reports, a "not deleted" rule on a nullable column is safer written as IS NOT TRUE.
Common mistakes
Common mistakes
1. Mixing AND and OR without parentheses
WHERE category = 'phone' OR category = 'laptop' AND in_stock applies the stock check to laptops only, so every out-of-stock phone comes back. Write WHERE (category = 'phone' OR category = 'laptop') AND in_stock, or category IN ('phone', 'laptop') AND in_stock.
2. Expecting NOT to include NULL rows
WHERE NOT discontinued silently drops products whose discontinued flag is NULL (not reviewed yet), because NOT NULL is NULL. To treat NULL like FALSE, write discontinued IS NOT TRUE; for text columns use IS DISTINCT FROM.
3. Testing one column against two values with AND
WHERE country = 'Mexico' AND country = 'Germany' returns zero rows, because a single row's country cannot hold two values at once. In speech we say "customers from Mexico and Germany", but SQL needs OR or IN.
Best practices
Best practices
- Add parentheses every time you mix AND with OR, even when you remember the precedence: it is for the reader.
- Replace ORs on one column with IN (...).
- Before using NOT on a nullable column, decide whether NULL rows belong in the result and pick IS DISTINCT FROM or IS NOT TRUE.
- Write one condition per line and check the row count against a prediction you made by hand.
Mini challenge
Mini challenge: a shop filter
Turn a user's filter into one SQL query on the products table: laptop or phone, in stock, priced under 1000, and not discontinued (a NULL flag means the product is still on sale).
- Show the name, category and price columns
- Wrap the category OR group in parentheses (or use IN)
- Phone Max, whose discontinued flag is NULL, must be in the result
- Sort by price, lowest first
CREATE TABLE products (
product_id integer PRIMARY KEY,
name text NOT NULL,
category text NOT NULL,
price numeric(8, 2) NOT NULL,
in_stock boolean NOT NULL,
discontinued boolean -- NULL = not reviewed yet
);
INSERT INTO products VALUES
(1, 'Laptop Air 13', 'laptop', 899.00, true, false),
(2, 'Laptop Pro 16', 'laptop', 1899.00, true, false),
(3, 'Phone Mini', 'phone', 499.00, false, false),
(4, 'Phone Max', 'phone', 999.00, true, NULL),
(5, 'Tablet 10', 'tablet', 349.00, true, false),
(6, 'Phone Classic', 'phone', 199.00, true, true);
-- TODO: laptops OR phones (mind the parentheses)
-- TODO: in stock and cheaper than 1000
-- TODO: not discontinued, but keep rows where discontinued IS NULL
-- TODO: cheapest first
SELECT name, category, price
FROM products;Expected: Two rows: Laptop Air 13 (899.00) and Phone Max (999.00). Laptop Pro 16 is too expensive, Phone Mini is out of stock, Phone Classic is discontinued and Tablet 10 is the wrong category.
Show hint
Writing NOT discontinued makes Phone Max disappear. Use IS NOT TRUE to treat a NULL boolean like FALSE.
Show solution
SELECT name, category, price
FROM products
WHERE (category = 'laptop' OR category = 'phone')
AND in_stock
AND price < 1000
AND discontinued IS NOT TRUE
ORDER BY price;Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- AND narrows the result, OR widens it, NOT flips one condition.
- Precedence is NOT, then AND, then OR: add parentheses whenever AND and OR meet.
- WHERE keeps only TRUE, so a row that evaluates to NULL vanishes from a condition and from its opposite.
- Use IN for ORs on one column, and keep NULLs out of NOT IN lists.
PostgreSQL SQL Tutorial — PostgreSQL Global Development Group