Uncategorized

Why SQL Joins Multiply Rows—and How to Check Your Results

Quick answer

SQL joins return matching pairs of rows, not necessarily one row per customer or order. If one order matches three items, its order-level total appears three times. Before summing, define what one result row should represent, check the join keys, and aggregate detailed tables to that level when needed. Changing an INNER JOIN to a LEFT JOIN does not prevent multiplication. (postgresql.org)

Dialect: PostgreSQL, using PostgreSQL 18 documentation. You need basic familiarity with SELECT, GROUP BY, and aggregate functions. All data and amounts below are synthetic; they are not actual business results.

1. Start with grain: what does one row represent?

Before writing a join, complete this sentence for each table:

“One row represents one ______.”

That is the table’s grain. For this lesson:

Table One row represents Unique identifier Repeating relationship key
customers Customer customer_id None
orders Order order_id customer_id
order_items Item line within an order item_id order_id

A customer can have multiple orders, and an order can have multiple item lines. Repeated relationship keys are therefore expected.

Do not confuse a repeated relationship key with a duplicate record. Two item lines sharing order_id = 101 are not duplicates if they represent different lines.

PostgreSQL primary keys enforce unique, non-null identifiers. Foreign keys enforce references to existing parent records, but do not make the child’s referencing column unique. Multiple orders can legitimately reference the same customer. (postgresql.org)

Write down the required output grain, too. “One row per customer with order count and total order value” requires a different result from “one row per item line.”

2. Build a small dataset you can inspect

Use the following setup in a PostgreSQL practice session. These temporary tables hold three customers, three orders, and five item lines.

CREATE TEMP TABLE customers (
    customer_id integer PRIMARY KEY,
    customer_name text NOT NULL
);

CREATE TEMP TABLE orders (
    order_id integer PRIMARY KEY,
    customer_id integer NOT NULL
        REFERENCES customers(customer_id),
    order_total numeric(10, 2) NOT NULL
);

CREATE TEMP TABLE order_items (
    item_id integer PRIMARY KEY,
    order_id integer NOT NULL
        REFERENCES orders(order_id),
    line_amount numeric(10, 2) NOT NULL
);

INSERT INTO customers VALUES
    (1, 'Alex'),
    (2, 'Blair'),
    (3, 'Casey');

INSERT INTO orders VALUES
    (101, 1, 100.00),
    (102, 1, 100.00),
    (103, 2,  80.00);

INSERT INTO order_items VALUES
    (1001, 101, 60.00),
    (1002, 101, 40.00),
    (1003, 102, 100.00),
    (1004, 103, 50.00),
    (1005, 103, 30.00);

The intended baseline is:

  • Alex: two orders totaling 200.00.
  • Blair: one order totaling 80.00.
  • Casey: no orders.
  • All orders combined: 280.00.

Here, each order total equals the sum of its item amounts by construction. Real datasets may include shipping, discounts, taxes, or adjustments at different levels. Do not assume that equality without checking the field definitions.

Record the baseline before joining:

SELECT
    COUNT(*) AS order_rows,
    SUM(order_total) AS total_order_value
FROM orders;

Expected output:

order_rows total_order_value
3 280.00

This gives you something concrete to reconcile against.

3. See exactly how matching rows multiply

Inspect the detail join before adding aggregation:

SELECT
    o.order_id,
    i.item_id,
    o.order_total,
    i.line_amount
FROM orders AS o
INNER JOIN order_items AS i
    ON i.order_id = o.order_id
ORDER BY o.order_id, i.item_id;

Expected output:

order_id item_id order_total line_amount
101 1001 100.00 60.00
101 1002 100.00 40.00
102 1003 100.00 100.00
103 1004 80.00 50.00
103 1005 80.00 30.00

An inner join produces a result row for each matching pair. Order 101 matches two item lines, so it appears twice. This is correct item-level output—not evidence that PostgreSQL duplicated records accidentally. (postgresql.org)

Now aggregate that result:

SELECT
    COUNT(*) AS joined_rows,
    COUNT(DISTINCT o.order_id) AS distinct_orders,
    SUM(o.order_total) AS repeated_order_value,
    SUM(i.line_amount) AS item_value
FROM orders AS o
INNER JOIN order_items AS i
    ON i.order_id = o.order_id;

Expected output:

joined_rows distinct_orders repeated_order_value item_value
5 3 460.00 280.00

SUM adds the non-null values it receives. It does not know that order_total belongs to an order rather than an item line. The repeated totals therefore sum to 460.00. (postgresql.org)

The same matching-pair rule explains many-to-many multiplication: if one non-null equality key appears twice on one side and three times on the other, that key produces six matching pairs. Use this rule to predict expansion before accepting a result. (postgresql.org)

4. Check keys and counts before trusting totals

Start by testing the column—or column combination—you expect to be unique:

SELECT
    customer_id,
    COUNT(*) AS rows_per_key
FROM customers
GROUP BY customer_id
HAVING COUNT(*) > 1;

The sample returns no rows. For imported data without enforced constraints, any returned key needs investigation.

