SQL Join Pitfalls: Fan-Out, Duplicates and Comparing Two Tables
Join mistakes that give wrong numbers without any error: fan-out when one row joins several child tables, inflated SUMs, why DISTINCT is no fix, checking a join's grain, partial keys and mismatched types, and comparing two tables to find added, removed and changed rows.
kvi5hnuCode Sprout team member12 min readOn this page
The join bugs in articles 12 and 13 lose rows. The bugs in this article add rows, and they're harder to spot, because the query still returns a plausible-looking result with no error. A sales total that's 30% too high looks like a good month. This article shows how rows multiply, how to detect it and how to fix it. It also covers a related task: comparing two tables to find what changed.
The examples use the shop database from article 12, plus a payments table. Order 101 was paid in two instalments, orders 102 and 103 were each paid in one, and the other orders are unpaid.
Fan-out
When you join a parent row to a child table, the parent row is repeated once per child. That's correct and expected: order 103 appears three times when you list its three lines. The result's grain, meaning what one row represents, has changed from "one row per order" to "one row per order line".
The trouble starts when one parent joins to two independent child tables. Each child row pairs with every row from the other child table, so the rows multiply:
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);
-- Payments: order 101 was paid in two instalments
CREATE TABLE payments (
payment_id INTEGER PRIMARY KEY,
order_id INTEGER NOT NULL REFERENCES orders (order_id),
amount DECIMAL(8, 2) NOT NULL
);
INSERT INTO payments VALUES (1, 101, 150.00), (2, 101, 147.99), (3, 102, 69.00), (4, 103, 154.45);
-- Order 101 on its own: 2 order lines, 2 payments
SELECT o.order_id, oi.product_id, oi.qty * oi.unit_price AS line_total, pay.payment_id, pay.amount
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN payments pay ON pay.order_id = o.order_id
WHERE o.order_id = 101
ORDER BY oi.product_id, pay.payment_id;
-- Summing after joining both child tables doubles both totals
SELECT o.order_id,
SUM(oi.qty * oi.unit_price) AS goods_total,
SUM(pay.amount) AS paid_total
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN payments pay ON pay.order_id = o.order_id
GROUP BY o.order_id
ORDER BY o.order_id;
order_id | product_id | line_total | payment_id | amount
----------+------------+------------+------------+--------
101 | 1 | 249.99 | 1 | 150.00
101 | 1 | 249.99 | 2 | 147.99
101 | 7 | 48.00 | 1 | 150.00
101 | 7 | 48.00 | 2 | 147.99
(4 rows)
order_id | goods_total | paid_total
----------+-------------+------------
101 | 595.98 | 595.98
102 | 69.00 | 69.00
103 | 154.45 | 463.35
(3 rows)
Order 101 has 2 lines and 2 payments, so joining both gives 2 × 2 = 4 rows. Each line total appears twice, once per payment, and each payment appears twice, once per line. That's why the second query (which uses SUM and GROUP BY, covered fully in Part 4) gets both totals wrong:
- order 101: goods and payments are both 595.98, double the real 297.99;
- order 103: three lines and one payment, so the goods total is right but the payment is counted three times, 463.35 instead of 154.45;
- orders 104, 105 and 106 disappeared, because the inner join to
paymentsdropped the unpaid orders.

