Pcornel
Browse topics
Options
Recent
Favorites
Databases · Technical reference

JOINs

Direct answer

JOINs combine rows from tables on a condition: INNER (matching rows), LEFT/RIGHT (keep one side), FULL (both), CROSS (all combinations).

When to use this

Use it when combining tables or when results have too many or too few rows.

First 30 seconds

1. Expected row count?

2. Join keys correct and indexed?

3. LEFT JOIN conditions in ON, not WHERE.

4. Duplicates → one-to-many join.

5. EXPLAIN the join.

Operational verification

tables → join condition → matched rows → result

Context & applicabilityCommon mistakes · platform/version boundaries
Platform / version applicability
MariaDB / MySQL / PostgreSQL / Microsoft SQL Server concepts
applies
Structured applicability is explicit Topic metadata; it does not infer compatibility beyond the stored rows.
At a glance

Operational reference

Fast context before you go deeper.

PlatformMariaDB / MySQL / PostgreSQL / Microsoft SQL Server concepts
Scope / prerequisiteUse it when combining tables or when results have too many or too few rows.
What next?2 suggested next steps
Evidence0
On this pageJump to a specific section
Operational workflow

Verification & Troubleshooting

Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.

2 steps Observe → verify → isolate → change minimally → repeat the original test.
ObservedRecord what the original test actually shows

Capture the concrete output, symptom, packet, log or counter before changing anything.

Step 1 How to verify Verify boundary

Run the join with count(*) and count(DISTINCT parent.id). Review EXPLAIN for the chosen join method and estimated rows.

Step 2 Common failures Narrow the fault

Joining two one-to-many tables at once inflates sums (fan-out). Joining on columns with different types prevents index use. Missing join conditions create a cartesian product.

Key points

Missing join conditions create row explosions. LEFT JOIN filters in WHERE turn it into an INNER JOIN — put them in ON. Index join columns.

Key checks
  • EXPLAIN — first check for this topic
  • psql -c "SELECT now(), version();" — PostgreSQL reachable and version
  • mysql -e "SELECT NOW(), VERSION();" — MariaDB/MySQL reachable and version
  • sqlcmd -S <server> -Q "SELECT @@VERSION" — SQL Server reachable and version
ReferenceWhat it is1 section · depth on demand

How it works

The planner picks a join method (nested loop, hash join, merge join) based on table sizes and indexes. A one-to-many join returns one row per match, so joining two child tables to the same parent multiplies rows.

ReferenceImportant terms & boundaries3 sections · depth on demand

Join types

JoinReturns
INNER JOINRows with matches in both tables
LEFT JOINAll left rows; NULLs where no match
RIGHT JOINAll right rows
FULL OUTER JOINAll rows from both (not in MySQL)
CROSS JOINEvery combination
SELECT o.id, c.name FROM orders o
LEFT JOIN customers c ON c.id = o.customer_id
WHERE c.id IS NULL;      -- orders without a customer

Index the join columns (foreign keys).

In depth

Join methods the planner chooses from

MethodGood whenShows in EXPLAIN as
Nested loopOuter side small, inner side has an index on the join keyNested Loop + Index Scan inside
Hash joinLarge unsorted inputs, equality join; builds a hash of the smaller side in memoryHash Join / Hash
Merge joinBoth sides already sorted on the key (index order)Merge Join

A hash join whose hash table exceeds work_mem spills to disk in batches (Batches: 8 in EXPLAIN ANALYZE).

Fan-out — the classic wrong total

-- WRONG: one order with 3 lines and 2 payments yields 6 rows; both sums are inflated
SELECT o.id, sum(l.amount), sum(p.amount)
FROM orders o JOIN order_lines l ON l.order_id = o.id
              JOIN payments p    ON p.order_id = o.id
GROUP BY o.id;

-- RIGHT: aggregate each child table first, then join one row per order
SELECT o.id, l.total, p.paid
FROM orders o
JOIN (SELECT order_id, sum(amount) total FROM order_lines GROUP BY 1) l ON l.order_id = o.id
LEFT JOIN (SELECT order_id, sum(amount) paid FROM payments GROUP BY 1) p ON p.order_id = o.id;

LEFT JOIN that silently becomes INNER

A condition on the right table in WHERE (WHERE p.status = 'ok') removes the rows where p is NULL. Put it in the ON clause to keep unmatched rows: LEFT JOIN payments p ON p.order_id = o.id AND p.status = 'ok'.

Anti-join

"Customers without orders": WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id) is NULL-safe and usually planned as an efficient anti join.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.

Common mistakes

  • Missing join conditions creating Cartesian products.
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Terminology layer

Terms & aliases

Hover a linked term for a quick definition; click it to open its glossary entry. Aliases are other names that find this Topic in search.

Aliases that resolve here
joinssql join left innerjoin fan-out
Confirmation

Confirm action

Continue?