Tricky SQL Problems and How to Solve Them
Solutions to SQL problems that trip people up: relational division, pairs bought together, finding changed rows when NULLs are involved, all/none/some conditions, comparing two lists both ways, custom sort orders and the SUM(DISTINCT) trap.
kvi5hnuCode Sprout team member9 min readOn this page
Some questions sound simple in English but have no obvious SQL shape: "customers who bought every product on a list", "which products are bought together", "which rows changed", "customers whose orders were all shipped". Each has a well-known solution, and once you know the pattern, you'll recognise it again in other forms.
This article collects these problems. Each section states the problem, shows the solution on the shop database, and explains the trap that makes it tricky.
Relational division: "every item on a list"
Find the customers who have bought both the Glow head torch and the Merino socks. A plain WHERE product_id IN (3, 7) finds customers who bought either. "Every item on a list" is called relational division, and it has two classic solutions:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Relational division: customers who bought EVERY product on a list
-- The list: the Glow head torch (3) and the Merino socks (7)
-- 1. Count matches: the number of distinct listed products bought equals the list's size
WITH wanted (product_id) AS (VALUES (3), (7))
SELECT c.name
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
JOIN order_items oi ON oi.order_id = o.order_id
WHERE oi.product_id IN (SELECT product_id FROM wanted)
GROUP BY c.customer_id, c.name
HAVING COUNT(DISTINCT oi.product_id) = (SELECT COUNT(*) FROM wanted)
ORDER BY c.name;
-- 2. Double negation: customers for whom no listed product exists that they haven't bought
WITH wanted (product_id) AS (VALUES (3), (7))
SELECT c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1 FROM wanted w
WHERE NOT EXISTS (
SELECT 1
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.customer_id = c.customer_id
AND oi.product_id = w.product_id))
ORDER BY c.name;
name
----------
Asha Rao
(1 row)
name
----------
Asha Rao
(1 row)