Nothing in the result looks broken. The numbers are simply too large, which is why this bug survives into production reports.
The fix: aggregate before you join
Reduce each child table to one row per parent first, then join the reduced results. Each side then contributes exactly one row per order, so nothing multiplies:
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);
-- Payments: order 101 was paid in two instalments
CREATE TABLE payments (
payment_id INTEGER PRIMARY KEY,
order_id INTEGER NOT NULL REFERENCES orders (order_id),
amount DECIMAL(8, 2) NOT NULL
);
INSERT INTO payments VALUES (1, 101, 150.00), (2, 101, 147.99), (3, 102, 69.00), (4, 103, 154.45);
\pset null '(null)'
-- Fix: reduce each child table to one row per order first, then join
SELECT o.order_id, g.goods_total, p.paid_total,
g.goods_total - COALESCE(p.paid_total, 0) AS balance
FROM orders o
JOIN (SELECT order_id, SUM(qty * unit_price) AS goods_total
FROM order_items GROUP BY order_id) AS g ON g.order_id = o.order_id
LEFT JOIN (SELECT order_id, SUM(amount) AS paid_total
FROM payments GROUP BY order_id) AS p ON p.order_id = o.order_id
WHERE o.status <> 'cancelled'
ORDER BY o.order_id;
-- A tempting non-fix: SUM(DISTINCT ...) also drops genuinely equal values
SELECT SUM(DISTINCT amount) AS distinct_sum, SUM(amount) AS real_sum
FROM (VALUES (20.00), (20.00), (35.00)) AS t(amount);
order_id | goods_total | paid_total | balance
----------+-------------+------------+---------
101 | 297.99 | 297.99 | 0.00
102 | 69.00 | 69.00 | 0.00
103 | 154.45 | 154.45 | 0.00
104 | 489.00 | (null) | 489.00
106 | 16.00 | (null) | 16.00
(5 rows)
distinct_sum | real_sum
--------------+----------
55.00 | 75.00
(1 row)
The subqueries in FROM (called derived tables, article 23) compute the goods total and the paid total per order. The outer query joins them to orders: an inner join for goods, since every live order has lines, and a LEFT JOIN for payments, so unpaid orders stay in the result with a NULL total. COALESCE turns the NULL into 0 for the balance. Common table expressions (article 24) give the same structure with more readable names.
The second query shows why SUM(DISTINCT ...) isn't a fix, although it's often suggested. It removes duplicate values, not duplicate rows, so two genuine payments of 20.00 count as one. It only seems to work when every value happens to be different. COUNT(DISTINCT key) is fine, because keys are unique by definition, but summing distinct amounts is wrong.
Other correct alternatives:
- Scalar subqueries in the select list:
(SELECT SUM(amount) FROM payments p WHERE p.order_id = o.order_id) AS paid_total. These are clear for one or two values (article 22). LATERALjoins compute the per-parent aggregate in a subquery that can refer to the outer row (article 23).- Window functions can attach a total to every row without changing the grain (Part 6).
Detecting fan-out
Before you trust a query that joins and aggregates, check the grain:
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);
-- Payments: order 101 was paid in two instalments
CREATE TABLE payments (
payment_id INTEGER PRIMARY KEY,
order_id INTEGER NOT NULL REFERENCES orders (order_id),
amount DECIMAL(8, 2) NOT NULL
);
INSERT INTO payments VALUES (1, 101, 150.00), (2, 101, 147.99), (3, 102, 69.00), (4, 103, 154.45);
-- Is the join key unique on the side you expect to be "one"?
SELECT order_id, COUNT(*) AS payments
FROM payments
GROUP BY order_id
HAVING COUNT(*) > 1;
-- After a join, more rows than distinct keys means the join fanned out
SELECT COUNT(*) AS joined_rows, COUNT(DISTINCT o.order_id) AS distinct_orders
FROM orders o
JOIN payments p ON p.order_id = o.order_id;
order_id | payments
----------+----------
101 | 2
(1 row)
joined_rows | distinct_orders
-------------+-----------------
4 | 3
(1 row)
- Check that the "one" side is really unique.
GROUP BY key HAVING COUNT(*) > 1lists the keys that occur more than once. Here it shows that order 101 has two payments, sopaymentscan't be treated as one row per order. - Compare row counts with distinct keys. After joining orders to payments, there are 4 rows but only 3 distinct orders. More rows than keys means the join fanned out.
Habits that prevent fan-out bugs:
- For each query, say what one result row represents, such as "one row per order", before you write it.
- Join each child table to the parent only once per query, or aggregate it first.
- After writing a join, count the rows and compare with the parent table.
- Be suspicious of
DISTINCTadded "because there were duplicates". Find out why there were duplicates first.
Other ways joins create wrong rows
Partial keys
When a table has a composite key, the join must compare all its columns. Suppose a prices table has the key (product_id, valid_from), with one row per price change. Joining it with only ON prices.product_id = oi.product_id matches every historical price of the product, so each order line is repeated once per price change. The full condition picks the one price that was valid when the order was placed, which is a range condition on the date (article 14).
Joining on the wrong column
A join on columns that happen to have compatible types, but different meanings, runs without complaint: ON o.order_id = c.customer_id joins order 3 to customer 3. Name columns clearly, such as customer_id rather than id everywhere, and qualify every column in joins, so that mistakes like this are easy to see.
Mismatched types
If one table stores a code as text and another as a number, products differ in what happens:
- PostgreSQL rejects
text = integerwith an error, which is the safest behaviour. - MySQL and SQL Server convert one side implicitly. MySQL converts text to a number, so
'007' = 7is true and'7abc' = 7is true too. The conversion can also prevent index use, so the join becomes slow.
Fix the schema so that both columns have the same type. As a workaround, cast explicitly, and preferably cast the side that isn't indexed.
NULLs in join columns
Rows with NULL in a join column never match on =, not even NULL to NULL, so they vanish from inner joins and appear unmatched in outer joins (article 12). If two tables both use NULL to mean "none" and you need those rows to pair up, join with IS NOT DISTINCT FROM (article 8). That's rarely what you want, though, and it's usually a sign that the data needs a real key.
Comparing two tables
A common task is to compare two versions of a table, such as yesterday's and today's import, production and a copy, or the current products and a supplier's new price list. You want to know which rows were added, which were removed and which changed. Both techniques below handle NULLs correctly:
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);
-- Payments: order 101 was paid in two instalments
CREATE TABLE payments (
payment_id INTEGER PRIMARY KEY,
order_id INTEGER NOT NULL REFERENCES orders (order_id),
amount DECIMAL(8, 2) NOT NULL
);
INSERT INTO payments VALUES (1, 101, 150.00), (2, 101, 147.99), (3, 102, 69.00), (4, 103, 154.45);
\pset null '(null)'
-- A new price list arrives; compare it with the current products
CREATE TABLE price_import (product_id INTEGER PRIMARY KEY, name VARCHAR(40), price DECIMAL(8, 2), brand VARCHAR(20));
INSERT INTO price_import VALUES
(1, 'Ridge 2 tent', 259.99, 'Alpina'), -- price changed
(2, 'Summit 4 tent', 489.00, 'Alpina'),
(3, 'Glow head torch', 34.50, 'Lumen'),
(4, 'Basecamp lantern', 27.00, 'Lumen'), -- brand was NULL
(5, 'Trail 30 backpack', 89.95, 'Kestrel'),
(7, 'Merino socks', 16.00, 'Woolly'),
(8, 'Trek poles', 42.00, 'Alpina'); -- new; product 6 is missing
-- Rows that differ, in either direction, with EXCEPT (NULLs compare as equal)
(SELECT 'only in products' AS side, product_id, name, price, brand FROM products
EXCEPT
SELECT 'only in products', product_id, name, price, brand FROM price_import)
UNION ALL
(SELECT 'only in import', product_id, name, price, brand FROM price_import
EXCEPT
SELECT 'only in import', product_id, name, price, brand FROM products)
ORDER BY product_id, side;
-- The same comparison by key with FULL JOIN: classify every difference
SELECT COALESCE(p.product_id, i.product_id) AS product_id,
CASE
WHEN p.product_id IS NULL THEN 'added'
WHEN i.product_id IS NULL THEN 'removed'
ELSE 'changed'
END AS change,
p.price AS old_price, i.price AS new_price,
p.brand AS old_brand, i.brand AS new_brand
FROM products p
FULL JOIN price_import i ON i.product_id = p.product_id
WHERE p.product_id IS NULL
OR i.product_id IS NULL
OR p.price IS DISTINCT FROM i.price
OR p.brand IS DISTINCT FROM i.brand
OR p.name IS DISTINCT FROM i.name
ORDER BY product_id;
side | product_id | name | price | brand
------------------+------------+------------------+--------+---------
only in import | 1 | Ridge 2 tent | 259.99 | Alpina
only in products | 1 | Ridge 2 tent | 249.99 | Alpina
only in import | 4 | Basecamp lantern | 27.00 | Lumen
only in products | 4 | Basecamp lantern | 27.00 | (null)
only in products | 6 | Day 18 backpack | 54.00 | Kestrel
only in import | 8 | Trek poles | 42.00 | Alpina
(6 rows)
product_id | change | old_price | new_price | old_brand | new_brand
------------+---------+-----------+-----------+-----------+-----------
1 | changed | 249.99 | 259.99 | Alpina | Alpina
4 | changed | 27.00 | 27.00 | (null) | Lumen
6 | removed | 54.00 | (null) | Kestrel | (null)
8 | added | (null) | 42.00 | (null) | Alpina
(4 rows)
With EXCEPT
The first query runs EXCEPT in both directions and stacks the results with UNION ALL. A row that's identical in both tables disappears, so what remains is every row that differs. The side column says which table each row came from. Set operators compare NULLs as equal (article 15), so the lantern's NULL brand in products compared with Lumen in the import counts as a difference, while two NULLs would count as the same.
This approach needs no knowledge of keys, and it's quick to write. But a changed row appears twice, once from each side, and you have to compare the two rows by eye. If you only want to know whether the tables differ, count the rows of each EXCEPT: two zeros mean identical contents. Matching COUNT(*) values alone don't prove that.
With FULL JOIN on the key
The second query joins the tables on the primary key with a FULL JOIN, so every key from either table appears once:
- a key missing from
productswas added; - a key missing from the import was removed;
- a key in both, where any column differs, was changed.
The WHERE clause compares columns with IS DISTINCT FROM rather than <>. With <>, the change from a NULL brand to Lumen would be unknown, and the lantern would be silently missed. This version shows old and new values side by side, which is what you usually want for reviewing a change, or for driving an update (article 32) or a MERGE (article 34).
What's current
IS DISTINCT FROMis available in PostgreSQL, SQL Server 2022 and later, and SQLite, so comparing nullable columns no longer needs longOR ... IS NULLconditions there. MySQL usesNOT (a <=> b). In Oracle, compare withDECODE(a, b, 0, 1) = 1, or write out the NULL cases.- Data-comparison tools, including the table-diff features of database IDEs, use the same two techniques at scale, often comparing hashes of blocks of rows first and only looking at individual rows where the hashes differ.
Common questions
Why is my SUM too high after a join? The join repeated rows. Usually one parent joined to two child tables, or the "one" side of the join wasn't unique. Aggregate each child table to one row per key before joining.
Can I fix duplicates with DISTINCT?
Not reliably. SELECT DISTINCT hides repeated rows, and SUM(DISTINCT ...) drops genuinely equal values. Fix the join's grain instead. COUNT(DISTINCT key) is safe, because keys are unique.
How do I know what one row of my result represents?
Look at the most detailed table in the joins, and at the GROUP BY if there is one. With orders, lines and payments joined together, one row is "one combination of a line and a payment", which is rarely meaningful.
Is a one-to-many join always a fan-out problem? No. Joining orders to their lines is correct when you want one row per line, or when you aggregate only line columns. It becomes a problem when you aggregate the parent's columns, such as an order's shipping fee, or join a second child table.
How do I check whether two tables have exactly the same rows?
Run A EXCEPT B and B EXCEPT A. If both are empty, the tables have the same distinct rows. If duplicates matter, use EXCEPT ALL where available, or compare COUNT(*) grouped by every column.
Should I compare by key or by whole row?
By key, with a FULL JOIN, when the tables share a primary key and you want to classify changes. By whole row, with EXCEPT, when there's no reliable key or you only need to know whether anything differs.
Summary
- A join changes the grain of the result to its most detailed table. Know what one row represents.
- Joining one parent to two child tables multiplies their rows, which inflates
SUMandCOUNTwithout any error. - Fix fan-out by aggregating each child table to one row per parent before joining, or by using scalar subqueries,
LATERALor window functions. SELECT DISTINCTandSUM(DISTINCT ...)aren't fixes for fan-out.- Detect fan-out by checking that the "one" side is unique (
GROUP BY ... HAVING COUNT(*) > 1) and by comparing row counts with distinct keys. - Join on complete keys, on columns with the same meaning and type, and remember that NULLs never match.
- Compare two tables with
EXCEPTin both directions, or with aFULL JOINon the key andIS DISTINCT FROMon every other column.
Practice questions
A query joins orders to order_items and returns SUM(o.shipping_fee) per customer. Each order has one shipping fee. Why is the result too high, and how do you fix it?
Answer
The join repeats each order once per order line, so an order with three lines contributes its shipping fee three times. Either sum the fee before joining, as in SELECT customer_id, SUM(shipping_fee) FROM orders GROUP BY customer_id, or, if line data is also needed, aggregate the lines per order in a derived table first and join that to orders. Don't use SUM(DISTINCT o.shipping_fee): two orders with the same fee would be counted once.
Write a query that returns each customer's name with their number of orders and their number of order lines, without fan-out errors. Customers with no orders should show 0 for both.
Answer
SELECT c.name,
COALESCE(o.order_count, 0) AS orders,
COALESCE(l.line_count, 0) AS order_lines
FROM customers c
LEFT JOIN (SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id) o ON o.customer_id = c.customer_id
LEFT JOIN (SELECT o.customer_id, COUNT(*) AS line_count
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
GROUP BY o.customer_id) l ON l.customer_id = c.customer_id
ORDER BY c.name;
Each derived table has one row per customer, so the joins can't multiply rows. Asha has 2 orders and 5 lines, Ben, Chen and Dana have 1 order and 1 line each, and Eli and Farah have 0 and 0. (In this case COUNT(DISTINCT o.order_id) and COUNT(oi.order_id) over a single join would also work, because counting distinct keys is safe. Aggregating first works for sums too.)
Two tables, staff_old and staff_new, share the key staff_id. Write a condition that finds staff whose email changed, including changes from NULL to a value and from a value to NULL.
Answer
SELECT n.staff_id, o.email AS old_email, n.email AS new_email
FROM staff_old o
JOIN staff_new n ON n.staff_id = o.staff_id
WHERE o.email IS DISTINCT FROM n.email;
o.email <> n.email would miss both kinds of change involving NULL, because comparing with NULL is unknown. In MySQL, write WHERE NOT (o.email <=> n.email).
(SELECT * FROM a EXCEPT SELECT * FROM b) returns no rows, and (SELECT * FROM b EXCEPT SELECT * FROM a) returns no rows. Are the tables identical?
Answer
They contain the same distinct rows, but they could still differ in duplicates. If a contains a row twice and b contains it once, both EXCEPT queries are empty. To compare including duplicates, use EXCEPT ALL in both directions, which counts occurrences, or compare the counts per row: SELECT *, COUNT(*) FROM a GROUP BY <all columns> against the same for b. If both tables have a primary key, duplicates are impossible, and the two empty results do prove that they're identical.
Previous: Finding Matches and Missing Rows: EXISTS, NOT EXISTS, IN and NOT IN

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.