Sub topic 1
Why duplicate rows appear in query results
Prerequisites
This chapter assumes you can already do the following:
- Write a basic
SELECT ... FROMquery. - Filter rows with
WHERE. - Sort rows with
ORDER BY. - Read a table as a set of rows and columns, with a primary key that identifies each row.
The examples use a small shop database with three tables: customers, orders, and order_items. They run in PostgreSQL, MySQL, and SQLite.
What a duplicate row is
A duplicate row in a result set is a row whose values in every selected column match another row in the same result. Duplicates are a property of the result, not of the table. A table with a primary key never holds two identical full rows, but a query can still return identical rows once you choose only some of the columns.
SQL treats a table and a query result as a multiset (also called a bag). A multiset is a collection where the same item can appear more than once. Rows have no hidden identity in a result. If two rows have equal values in all selected columns, they are indistinguishable.
This is different from the relational model in textbooks, which uses true sets with no repeated members. SQL keeps duplicates by default because removing them costs work and often changes the meaning of the answer. For example, summing a column over a result that was silently de-duplicated would give the wrong total.
The sample data
Here is the customers table used throughout this chapter.
| customer_id | name | country | city |
|---|---|---|---|
| 1 | Ana | Spain | Madrid |
| 2 | Ben | Spain | Madrid |
| 3 | Chloe | Spain | Barcelona |
| 4 | Dmitri | France | Paris |
| 5 | Elena | France | Paris |
| 6 | Farid | Egypt | NULL |
| 7 | Grace | NULL | NULL |
The table has no duplicate rows, because customer_id is unique. Now select only one column:
SELECT country
FROM customers;The result has seven rows:
| country |
|---|
| Spain |
| Spain |
| Spain |
| France |
| France |
| Egypt |
| NULL |
Spain appears three times and France twice. The query did not go wrong. It returned one row per customer, and several customers share a country.
Common causes of duplicates
Duplicates come from a small number of situations. Recognizing which one you are in tells you whether DISTINCT is the right fix.
Projecting away the unique column
The most common cause is the one shown above. Selecting a subset of columns that does not include a unique key makes different rows look the same. Here the question "which countries do we have customers in?" is about countries, but the table stores customers.
One-to-many joins
A join repeats a row from the "one" side once for every matching row on the "many" side. Suppose each customer can have many orders:
SELECT c.customer_id, c.name
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id;If Ana has four orders, this query returns Ana four times. The join produces one output row per matching pair, and the selected columns come only from customers, so the four rows look identical.
The diagram shows how the join multiplies rows.
Many-to-many joins
Joining through a link table, such as order_items between orders and products, can multiply rows more than once. Each additional one-to-many step multiplies the count. An order with 3 items, each tagged with 2 categories, appears 6 times if you select only order columns.
Chained joins that fan out
A less obvious form occurs when you join one parent to two unrelated child tables. Each child's rows multiply with the other's. A customer with 3 orders and 2 support tickets produces 6 rows. This is sometimes called a fan-out or a row explosion. It is a frequent source of wrong totals as well as duplicates.
Combining queries with UNION ALL
UNION ALL appends the results of two queries and keeps everything. If the same row appears in both inputs, it appears twice in the output. Plain UNION removes duplicates, and UNION ALL does not.
SELECT country FROM customers
UNION ALL
SELECT country FROM customers;This returns every country value twice, including both NULL rows.
Missing or incomplete join conditions
If a join condition omits part of a composite key, rows match more broadly than intended. If you omit the condition completely, the database returns a Cartesian product, which pairs every row of one table with every row of the other. A table of 1,000 customers joined to 1,000 products without a condition returns 1,000,000 rows.
Genuine duplicates in the data
Sometimes the table itself holds repeated values. Tables without a primary key or unique constraint can contain fully identical rows, for example after loading the same file twice. No query-level fix is correct here. The data should be cleaned, and a constraint should be added to prevent the problem.
Telling the causes apart
Before you reach for DISTINCT, decide whether the duplicates are expected. This table summarizes the usual diagnosis.
| Situation | Are duplicates a bug? | Typical fix |
|---|---|---|
| Selecting a non-unique column such as `country` | No, the question is about values | `DISTINCT` |
| One-to-many join, selecting only parent columns | Often no, the question is about parents | `DISTINCT`, or `EXISTS` / `IN` |
| Fan-out across two child tables | Yes, totals will be wrong | Aggregate each child separately first |
| `UNION ALL` of overlapping queries | Depends on intent | Use `UNION` if overlap is unwanted |
| Missing join condition | Yes | Add the condition |
| Repeated rows stored in the table | Yes | Clean data and add a constraint |
A quick way to check the cause is to compare row counts. If COUNT(*) returns more rows than you expect, find the grain of the result, meaning what one row is supposed to represent. If one row should be one customer, then any repeated customer_id signals a join problem.
SELECT c.customer_id, COUNT(*) AS row_count
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id
GROUP BY c.customer_id
HAVING COUNT(*) > 1;This query lists each customer that the join repeats and shows how many times.
Finding duplicates in a table
To find fully repeated values in a column or combination of columns, group by those columns and keep groups with more than one row:
SELECT country, city, COUNT(*) AS occurrences
FROM customers
GROUP BY country, city
HAVING COUNT(*) > 1;On the sample data this returns Spain, Madrid, 2 and France, Paris, 2. These pairs repeat, but they belong to different customers, so they are not errors. Whether a repeat is a problem depends on what a row is supposed to mean.
Why duplicates matter
Duplicates affect results in specific ways:
- Counts inflate.
COUNT(*)over a joined result counts joined rows, not parents. - Sums inflate. Summing a parent column after a one-to-many join counts that value once per child row. If an order total of 50 is repeated for 3 items, the sum shows 150.
- Averages shift. Repeated rows weigh more in the average.
- Output grows. Reports, exports, and API responses become longer than needed and confuse readers.
- Paging breaks. If you page through repeated rows with
LIMITandOFFSET, equal rows have no stable order between them. This is covered later in the tutorial.
-- Wrong if orders.total is stored on the order row
SELECT SUM(o.total)
FROM orders AS o
JOIN order_items AS i ON i.order_id = o.order_id;Each order's total is added once per item. The correct sum uses orders alone, or aggregates items separately.
Two ways to get one row per entity
When the goal is "one row per parent," you have two broad options. The next chapters cover the first in detail.
- Remove duplicates from the result. Use
SELECT DISTINCT. It is simple, and it works on whatever columns you select. - Avoid creating duplicates. Use
EXISTSorINfor "has at least one matching child," or aggregate the child table in a subquery before joining.
SELECT c.customer_id, c.name
FROM customers AS c
WHERE EXISTS (
SELECT 1
FROM orders AS o
WHERE o.customer_id = c.customer_id
);This returns each customer with at least one order exactly once, with no repeated rows to remove.
Summary of the model
- SQL results are multisets, so repeated rows are allowed and kept by default.
- Duplicates arise from projecting away a unique key, from joins that multiply rows, from
UNION ALL, from missing join conditions, and from repeated stored data. - Decide what one row should represent before you decide how to remove duplicates.
- Repeated rows are sometimes correct and sometimes a sign of a bug. The cause determines the fix.
Exercise
A query selects c.name from customers c JOIN orders o ON o.customer_id = c.customer_id. Ana has 3 orders and Ben has 1. How many rows does the query return for these two customers, and why? Name two different ways to return each customer once.
Show answer
It returns 4 rows: Ana three times and Ben once. The join produces one output row per matching customer and order pair, and only name is selected, so Ana's three rows look identical. To return each customer once, use SELECT DISTINCT c.name (or DISTINCT c.customer_id, c.name if two customers could share a name), or rewrite the query with WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id), which does not repeat parent rows.
Exercise
An order has a total of 80 and 4 rows in order_items. You run SELECT SUM(o.total) FROM orders o JOIN order_items i ON i.order_id = o.order_id and this is the only order. What does the query return, and what is the underlying problem?
Show answer
It returns 320, because the order row is repeated once for each of its 4 items and total is added each time. The problem is a one-to-many join that changes the grain of the result from one row per order to one row per item. Sum orders.total without the join, or aggregate order_items in a subquery before joining.
Exercise
You run SELECT country, city FROM customers on the sample data. Which rows are duplicates of each other, and does the NULL handling change your answer?
Show answer
The two Spain, Madrid rows (customers 1 and 2) and the two France, Paris rows (customers 4 and 5) are duplicates. The rows Egypt, NULL and NULL, NULL are each unique in this data, so they are not duplicates of anything. If two rows both had NULL, NULL, they would count as duplicates when removing duplicates, because that comparison treats NULLs as equal.