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.
Keys and how the tables connect
Section titled “Keys and how the tables connect”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.
| Column | Points to | Relationship |
|---|---|---|
products.merchant_id | merchants.id | a merchant has many products |
transactions.product_id | products.id | a product has many transactions |
webhook_events.product_id | products.id | a product has many events |
channel_payouts.merchant_id | merchants.id | a merchant has many payouts |
advances.merchant_id | merchants.id | a merchant has many advances |
ledger_entries.merchant_id | merchants.id | a merchant has many ledger entries |
ledger_entries.advance_id | advances.advance_id | an 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.
A join that keeps one row per transaction
Section titled “A join that keeps one row per transaction”FROM transactions tJOIN products p ON p.id = t.product_idJOIN merchants m ON m.id = p.merchant_idEach 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_joinFROM transactions tJOIN products p ON p.id = t.product_idJOIN merchants m ON m.id = p.merchant_id;| transactions | after_join |
|---|---|
| 8294 | 8294 |
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 or USING
Section titled “ON or USING”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_usdFROM advances vJOIN ledger_entries l USING (advance_id)WHERE advance_id = 'adv_0001'ORDER BY l.entry_id;| advance_id | amount_usd | entry_type | entry_usd |
|---|---|---|---|
| adv_0001 | 68.38 | advance | 68.38 |
| adv_0001 | 68.38 | fee | 2.05 |
| adv_0001 | 68.38 | repayment | -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 comparesmer_01withprd_01: both tables call their keyid, but they are different keys.NATURAL JOINjoins on every column with the same name.advances NATURAL JOIN ledger_entriesmatchesadvance_id,merchant_id,amount_usdandcreated_atat once, and returns 38 rows instead of 104. Do not use it in an interview.
What a join does to the row count
Section titled “What a join does to the row count”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_joinFROM advances vJOIN ledger_entries l ON l.advance_id = v.advance_id;| advances | advanced_usd | rows_after_join | advanced_after_join |
|---|---|---|---|
| 38 | 4824.32 | 104 | 13129.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.
| Join | Example | Rows after |
|---|---|---|
| to the “one” side | transaction → product → merchant | the same as before |
| to the “many” side | advance → ledger entries | more than before |
| “many” with “many” | a merchant’s transactions × the same merchant’s advances | the product of both |
Group by the key, show the name
Section titled “Group by the key, show the name”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.
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.
Practice
Section titled “Practice”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.idstart_time— start of the period = time of purchase; "started in …" means this columnrevenue_usd— revenue net of refunds: 0 if the transaction was refunded (net)is_test— test purchase: exclude it from business numbers
| product_id | start_time | revenue_usd | is_test |
|---|---|---|---|
| prd_01 | 2025-01-05 05:52:57 | 0.00 | false |
| prd_01 | 2025-01-03 05:03:11 | 6.99 | false |
| prd_01 | 2025-01-10 11:02:39 | 6.99 | false |
products — products (20 rows); a merchant can own several
id— key: prd_01 …merchant_id— → merchants.idname— product name
| id | merchant_id | name |
|---|---|---|
| prd_01 | mer_01 | Product 01 |
| prd_02 | mer_02 | Product 02 |
| prd_03 | mer_03 | Product 03 |
merchants — merchants (12 rows): businesses that sell subscriptions on the platform
id— key: mer_01 …name— company name (made up)
| id | name |
|---|---|
| mer_01 | Pocket Quest |
| mer_02 | Lumen Labs |
| mer_03 | Driftwood 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_usdFROM transactions tJOIN products p ON p.id = t.product_idJOIN merchants m ON m.id = p.merchant_idWHERE 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.nameORDER BY net_usd DESC, m.name;Expected output
| name | net_usd |
|---|---|
| Kite Works | 1277.36 |
| Lumen Labs | 1187.38 |
| Cobalt Studio | 569.73 |
| Orbit Fitness | 553.70 |
| Paper Fox | 413.70 |
| Driftwood Labs | 389.82 |
| Sunday Software | 359.53 |
| Brightleaf | 314.53 |
| Pocket Quest | 264.81 |
| Maple Games | 249.81 |
| Quiet Mind | 225.80 |
| North Pixel | 155.64 |
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.
Further reading
Section titled “Further reading”- Joined tables — inner and outer joins,
ON,USINGandNATURAL. - Joins between tables — the tutorial chapter, with small examples.
- Primary keys and foreign keys — the constraints behind “one” and “many”.
- FROM clause — the full join syntax in the
SELECTreference.
Related topics
Section titled “Related topics”- LEFT JOIN and zeros — keep the rows that have no match.
- Row multiplication — aggregate before you join two “many” sides.
- Practice dataset — every table and column used in the examples.
- Subqueries and CTE — aggregate in a named step, then join the result.
- Database concepts — keys and constraints when the talk turns to schema design.
Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.