- Count the matches. Keep only purchases of listed products, group by customer, and require the number of distinct listed products bought to equal the size of the list.
DISTINCTmatters: Asha bought socks twice, and counting rows would credit two matches for one product. - Double negation. "Bought every listed product" is the same as "there's no listed product that they haven't bought":
NOT EXISTS (listed product WHERE NOT EXISTS (purchase of it)). It reads awkwardly, but it's a direct translation of the logic.
Only Asha qualifies. The two methods differ in one edge case: with an empty list, the count method returns nobody, while double negation returns every customer, because "no listed product is missing" is true for everyone. Decide which answer an empty list should give.
A variant is exact division: customers who bought the listed products and nothing else. With the count method, drop the WHERE ... IN filter and require both COUNT(DISTINCT product_id) = list size and every product to be in the list: HAVING COUNT(DISTINCT oi.product_id) FILTER (WHERE oi.product_id NOT IN (3, 7)) = 0.
Pairs: bought together, and symmetric pairs
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Products bought together: each unordered pair once, counted across orders
SELECT a.product_id AS product_a, b.product_id AS product_b,
pa.name AS name_a, pb.name AS name_b,
COUNT(*) AS orders_together
FROM order_items a
JOIN order_items b ON b.order_id = a.order_id
AND a.product_id < b.product_id -- each pair once, never a product with itself
JOIN products pa ON pa.product_id = a.product_id
JOIN products pb ON pb.product_id = b.product_id
GROUP BY a.product_id, b.product_id, pa.name, pb.name
ORDER BY orders_together DESC, product_a, product_b;
-- Normalising symmetric pairs: (x, y) and (y, x) are the same pair
SELECT LEAST(a, b) AS first, GREATEST(a, b) AS second, COUNT(*) AS times_reported
FROM (VALUES (3, 7), (7, 3), (1, 7), (3, 7)) AS reports(a, b)
GROUP BY LEAST(a, b), GREATEST(a, b)
ORDER BY first, second;
product_a | product_b | name_a | name_b | orders_together
-----------+-----------+-------------------+-------------------+-----------------
1 | 7 | Ridge 2 tent | Merino socks | 1
3 | 5 | Glow head torch | Trail 30 backpack | 1
3 | 7 | Glow head torch | Merino socks | 1
5 | 7 | Trail 30 backpack | Merino socks | 1
(4 rows)
first | second | times_reported
-------+--------+----------------
1 | 7 | 1
3 | 7 | 3
(2 rows)
Products bought together is a self-join (article 14) of order lines on the same order. The condition a.product_id < b.product_id does two jobs: it stops a product pairing with itself, and it reports each pair once. With <> instead, every pair would appear twice, as (3, 7) and (7, 3). This is the start of "market basket" analysis, as in "customers who bought this also bought".
Symmetric pairs turn up when the same relationship is recorded in either direction: friendships, matches between two players, two products reported as duplicates. (3, 7) and (7, 3) should count as one pair. LEAST(a, b) and GREATEST(a, b) (article 47) put every pair into a standard order, smallest first, so the two directions group together: the pair 3 and 7 was reported three times.
The same normalisation stops duplicates being stored in the first place: a unique index on (LEAST(a, b), GREATEST(a, b)) rejects (7, 3) when (3, 7) exists.
Finding changed rows, with NULLs
Two versions of a table, such as yesterday's copy and today's, need comparing: which rows changed? The obvious old.col <> new.col gets NULLs wrong:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
\pset null '(null)'
-- Which rows changed between two versions of a table? NULLs make <> unreliable
CREATE TABLE products_v2 AS SELECT * FROM products;
UPDATE products_v2 SET brand = 'Lumen' WHERE product_id = 4; -- NULL -> 'Lumen'
UPDATE products_v2 SET brand = NULL WHERE product_id = 7; -- 'Woolly' -> NULL
UPDATE products_v2 SET price = 52.00 WHERE product_id = 6;
SELECT p.product_id, p.brand AS old_brand, v.brand AS new_brand,
p.brand <> v.brand AS not_equal,
p.brand IS DISTINCT FROM v.brand AS is_distinct
FROM products p
JOIN products_v2 v ON v.product_id = p.product_id
WHERE p.product_id IN (3, 4, 7);
-- Every changed row, comparing whole rows at once
SELECT p.product_id, p.name
FROM products p
JOIN products_v2 v ON v.product_id = p.product_id
WHERE (p.*) IS DISTINCT FROM (v.*)
ORDER BY p.product_id;
product_id | old_brand | new_brand | not_equal | is_distinct
------------+-----------+-----------+-----------+-------------
3 | Lumen | Lumen | f | f
4 | (null) | Lumen | (null) | t
7 | Woolly | (null) | (null) | t
(3 rows)
product_id | name
------------+------------------
4 | Basecamp lantern
6 | Day 18 backpack
7 | Merino socks
(3 rows)
When either side is NULL, <> returns NULL rather than true (article 8), so a filter WHERE p.brand <> v.brand silently misses the lantern, whose brand went from NULL to Lumen, and the socks, whose brand was removed. IS DISTINCT FROM treats NULL as a comparable value: two NULLs are not distinct, and NULL versus a value is distinct. Its opposite, IS NOT DISTINCT FROM, is a NULL-safe equals.
PostgreSQL can compare whole rows at once: (p.*) IS DISTINCT FROM (v.*) is true when any column differs, which finds all three changed products, including the backpack's price change, without listing columns. Both tables must have the same columns in the same order.
Support for IS DISTINCT FROM is widespread now: PostgreSQL, SQL Server 2022, Oracle AI Database 26ai, SQLite (IS DISTINCT FROM since 3.39, or IS NOT) and MySQL (<=>, the NULL-safe equals) all have a form of it.
"All", "none" and "some" over a group
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- One row per order line, with its category, order status and line amount
CREATE VIEW sales AS
SELECT o.order_id, o.placed_on, o.status, p.category, p.brand,
oi.qty, oi.qty * oi.unit_price AS amount
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id;
-- "All", "none" and "some" conditions over a group
SELECT c.name,
COUNT(o.order_id) AS orders,
BOOL_AND(o.status IN ('shipped', 'delivered')) AS all_dispatched,
BOOL_OR(o.status = 'cancelled') AS any_cancelled,
COUNT(*) FILTER (WHERE o.status = 'pending') = 0 AS none_pending
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name
ORDER BY c.customer_id;
-- Orders whose items all come from one category
SELECT order_id, MIN(category) AS category
FROM sales
GROUP BY order_id
HAVING COUNT(DISTINCT category) = 1
ORDER BY order_id;
name | orders | all_dispatched | any_cancelled | none_pending
------------+--------+----------------+---------------+--------------
Asha Rao | 2 | t | f | t
Ben Okafor | 1 | t | f | t
Chen Wei | 1 | f | f | f
Dana Cruz | 1 | f | t | t
(4 rows)
order_id | category
----------+----------
102 | lighting
104 | tents
105 | packs
106 | clothing
(4 rows)
Conditions about every row of a group are aggregates over a boolean:
- all:
BOOL_AND(condition), also written with the standard nameEVERY, is true when the condition holds for every row. Asha's orders were all shipped or delivered. - any:
BOOL_OR(condition)is true when at least one row satisfies it. Dana has a cancelled order. - none: count the matching rows and require 0:
COUNT(*) FILTER (WHERE condition) = 0.
In databases without boolean aggregates, use MIN and MAX of a CASE returning 1 or 0: "all" is MIN(CASE WHEN cond THEN 1 ELSE 0 END) = 1, and "any" is MAX(...) = 1.
The second query finds orders whose items all come from one category: HAVING COUNT(DISTINCT category) = 1. Comparing MIN(category) = MAX(category) does the same and is often faster. Since all values are equal, MIN(category) also gives that one category.
One trap: these aggregates ignore NULLs, so a condition that's NULL for some rows can make "all" true when it shouldn't be. Use COALESCE(condition, false) if NULL should count as a failure.
Comparing two lists both ways
The warehouse sends a stock count. Which products differ, which weren't counted, and which counted items aren't in the catalogue at all?
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
\pset null '(null)'
-- A stock count from the warehouse, to compare with the catalogue
CREATE TABLE stock_count (product_id INTEGER PRIMARY KEY, counted INTEGER);
INSERT INTO stock_count VALUES (1, 12), (2, 2), (3, 40), (5, 22), (7, 75), (9, 4);
-- In one list but not the other, both directions, in one query
SELECT COALESCE(p.product_id, s.product_id) AS product_id,
p.name,
p.stock AS system_stock,
s.counted,
CASE WHEN s.product_id IS NULL THEN 'not counted'
WHEN p.product_id IS NULL THEN 'unknown product'
ELSE 'stock differs' END AS problem
FROM products p
FULL JOIN stock_count s ON s.product_id = p.product_id
WHERE p.product_id IS NULL
OR s.product_id IS NULL
OR p.stock IS DISTINCT FROM s.counted
ORDER BY 1;
product_id | name | system_stock | counted | problem
------------+------------------+--------------+---------+-----------------
2 | Summit 4 tent | 3 | 2 | stock differs
4 | Basecamp lantern | 15 | (null) | not counted
6 | Day 18 backpack | 0 | (null) | not counted
9 | (null) | (null) | 4 | unknown product
(4 rows)
A FULL JOIN (article 13) keeps unmatched rows from both sides, so one query covers all three problems:
- a catalogue product without a count row has a NULL on the count side: the lantern and the Day 18 backpack weren't counted
- a count row without a product has a NULL on the catalogue side: product 9 doesn't exist
- matched rows are compared with
IS DISTINCT FROM, so a NULL on either side would count as a difference: the Summit 4 tent has 3 in the system but 2 on the shelf
COALESCE of the two IDs gives one key column whichever side the row came from. EXCEPT in both directions (article 15) answers "which IDs are missing" too, but needs two queries and can't show the values side by side. MySQL has no FULL JOIN: combine a LEFT JOIN with the unmatched rows of a RIGHT JOIN using UNION ALL.
Custom sort orders, and DISTINCT inside aggregates
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- A custom sort order: the order statuses follow the order lifecycle, not the alphabet
SELECT order_id, status
FROM orders
ORDER BY array_position(ARRAY['pending', 'shipped', 'delivered', 'cancelled'], status::text),
order_id;
-- SUM(DISTINCT) and COUNT(DISTINCT) don't do what they seem to
SELECT SUM(qty) AS units,
SUM(DISTINCT qty) AS sum_of_distinct_values,
COUNT(DISTINCT qty) AS distinct_values
FROM order_items;
order_id | status
----------+-----------
104 | pending
101 | shipped
102 | shipped
106 | shipped
103 | delivered
105 | cancelled
(6 rows)
units | sum_of_distinct_values | distinct_values
-------+------------------------+-----------------
13 | 6 | 3
(1 row)
Custom order. Statuses should appear in lifecycle order, pending, shipped, delivered, cancelled, which isn't alphabetical. array_position(array, value) returns a value's position in an array, which then sorts correctly. The portable version is a CASE: ORDER BY CASE status WHEN 'pending' THEN 1 WHEN 'shipped' THEN 2 ... END. MySQL has FIELD(status, 'pending', 'shipped', ...). If the order is used often, store it: a statuses lookup table with a sort_order column, or an ENUM type, whose values sort in declaration order.
SUM(DISTINCT) adds up the distinct values, not the distinct rows. The order lines have quantities 1, 3, 2, 1, 1, 2, 1, 1 and 1, which total 13 units, but SUM(DISTINCT qty) is 1 + 2 + 3 = 6. It's almost never what a report wants. The usual cause is a join that duplicated rows (article 17), and the fix is to aggregate before joining, not to add DISTINCT.
What's current
- SQL Server 2022 and Oracle AI Database 26ai added
IS [NOT] DISTINCT FROM, so NULL-safe comparison is now available in every major database, with MySQL's<=>as its equivalent. - SQL Server 2022 added
GREATESTandLEAST, used for symmetric pairs. BOOL_ANDandBOOL_ORare PostgreSQL's. PostgreSQL also accepts the standardEVERY, but not the standardANY/SOMEaggregates, which would clash with= ANY (subquery). Other databases useMINandMAXoverCASE.
Common questions
How do I find customers who bought all of a set of products?
Filter to those products, group by customer, and keep groups where COUNT(DISTINCT product_id) equals the size of the set. Or use a double NOT EXISTS.
How do I list each pair of items only once?
Join with a.id < b.id instead of a.id <> b.id.
Why doesn't WHERE a <> b find rows where one side is NULL?
Comparisons with NULL return NULL, not true. Use a IS DISTINCT FROM b.
How do I test that every row of a group meets a condition?
BOOL_AND(cond) or EVERY(cond) in PostgreSQL. Elsewhere, MIN(CASE WHEN cond THEN 1 ELSE 0 END) = 1.
How do I sort by a custom order?
ORDER BY CASE col WHEN 'a' THEN 1 WHEN 'b' THEN 2 ... END, array_position in PostgreSQL, FIELD in MySQL, or a lookup table with a sort column.
Is SUM(DISTINCT x) a fix for double counting?
No. It ignores repeated values, including legitimate ones. Fix the join that duplicates rows instead.
Summary
- Relational division ("every item on a list") uses
COUNT(DISTINCT) = list sizeor a doubleNOT EXISTS. They differ for an empty list. - Self-join with
a.id < b.idto list each pair once.LEASTandGREATESTnormalise symmetric pairs. - Use
IS DISTINCT FROMto compare values that may be NULL. PostgreSQL can compare whole rows with it. BOOL_AND,BOOL_ORand a zeroFILTERcount express "all", "any" and "none" over a group.- A
FULL JOINreconciles two lists in both directions in one query. - Sort in a custom order with
CASE,array_positionor a lookup table. SUM(DISTINCT)sums distinct values, which is rarely what a report needs.
Practice questions
Write a query that finds the orders containing both product 3 (the Glow head torch) and product 7 (the Merino socks).
Answer
SELECT order_id
FROM order_items
WHERE product_id IN (3, 7)
GROUP BY order_id
HAVING COUNT(DISTINCT product_id) = 2;
Order 103. It's relational division with orders instead of customers.
A query joins friendships f1 to friendships f2 on f1.a = f2.b AND f1.b = f2.a to find relationships recorded in both directions, and gets each pair twice. How do you get it once?
Answer
Add AND f1.a < f1.b, so only the copy with the smaller value first is kept. Each mutual pair then appears once.
What do NULL <> 'Lumen', NULL IS DISTINCT FROM 'Lumen' and NULL IS DISTINCT FROM NULL return?
Answer
NULL, true and false. <> with a NULL operand is unknown. IS DISTINCT FROM treats NULL as an ordinary value: a NULL differs from 'Lumen' but not from another NULL.
Write a query that lists the customers none of whose orders were cancelled, using a zero count.
Answer
SELECT c.name
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name
HAVING COUNT(*) FILTER (WHERE o.status = 'cancelled') = 0
ORDER BY c.name;
Asha Rao, Ben Okafor and Chen Wei. Customers without orders aren't included, because of the inner join. Use a LEFT JOIN if they should count as "no cancelled orders" too.
The order lines have quantities 1, 3, 2, 1, 1, 2, 1, 1 and 1. What do COUNT(DISTINCT qty) and SUM(DISTINCT qty) return?
Answer
3 and 6. The distinct values are 1, 2 and 3.
Previous: Hierarchical Queries: Trees, Paths and Levels in SQL
Next: Database Design: Entities, Relationships and ER Diagrams

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.