Run the equivalent check for orders.order_id. Then inspect a relationship key:

SELECT
    order_id,
    COUNT(*) AS item_lines
FROM order_items
GROUP BY order_id
ORDER BY order_id;

Expected output:

order_id item_lines
101 2
102 1
103 2

This repetition is legitimate. The question is whether your metric can safely repeat alongside it.

For a composite key, group by every component. If uniqueness belongs to (account_id, order_id), checking or joining on order_id alone is insufficient. PostgreSQL supports uniqueness constraints across column combinations. (postgresql.org)

Compare row counts after each join:

Stage Expected sample rows
customers 3
orders 3
Customers inner-joined to orders 3
Customers left-joined to orders 4
Orders inner-joined to items 5

Notice that the customer-to-order inner join has three rows—the same count as the customer table—but it repeats Alex and excludes Casey. An unchanged count is not proof of a correct join. These sample counts follow from the matching-pair and outer-join rules. (postgresql.org)

For your own analysis, compare both total rows and distinct identifiers at the intended grain.

5. Choose INNER or LEFT JOIN deliberately

Use an INNER JOIN when you want only matching records. Use a LEFT JOIN when you need to retain every left-side record, including those without a match. An unmatched left row receives nulls in the right-side columns. Neither choice removes multiple matches. (postgresql.org)

For all customers and their order counts:

SELECT
    c.customer_id,
    c.customer_name,
    COUNT(o.order_id) AS order_count
FROM customers AS c
LEFT JOIN orders AS o
    ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.customer_name
ORDER BY c.customer_id;

Expected counts are Alex 2, Blair 1, and Casey 0.

Use COUNT(o.order_id), not COUNT(*). The former counts non-null order IDs; the latter includes Casey’s retained customer row and would report one for Casey. (postgresql.org)

To investigate customers without orders:

SELECT c.customer_id, c.customer_name
FROM customers AS c
WHERE NOT EXISTS (
    SELECT 1
    FROM orders AS o
    WHERE o.customer_id = c.customer_id
);

This returns Casey. EXISTS tests whether a subquery returns any rows; NOT EXISTS reverses that test. It is also useful for checking orders without items or imported orders without matching customers. (postgresql.org)

Be careful with right-side filters. After a left join, WHERE o.order_total > 90 removes null-extended rows. Put that condition in ON if your intention is to retain all customers while matching only qualifying orders. The placement changes the result. (postgresql.org)

6. Pre-aggregate detail to the grain you need

If the question only needs order totals, leave out order_items.

If you also need item-line counts, summarize items to one row per order before joining them to orders:

WITH items_per_order AS (
    SELECT
        order_id,
        COUNT(*) AS item_lines
    FROM order_items
    GROUP BY order_id
)
SELECT
    c.customer_id,
    c.customer_name,
    COUNT(o.order_id) AS order_count,
    COALESCE(SUM(o.order_total), 0) AS total_order_value,
    COALESCE(SUM(ip.item_lines), 0) AS item_lines
FROM customers AS c
LEFT JOIN orders AS o
    ON o.customer_id = c.customer_id
LEFT JOIN items_per_order AS ip
    ON ip.order_id = o.order_id
GROUP BY c.customer_id, c.customer_name
ORDER BY c.customer_id;

Expected output:

customer_id customer_name order_count total_order_value item_lines
1 Alex 2 200.00 3
2 Blair 1 80.00 2
3 Casey 0 0.00 0

In this constructed query, the item summary has one row per order, so it cannot expand an order into multiple item rows. The customer output reconciles to three orders, 280.00 in order value, and five item lines.

PostgreSQL SUM returns null when there are no non-null values to sum; COALESCE supplies zero here. That is an explicit reporting choice for “no orders,” not a rule that every missing monetary value should become zero. (postgresql.org)

When joining two separate detail tables, consider summarizing each independently to the shared reporting key before joining their summaries.

7. Avoid DISTINCT fixes and finish with reconciliation

COUNT(DISTINCT order_id) is appropriate when the question genuinely asks for unique orders. But it does not repair a repeated monetary total.

SUM(DISTINCT order_total) sums unique amounts, not unique orders. PostgreSQL applies aggregate DISTINCT to the values of the supplied expression. (postgresql.org)

In this sample, two different orders both total 100.00. Distinct amounts are only 100.00 and 80.00, producing 180.00 instead of 280.00. It replaces overcounting with undercounting.

Likewise, do not add SELECT DISTINCT merely to make repeated-looking output disappear. First determine whether the rows represent legitimate detail or an incorrect join.

Before sharing a result:

  • State the output grain: one customer, order, or item line?
  • Check the full key: are all required components present?
  • Inspect repeated keys: legitimate detail or faulty uniqueness?
  • Compare rows and identifiers: did records multiply, disappear, or both?
  • Review unmatched records: expected absence or a data-quality problem?
  • Reconcile totals: use the same population, filters, and metric definition.
  • Trace one case manually: an order with several items is especially useful.

The goal is not to prevent every increase in row count. It is to ensure that each metric is calculated at the grain where it makes sense.