Full answer
A join is not a lookup that stops at the first match. For each left row it returns one output row per matching right row.
WITH prices(product, price) AS (VALUES ('Pen', 1), ('Pen', 2), ('Bag', 30)),
stock(product, shelf) AS (VALUES ('Pen', 'A1'), ('Pen', 'B4'), ('Bag', 'C2'))
SELECT p.product, p.price, s.shelf
FROM prices p JOIN stock s ON s.product = p.product
ORDER BY p.product, p.price, s.shelf;| product | price | shelf |
|---|---|---|
| Bag | 30 | C2 |
| Pen | 1 | A1 |
| Pen | 1 | B4 |
| Pen | 2 | A1 |
| Pen | 2 | B4 |
Count it: 2 Pen rows in the price list times 2 Pen rows in the stock table gives 4 rows for Pen, plus 1 x 1 for Bag.
A frequent real cause is a lookup table that someone assumed was unique. Here a price list accidentally holds two current prices for Pen, and every Pen sale is doubled when joined:
CREATE TABLE price_list (product TEXT, price INTEGER);
INSERT INTO price_list VALUES ('Pen', 1), ('Pen', 1), ('Bag', 30);
CREATE TABLE sales (product TEXT, qty INTEGER);
INSERT INTO sales VALUES ('Pen', 10), ('Bag', 1);
SELECT SUM(s.qty * p.price) AS revenue
FROM sales s JOIN price_list p ON p.product = s.product;| revenue |
|---|
| 50 |
The right answer is 10 x 1 + 1 x 30 = 40, but the duplicate Pen price row doubled the pen revenue. Finding the culprit:
SELECT product, COUNT(*) AS copies
FROM price_list
GROUP BY product
HAVING COUNT(*) > 1;| product | copies |
|---|---|
| Pen | 2 |
The protection is a constraint, not a DISTINCT in the report: make the lookup key a PRIMARY KEY or UNIQUE so the duplicate can never be inserted. To find existing duplicates, group by the key and keep groups with COUNT(*) > 1.
WITH prices(product, price) AS (VALUES ('Pen', 1), ('Pen', 2), ('Bag', 30)),
stock(product, shelf) AS (VALUES ('Pen', 'A1'), ('Pen', 'B4'), ('Bag', 'C2'))
SELECT p.product, p.price, s.shelf
FROM prices p JOIN stock s ON s.product = p.product
ORDER BY p.product, p.price, s.shelf;
CREATE TABLE price_list (product TEXT, price INTEGER);
INSERT INTO price_list VALUES ('Pen', 1), ('Pen', 1), ('Bag', 30);
CREATE TABLE sales (product TEXT, qty INTEGER);
INSERT INTO sales VALUES ('Pen', 10), ('Bag', 1);
SELECT SUM(s.qty * p.price) AS revenue
FROM sales s JOIN price_list p ON p.product = s.product;
SELECT product, COUNT(*) AS copies
FROM price_list
GROUP BY product
HAVING COUNT(*) > 1;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- Each left row pairs with every matching right row
- Duplicate keys on both sides multiply: m x n rows per key
- Duplicate keys in a lookup table inflate totals
- Enforce uniqueness with a constraint instead of DISTINCT
Common mistakes
- Assuming a join returns one match per left row
- Hiding duplicated rows with DISTINCT rather than fixing the data
Follow-ups
- How do you find duplicate keys in the price list?
- How would you pick only the latest price when several exist?
Tips
- Say the m x n rule before showing the result