Course contents 06 / 17

06 / 17 · Combining Rows

Inner joins

Pair order lines with catalogue entries. Track the number of matches and see how a join can double a total.

The report already knows that tea accounts for four units. The order table stores the code tea, while the catalogue says it belongs to drinks. The code connects the two facts. The report needs one catalogue category for each order line.

Match rows by a shared field#

Use the six order lines and add this catalogue in the same session. Each product has a single catalogue entry.

CREATE TEMP TABLE catalogue (
    product text PRIMARY KEY,
    category text NOT NULL
);

INSERT INTO catalogue VALUES
    ('tea', 'drinks'),
    ('coffee', 'drinks'),
    ('cocoa', 'pantry'),
    ('mint', 'herbs');

The inner join emits one result row for each pair of input rows for which the condition in ON is true. The query names each table with an alias, l or c. The expression l.product = c.product compares the two fields, and SELECT chooses what to show for every matching pair. (PostgreSQL 18, §7.2.1; SQLite, §2.1)

SELECT l.order_id, l.line_no, l.product, c.category
FROM order_lines AS l
JOIN catalogue AS c ON c.product = l.product
ORDER BY l.order_id, l.line_no;
order_idline_noproductcategory
1011teadrinks
1012coffeedrinks
1021teadrinks
1031coffeedrinks
1032teadrinks
1041cocoapantry

A cross join pairs each row with every row on the other side. It would yield 24 pairs here, from 6 order lines and 4 catalogue entries. We can reason about the inner join by testing the equality on each of those pairs and retaining the six that pass. This explains the result. It does not imply that the DBMS has to build all 24 pairs to execute the query. (PostgreSQL 18, §7.2.1; DuckDB 1.4, Cross product and conditional joins)

The catalogue’s primary key enforces at most one match for each order line. All six order lines happen to have matching codes. If the catalogue omitted cocoa, the corresponding order line would disappear from the result. The unique key limits multiplicity but does not require a match for each line.

How many pairs can one key create?#

Now the report writer uses a list of supplier offers in place of the catalogue. Each supplier may make one offer per product. Two suppliers offer tea. We compare by product again.

CREATE TEMP TABLE supplier_offers (
    product text,
    supplier text,
    PRIMARY KEY (product, supplier)
);

INSERT INTO supplier_offers VALUES
    ('tea', 'A'),
    ('tea', 'B'),
    ('coffee', 'A'),
    ('cocoa', 'C');

SELECT l.product, COUNT(*) AS pairs,
       SUM(l.quantity) AS summed_units
FROM order_lines AS l
JOIN supplier_offers AS s ON s.product = l.product
GROUP BY l.product
ORDER BY l.product;
productpairssummed_units
cocoa13
coffee23
tea68

Each of the three tea positions pairs with both offers. The result has six tea rows and counts the same four sold units twice. The grain is now one row per order line and offer pair. Eight describes the sum over those pairs. Actual tea sales remain four units.

Figure

Each tea line contributes two pairs

Each tea line contributes two pairsLines 101/1, 102/1 and 103/2 have quantities 2, 1 and 1. Each line matches both suppliers.LineSupplier ASupplier B101/122102/111103/211
Rows are order lines and columns are offers. Quantities sum to 8 across the six cells, even though the three lines sold 4 units.

For an equality join on a non-null key value kk, let nkn_k and mkm_k be the numbers of input rows with key kk on the left and right. Each of the nkn_k rows matches all mkm_k right rows with that value. That key contributes nkmkn_k m_k result rows. The tea key contributes 3⋅2=63 \cdot 2 = 6. Coffee and cocoa contribute 2 and 1, so the joined result has nine rows. In an ordinary equality condition, a comparison to NULL is unknown. Null keys do not match each other. (PostgreSQL 18, §7.2.1; SQLite, §2.1)

Match at the intended grain#

The offer table’s primary key is the pair (product, supplier). The query compares only one part of the key, so uniqueness of that pair does not prevent two offers from matching a line. If another input actually identifies a chosen supplier, match both fields. When the input identifies only a product and the report needs one category per product, the original catalogue has the right grain.

Use the same reasoning with repeated display values. Two tea positions each record one unit. SUM(DISTINCT l.quantity) would count the distinct quantities 1 and 2 once each, giving 3. The report needs both one-unit positions. Changing the aggregate would replace the meaning of the calculation while leaving the join’s row grain unchanged.

Before applying an aggregate, decide which joined row each pair represents. If the query needs one right-hand match per left-hand row, the compared fields must identify a right row uniquely. A missing match is a separate case. When it matters that every order line has a catalogue entry, that relationship must be checked or enforced independently.

Next#

The inner join dropped mint because it has no sale to form a pair with. A catalogue report may need to show mint with zero sales. Outer joins keep the unmatched catalogue row and show how to count genuine matches in its presence.

References#

  1. PostgreSQL Global Development Group. PostgreSQL 18 documentation, 2025. §7.2.1 defines cross and inner joins, join predicates and table aliases.
  2. SQLite Project. SELECT, §2.1. Specifies join semantics in terms of candidate row pairs and true predicates.
  3. DuckDB Foundation. FROM and JOIN Clauses. DuckDB 1.4 documentation, sections on cross products and conditional joins.