Skip to content

Joins

The numbers a report needs are often spread over several tables: revenue is in transactions, the merchant’s name is in merchants. A JOIN glues rows together by a key. Before you write one, know which column links which tables, and what the join will do to the number of rows.

A primary key is a column whose value is unique and never NULL: one value, one row. merchants.id and products.id are primary keys. A foreign key is a column that points to the primary key of another table: products.merchant_id points to merchants.id. The direction tells you the relationship. One merchant has many products; one product has one merchant.

ColumnPoints toRelationship
products.merchant_idmerchants.ida merchant has many products
transactions.product_idproducts.ida product has many transactions
webhook_events.product_idproducts.ida product has many events
channel_payouts.merchant_idmerchants.ida merchant has many payouts
advances.merchant_idmerchants.ida merchant has many advances
ledger_entries.merchant_idmerchants.ida merchant has many ledger entries
ledger_entries.advance_idadvances.advance_idan advance has several ledger entries

merchants and products call their own key id; the other tables call it merchant_id or product_id. transactions has no merchant column. A transaction reaches its merchant only through products.

FROM transactions t
JOIN products p ON p.id = t.product_id
JOIN merchants m ON m.id = p.merchant_id

Each transaction has exactly one product, and each product has exactly one merchant. Every step joins to the “one” side, so the join adds columns and keeps the rows. Check it instead of assuming it:

SELECT (SELECT COUNT(*) FROM transactions) AS transactions,
COUNT(*) AS after_join
FROM transactions t
JOIN products p ON p.id = t.product_id
JOIN merchants m ON m.id = p.merchant_id;
transactionsafter_join
82948294

JOIN (an inner join) keeps only rows that have a match on both sides. Here every transaction has a product and every product has a merchant, so nothing is lost. When the other side may be missing, an inner join drops the row without a word: see LEFT JOIN and zeros.

ON takes any condition: ON p.id = t.product_id. USING (col) is a short form of “the column with this name is equal on both sides”. Both tables need a column with that name, and the output gets one merged column instead of two.

ledger_entries.advance_id and advances.advance_id share the name, so USING fits:

SELECT advance_id, v.amount_usd, l.entry_type, l.amount_usd AS entry_usd
FROM advances v
JOIN ledger_entries l USING (advance_id)
WHERE advance_id = 'adv_0001'
ORDER BY l.entry_id;
advance_idamount_usdentry_typeentry_usd
adv_000168.38advance68.38
adv_000168.38fee2.05
adv_000168.38repayment-70.43

The advance of 68.38 has three ledger entries: the advance, its fee and the repayment. Their sum is 0, so this advance is fully repaid.

When the names differ, USING fails. When the names match but the meaning does not, it is worse:

  • products p JOIN merchants m USING (merchant_id) fails: column "merchant_id" specified in USING clause does not exist in right table.
  • merchants m JOIN products p USING (id) runs and returns 0 rows. It compares mer_01 with prd_01: both tables call their key id, but they are different keys.
  • NATURAL JOIN joins on every column with the same name. advances NATURAL JOIN ledger_entries matches advance_id, merchant_id, amount_usd and created_at at once, and returns 38 rows instead of 104. Do not use it in an interview.

Count the rows of the table that sets the grain, then count again after the join. A join to the “many” side repeats every row of the “one” side:

SELECT (SELECT COUNT(*) FROM advances) AS advances,
(SELECT SUM(amount_usd) FROM advances) AS advanced_usd,
COUNT(*) AS rows_after_join,
SUM(v.amount_usd) AS advanced_after_join
FROM advances v
JOIN ledger_entries l ON l.advance_id = v.advance_id;
advancesadvanced_usdrows_after_joinadvanced_after_join
384824.3210413129.33

38 advances become 104 rows, and the sum of v.amount_usd after the join is almost three times the real total. This is row multiplication (fan-out). The usual fix is to aggregate the “many” side first, to one row per key, and join after that. Row multiplication shows the pattern in detail.

JoinExampleRows after
to the “one” sidetransaction → product → merchantthe same as before
to the “many” sideadvance → ledger entriesmore than before
“many” with “many”a merchant’s transactions × the same merchant’s advancesthe product of both

Two merchants can have the same name. GROUP BY m.name would then merge their numbers into one row. Group by the key and show the name: GROUP BY m.id, m.name. Because m.id is the primary key, PostgreSQL also accepts GROUP BY m.id alone.

When a merchant sells in several currencies

Section titled “When a merchant sells in several currencies”

A schema question often follows a join task. In the practice data every amount is already in US dollars: charged_usd, revenue_usd. Real merchants usually charge customers in their own currency, and the schema has to change for that.

TalkSay it out loud

A merchant now sells the same plan in several currencies. How would you change the schema?

Say your answer out loud first, then open it.

Show the answer

“I’d keep the amount and the currency code on each transaction, exactly as the customer was charged: for example 9.99 and EUR. Then I’d add an exchange-rate table with one rate per currency and day. A report in dollars joins each transaction to the rate of its own date and converts there. I’d never overwrite the original amount, because a refund must return what the customer paid. And amounts and rates are NUMERIC, not float.”

A common short answer is “add a currency column”. The key part is the date of the rate: with the rate of the transaction date, last month’s revenue does not change when today’s rate moves. Ask what happens on a day with no rate, such as a weekend: usually the last rate before that date is used.

SQLWrite a querycore

Net revenue (revenue_usd) per merchant for September 2026, test purchases excluded: the merchant's name and the amount. Two merchants can have the same name. Highest first.

Output columns: name, net_usdOrder: ORDER BY net_usd DESC, name

Tables, columns and how they connect

transactions — one row = one paid (or trial) period of a subscription

  • product_id — → products.id
  • start_time — start of the period = time of purchase; "started in …" means this column
  • revenue_usd — revenue net of refunds: 0 if the transaction was refunded (net)
  • is_test — test purchase: exclude it from business numbers
product_idstart_timerevenue_usdis_test
prd_012025-01-05 05:52:570.00false
prd_012025-01-03 05:03:116.99false
prd_012025-01-10 11:02:396.99false

products — products (20 rows); a merchant can own several

  • id — key: prd_01 …
  • merchant_id — → merchants.id
  • name — product name
idmerchant_idname
prd_01mer_01Product 01
prd_02mer_02Product 02
prd_03mer_03Product 03

merchants — merchants (12 rows): businesses that sell subscriptions on the platform

  • id — key: mer_01 …
  • name — company name (made up)
idname
mer_01Pocket Quest
mer_02Lumen Labs
mer_03Driftwood Labs

Joins: products.merchant_id = merchants.id; transactions.product_id = products.id

"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.

-- your query here
Show answer

Reference

SELECT m.name, SUM(t.revenue_usd) AS net_usd
FROM transactions t
JOIN products p ON p.id = t.product_id
JOIN merchants m ON m.id = p.merchant_id
WHERE NOT t.is_test
AND t.start_time >= TIMESTAMP '2026-09-01'
AND t.start_time < TIMESTAMP '2026-10-01'
GROUP BY m.id, m.name
ORDER BY net_usd DESC, m.name;

Expected output

namenet_usd
Kite Works1277.36
Lumen Labs1187.38
Cobalt Studio569.73
Orbit Fitness553.70
Paper Fox413.70
Driftwood Labs389.82
Sunday Software359.53
Brightleaf314.53
Pocket Quest264.81
Maple Games249.81
Quiet Mind225.80
North Pixel155.64
12 rows

A transaction reaches its merchant only through products. Each transaction has exactly one product and each product one merchant, so the rows do not multiply. GROUP BY m.id, m.name keeps two merchants with the same name apart.

Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.