QA Interview Hub · Knowledge base · Quizzes · Українська

SQL

JOIN

kinds of joins and their traps

What is a JOIN and why is it needed?

JOIN combines rows of tables by the ON condition, usually a foreign key equal to a primary key, and returns one row for every pair found. It is needed because in a normalised model each fact lives in one place and the full picture is assembled at read time. A forgotten condition gives a Cartesian product, and the kind of JOIN only decides the fate of rows without a pair.

SQL · JOIN

The orders table has only a user_id and the report needs an email. How do you get it in one query?

An order stores user_id = 1, but a support report must show the buyer's email. The email lives in another table, and copying it into every order is not an option: after the email changes the data would drift apart. This lesson explains why data is split across tables, what exactly JOIN does and how one missing condition turns a query into millions of extra rows.

How it works and why. The relational model keeps each fact in one place: the email in users, the amount in orders, and the link is a key (orders.user_id points to users.id). This is normalisation: there are no copies that can disagree. The price is that the full picture is assembled at read time. JOIN does that: it takes each row of the left table, looks in the right one for rows where the ON condition is true and outputs one result row per pair found.

JOIN builds pairs of rows

usersordersAnnaIvanOlhao100 · 50o101 · 30o102 · 20Each arrow is one result row.Olha has no pair: INNER JOIN drops her.
Figure 1. The result is the pairs that passed the ON condition. A row with no pair either disappears or stays, depending on the kind of JOIN.

Three things follow. The number of result rows is set by the pairs, not by the size of one table. The ON condition is an ordinary predicate, so you can join on any expression, though most often it is "a foreign key equals a primary key". And the kind of JOIN answers only one question: what to do with a row that found no pair (the next lessons go through the kinds one by one).

Example: from 9 rows to 3. A tester writes a query in the old style, with tables separated by a comma, and forgets the link condition:

-- old syntax: a comma join with no condition
SELECT u.email, o.total
FROM users u, orders o;
-- 9 rows: every user with every order

The query runs without errors but on our data set (3 users, 3 orders) it returns 9 rows: every user was paired with every order, a Cartesian product. On a small test database this goes unnoticed; on a real one with 10,000 users and 50,000 orders it is 500 million rows and a hung environment. The diagnostic signal: the row count equals the product of the table sizes. The fix is an explicit JOIN … ON:

SELECT u.email, o.id AS order_id, o.total
FROM users u
JOIN orders o ON o.user_id = u.id;
-- 3 rows: Anna twice, Ivan once; Olha is absent

What is left after the join

users
idemail
1anna@test.com
2ivan@test.com
3olha@test.com lost
JOIN result
emailorder_idtotal
anna@test.com10050
anna@test.com10130
ivan@test.com10220
Figure 2. Anna appears twice because she has two orders. Olha has no orders and did not reach the result.

The result is now right, but it revealed one more thing: Olha is missing. For a report "orders with email" that is fine, for a report "all users" it is not. The difference between these two questions is exactly the choice of the kind of JOIN.

Limits and alternatives. A query can have as many tables as needed, and each next JOIN attaches a new table to the result built so far:

-- a chain: transaction → account → user
SELECT t.id, t.amount, u.email
FROM transactions t
JOIN accounts a ON a.id = t.account_id
JOIN users u    ON u.id = a.user_id;

Here each INNER JOIN adds the condition "a pair is mandatory", so one missing link (an account with no user) drops the transaction from the result. If the join columns have the same name in both tables, PostgreSQL and MySQL offer the shortcut USING (user_id), but an explicit ON reads less ambiguously. A dialect difference: in PostgreSQL a JOIN without ON is a syntax error, in MySQL it is allowed and works as CROSS JOIN, so a forgotten ON will not stop the query there. An alternative to JOIN when you only need to check that a related record exists is EXISTS: it does not multiply rows.

Common mistakes.

  • A forgotten link condition: a Cartesian product instead of pairs, millions of rows and a slow environment.
  • Joining on a non-unique column (for example a name): one row finds several pairs and the result multiplies.
  • Reading a JOIN result as "one row per entity": it is one row per pair.
  • Expecting JOIN to check integrity: without a foreign key in the schema it silently skips orphan records.
  • SELECT * after several JOINs: columns with the same name (id) overwrite each other in client code.

Check yourself

users has 4 rows and orders has 6. How many rows does FROM users, orders without a condition return and why does a tester need to know it?

Answer

24 rows (4 × 6): every user with every order. If the result row count equals the product of the table sizes, the query has no link. On large tables such a query can overload a shared environment.

All orders have a user_id, but for one value there is no row in users because the schema has no foreign key. Will that order appear in a JOIN query?

Answer

No. INNER JOIN keeps only pairs, so the order with no user vanishes from the report without any error. That is why the row count after a JOIN is worth comparing with COUNT(*) of the source table.

In an interview. Junior: JOIN combines tables by a condition, usually a foreign key equals a primary key. Data is stored separately to avoid duplication, and JOIN puts it together: for example an order and the owner's email. Middle/Senior: The result is the pairs of rows that passed the ON condition, so the row count depends on the link, not on the table size. A forgotten condition gives a Cartesian product, a non-unique key multiplies rows, and the kind of JOIN decides the fate of rows without a pair. After a JOIN I compare the row count with the source table.

How does INNER JOIN work?

INNER JOIN returns only the pairs of rows for which the ON condition is true, and everything without a pair silently disappears from the result. A NULL in the key matches nothing, not even another NULL, so such a row disappears too. That is why the row count after a JOIN is compared with the source table, and missing pairs are found with an anti-join.

SQL · JOIN

The table has 4 orders worth 140 and the JOIN report shows 100. Which order vanished?

A tester reconciles revenue: the sum over the orders table is 140, while the report that adds the buyer's email through a JOIN shows 100. The query has no error and the database did not fail. INNER JOIN simply dropped everything for which it found no pair. This lesson is about what exactly INNER JOIN keeps, why a missing row gives no signal and how to turn that into a data integrity check.

How it works and why. INNER JOIN returns the intersection: only pairs for which the ON condition is true. The word INNER can be omitted, because JOIN is inner by default. The design makes sense when the link is mandatory: an order without a buyer should not appear in a report about buyers. The silence is also the weak spot: SQL does not treat a vanished row as an event, so there is no warning or error.

The ON condition is true only when both sides are known and equal. NULL never equals anything, not even another NULL (the comparison gives UNKNOWN and JOIN takes only true). So a row with user_id = NULL finds no pair anywhere and vanishes the same way as a row that points to a user that does not exist.

Example: the sum that does not add up. The table has four orders: 100 (Anna, 50), 101 (Anna, 30), 102 (Ivan, 20) and 103 (a guest order, no user_id, 40). The initial query:

-- revenue by email: 100, although orders hold 140
SELECT SUM(o.total)
FROM orders o
JOIN users u ON u.id = o.user_id;

It returns 100 instead of 140. To find the cause, do not guess: compare the counts before and after the join, and then output the rows that are missing:

SELECT COUNT(*) AS all_orders,
       COUNT(user_id) AS with_user
FROM orders;
-- illustration: 4 and 3

SELECT id, total
FROM orders
WHERE user_id IS NULL
   OR NOT EXISTS (SELECT 1 FROM users u WHERE u.id = orders.user_id);

The gap between 4 and 3 says that one order has no user. The second query names it: 103. Two conclusions here. For a report "revenue by buyer" the result 100 may be right, since a guest order belongs to no buyer, but only if that is known and agreed. If by the requirement an order must have a user, order 103 is a data defect, and INNER JOIN hid it.

What INNER JOIN dropped

orders
iduser_idtotal
100150
101130
102220
103NULL40 lost
JOIN result
orderemailtotal
100anna@test.com50
101anna@test.com30
102ivan@test.com20
Figure 1. A NULL key has no pair, so order 103 vanishes without any error: the sum is 100 instead of 140.

Limits and alternatives. In a chain of several INNER JOINs the loss accumulates: a row must pass every link.

-- an INNER JOIN chain: one missing link drops the row
SELECT o.id, u.email, p.amount
FROM orders o
JOIN users u    ON u.id = o.user_id
JOIN payments p ON p.order_id = o.id;

Here an order with no payment vanishes even if the buyer exists. So when you need "everything from one table and, if present, data from another", take LEFT JOIN (the next lesson). When you only need to prove that a related record exists, without multiplying rows, EXISTS fits. When losing rows is undesirable, the best fix is a foreign key and NOT NULL in the schema: then an "order with no user" cannot be created at all, and INNER JOIN has nothing to drop. The table order in an INNER JOIN does not affect the result; the optimiser picks where to start.

Common mistakes.

  • Using INNER JOIN for the question "what is missing": whatever has no pair just disappears from the result.
  • Not comparing the row count after a JOIN with the source table: the loss goes unnoticed, the sum looks plausible.
  • Assuming a NULL key joins with a NULL in another table: it never matches.
  • Building a long INNER JOIN chain in a report "about everything": each link quietly filters rows.
  • Adding an INNER JOIN to a working query without recomputing the result: the report "lost weight" for no visible reason.

Check yourself

orders has 1000 rows, user_id is filled in all of them, and users lacks one user referenced by 5 orders. How many rows does an INNER JOIN with users return and how do you detect it without browsing the table?

Answer

995 rows. The orders vanished with no error. Detect it by comparison: SELECT COUNT(*) FROM orders against COUNT(*) after the JOIN, and then an anti-join (LEFT JOIN … WHERE u.id IS NULL) will show those 5 orders.

Why do rows with user_id = NULL in orders and id = NULL (if there were such) in users not join under ON u.id = o.user_id?

Answer

The comparison NULL = NULL gives UNKNOWN, not true, and INNER JOIN keeps only pairs with a true condition. So NULL does not match even NULL. If you need NULLs treated as equal, PostgreSQL has IS NOT DISTINCT FROM, but for keys that is almost always a sign of a problem in the data.

In an interview. Junior: INNER JOIN returns only rows that have a pair in both tables, the rest disappear. So if there are fewer records after a JOIN than expected, I check whether some records have no pair: it may be a data problem. Middle/Senior: The ON condition takes only true pairs and NULL equals nothing, so a row with a NULL key drops silently. I treat each link of an INNER JOIN chain as a filter. I compare COUNT(*) before and after and look for the missing rows with an anti-join. In the schema I back the link with a foreign key and NOT NULL.

How does LEFT JOIN work?

LEFT JOIN keeps every row of the left table; where there is no pair on the right, the right columns are filled with NULL. This NULL means a missing pair, not missing data, so aggregates count the right table's key, for example COUNT(o.id) instead of COUNT(*), and sums are wrapped in COALESCE. The order of tables matters here.

SQL · JOIN

The report "orders per user" says Olha has one order, although she never bought anything.

A manager asks for a report: every user and the number of their orders, including those who have not bought anything yet. The tester takes a LEFT JOIN, all users appear, and Olha has one order. But she has none in the orders table. This lesson explains what LEFT JOIN does to a row with no pair, why a NULL in the result breaks familiar aggregates and how to check such a report.

How it works and why. LEFT JOIN solves the problem of INNER JOIN: rows of the left table must not be lost. For each left row, pairs are searched on the right. If there is a pair, the result is the same as in INNER JOIN. If there is none, the left row still goes into the result once, and all columns of the right table are filled with NULL. The left table becomes the "preserved" side and the right one the "optional" side. So the table order matters here, unlike in INNER JOIN.

The main danger follows. The result contains NULLs that are not in the data: they are created by the join itself. A NULL in a right column means "no pair was found", not "the value is unknown". Any function that reads right-hand columns must take that into account.

Example: Olha with one order. Three users, orders 100 and 101 belong to Anna, 102 to Ivan, Olha has none. The initial query:

SELECT u.email, COUNT(*) AS orders_cnt
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
GROUP BY u.email;
-- anna 2, ivan 1, olha 1: the last one is wrong

For Olha the result is wrong. Let us take it apart: LEFT JOIN returned one row for her with NULL in the columns o.id and o.total. COUNT(*) counts rows, and there is one row, so it gives 1. COUNT(o.id) counts only non-NULL values, so it gives 0. The fixed query also adds COALESCE for the sum: SUM over only NULLs gives NULL, not 0, and the report would show an empty cell.

SELECT u.email,
       COUNT(o.id)                AS orders_cnt,
       COALESCE(SUM(o.total), 0)  AS revenue
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
GROUP BY u.email;
-- anna 2 / 80, ivan 1 / 20, olha 0 / 0

LEFT JOIN and grouping

after LEFT JOIN
emailorder_idtotal
anna@test.com10050
anna@test.com10130
ivan@test.com10220
olha@test.comNULLNULL
COUNT(*) and COUNT(o.id)
emailCOUNT(*)COUNT(o.id)
anna@test.com22
ivan@test.com11
olha@test.com10
Figure 1. Olha’s row exists only after the join. COUNT(*) sees it, COUNT(o.id) does not.

A diagnostic rule: if a LEFT JOIN report has a group with a count of 1 where 0 was expected, check which column the aggregate counts. It should count a column of the right table, best of all its key, because a key is never NULL in a real row.

Limits and alternatives. The second dangerous case is a chain. If a plain JOIN to the next table follows a LEFT JOIN, the rows with NULL find no pair again and vanish:

-- wrong: an INNER after a LEFT drops users with no orders again
FROM users u
LEFT JOIN orders o   ON o.user_id = u.id
JOIN payments p      ON p.order_id = o.id

-- right: a LEFT chain, the pair stays optional
FROM users u
LEFT JOIN orders o   ON o.user_id = u.id
LEFT JOIN payments p ON p.order_id = o.id

So in a chain where all rows on the left are needed, every next join must be LEFT too. The second trap is a condition on the right table in WHERE (a separate lesson covers ON versus WHERE). RIGHT JOIN does the mirror image, so everything said applies to it with the sides swapped. To check a LEFT JOIN, compare row counts: the result is not smaller than the left table, and exceeds it only when some left row has several pairs. If you only need to show that a related record exists, EXISTS is simpler and does not multiply rows. The behaviour is the same in all databases; only the way clients print NULL differs.

Common mistakes.

  • COUNT(*) instead of COUNT(right_column) after a LEFT JOIN: "orphans" count as one record.
  • SUM/AVG without COALESCE: a NULL in the report instead of zero, and AVG ignores NULLs, so an average over LEFT JOIN rows leaves out users with no orders.
  • A plain JOIN after a LEFT JOIN: everything that had no pair vanishes again.
  • Mixing up the sides: LEFT JOIN preserves the left table, and if all orders are needed, not all users, orders must be on the left.
  • Reading a NULL in the result as data: it is only the absence of a pair.

Check yourself

users has 10 rows, orders has 16: each user has 2 orders, except two users with none. How many rows does users LEFT JOIN orders return?

Answer

8 users give 2 rows each (16), the two with no orders give 1 row each with NULL: 18 in total. The result is bigger than users because LEFT JOIN keeps everyone on the left and multiplies by pairs on the right.

Why does AVG(o.total) after a LEFT JOIN per user give NULL, not 0, for Olha who has no orders, and what do you do about it?

Answer

AVG ignores NULL, and all values in Olha's group are NULL, so the average is undefined. If the requirement needs zero, wrap it as COALESCE(AVG(o.total), 0). But an average with no orders is perhaps better left empty: zero is misleading.

In an interview. Junior: LEFT JOIN returns all rows of the left table and from the right one only those that have a pair, otherwise NULL. I use it when records must not be lost: for example to show all users, including those with no account. Middle/Senior: A NULL on the right is the absence of a pair, not data, so in aggregates I count the right table's key (COUNT(o.id)) rather than COUNT(*), and wrap sums in COALESCE. All next joins in the chain are LEFT too, otherwise rows without a pair vanish. I compare row counts: the result is not smaller than the left table.

What are RIGHT, FULL OUTER and CROSS JOIN?

JOIN kinds differ in whose rows without a pair are kept: RIGHT keeps the right table, FULL OUTER both. CROSS JOIN has no condition and returns all combinations. RIGHT JOIN is usually replaced by LEFT with the tables swapped. FULL OUTER suits reconciling two sets, and CROSS JOIN only small reference tables, because the result size is the product of the sizes.

SQL · JOIN

Reconciling with a provider statement: which operations exist only on our side and which only on theirs?

At the end of the day the platform's transactions must be reconciled with the payment provider's statement. A LEFT JOIN from our transactions finds what we have and the provider does not. But money that the provider accepted and we did not record is invisible to this query. This lesson is about the three remaining kinds of JOIN, RIGHT, FULL OUTER and CROSS, and which question each answers.

How it works and why. All kinds of JOIN differ in whose rows without a pair are kept. INNER keeps no one. LEFT keeps the left side, RIGHT the right one. FULL OUTER keeps both sides: a row without a pair from either side goes into the result, and the missing half is filled with NULL. CROSS JOIN stands apart: there is no condition, and every row of the left table is combined with every right one.

Two statements, three possible states

oursprovidere1e2e3e2e3e4e1 and e4 have no pair: kinds of JOINtreat them differently.
Figure 1. e2 and e3 match. e1 exists only on our side, e4 only on the provider side. FULL OUTER JOIN returns all four, LEFT JOIN will not show e4.

In practice RIGHT JOIN is almost never written: A RIGHT JOIN B gives the same as B LEFT JOIN A but with a different column order, and a result where the "main" table comes second is awkward to read. FULL OUTER JOIN is the tool for reconciling two sets when differences are possible on both sides. CROSS JOIN gives all combinations and is useful for generating test data.

Example: reconciliation in both directions. Our transactions: e1, e2, e3. In the provider statement: e2, e3, e4. A "what is missing" report with a LEFT JOIN finds only e1 (we have it, they do not). Transaction e4, accepted by the provider and not recorded on our side, goes unnoticed, although it is the worse case: money was debited and there is no order. The right query selects both sides:

-- reconciliation: what exists on one side only
SELECT o.ext_id AS our_id, p.ext_id AS provider_id
FROM transactions o
FULL OUTER JOIN provider_report p ON p.ext_id = o.ext_id
WHERE o.ext_id IS NULL OR p.ext_id IS NULL;

FULL OUTER JOIN and the mismatch filter

after FULL OUTER JOIN
our_idprovider_id
e1NULL
e2e2 filtered
e3e3 filtered
NULLe4
after WHERE IS NULL
our_idprovider_id
e1NULL
NULLe4
Figure 2. The filter keeps only mismatches. The matches e2 and e3 are filtered out; the report shows e1 (missing at the provider) and e4 (missing on our side).

The result contains two categories of defects with different consequences: a row with NULL on the right is our operation that the provider does not see, a row with NULL on the left is an accepted payment with no record. They are told apart by the column that holds NULL. If the keys differ in format (case, spaces, a prefix), the pair is not found and the reconciliation shows mismatches where there are none: normalise the keys first.

Limits and alternatives. MySQL has no FULL OUTER JOIN. It is built from two parts: a LEFT JOIN and a second query from the right side, only rows without a pair, through UNION ALL:

-- MySQL has no FULL JOIN: build it from two parts
SELECT o.ext_id AS our_id, p.ext_id AS provider_id
FROM transactions o
LEFT JOIN provider_report p ON p.ext_id = o.ext_id
WHERE p.ext_id IS NULL
UNION ALL
SELECT o.ext_id, p.ext_id
FROM provider_report p
LEFT JOIN transactions o ON o.ext_id = p.ext_id
WHERE o.ext_id IS NULL;

It is UNION ALL here, not UNION: the parts no longer overlap, and UNION also removes duplicates, which can hide real repeats. In PostgreSQL FULL JOIN is supported only for conditions that can be run with a merge or a hash, in practice mainly equality. For reconciling sets there are other tools too: EXCEPT gives the difference in one direction but does not show values from both sides side by side. CROSS JOIN needs care:

-- a test data matrix: roles × browsers
SELECT r.name AS role, b.name AS browser
FROM roles r
CROSS JOIN browsers b;
-- 4 roles × 3 browsers = 12 rows

The result size equals the product: 4 × 3 gives 12 rows, but for 10,000 × 10,000 it is a hundred million. So CROSS JOIN is applied to small reference tables (roles, browsers, languages), not to data tables.

Common mistakes.

  • Reconciling only with a LEFT JOIN: mismatches on the other side stay unnoticed.
  • Looking for FULL JOIN in MySQL: it does not exist, a union of two parts is needed.
  • Writing UNION instead of UNION ALL in the MySQL variant: real duplicates disappear.
  • Reconciling on keys of different formats: mass "mismatches" because of a space or case.
  • CROSS JOIN on large tables: the product of sizes exhausts memory and time.
  • Writing RIGHT JOIN where it is more readable to swap the tables and take LEFT.

Check yourself

We have 1000 transactions, the provider statement has 990, and 985 match. How many rows does a FULL OUTER JOIN on the key return and how many of them are mismatches?

Answer

1000 + 990 − 985 = 1005 rows in total. There are 20 mismatches: 15 exist only on our side (1000 − 985) and 5 only on the provider side (990 − 985). This assumes the key is unique on both sides.

In a reconciliation the key on the provider side is NULL in a few rows. What happens to those rows in a FULL OUTER JOIN on key equality?

Answer

NULL equals nothing, so these rows find no pair and land in the result as right-only rows with NULL on the left. In the mismatch report they will look like "missing on our side", although the real cause is a defect in the statement, so the column with NULL must be checked separately.

In an interview. Junior: RIGHT JOIN is the mirror of LEFT, and it is usually replaced by LEFT with the tables swapped. FULL OUTER JOIN returns everything from both sides and suits reconciling two sets, and CROSS JOIN gives all combinations. Middle/Senior: I pick the kind by whose rows without a pair must be kept. For reconciliation I take FULL OUTER JOIN with an IS NULL filter on both sides, and in MySQL I build it from two LEFT JOINs through UNION ALL. I normalise the keys, because otherwise pairs are not found. I leave CROSS JOIN to small reference tables.

How do you find records that have no match in another table?

An anti-join returns the rows of the left table that have no pair in the right one. It is written as a LEFT JOIN with the right key IS NULL, or as NOT EXISTS. NOT IN with a subquery is avoided: a single NULL in it makes the query return 0 rows, hiding the defect. A LEFT JOIN checks a column that cannot be NULL, ideally the primary key.

SQL · JOIN

After sign-up some users have no account or order. How do you find all of them in one query?

One of the most useful integrity checks is the search for "orphans": users without orders, orders without a payment, transactions without a log entry. The technique is called an anti-join. It can be written three ways, and one of them silently returns 0 rows exactly when the data has a defect. This lesson shows all three, explains why NOT IN lets you down and gives a rule of choice.

How it works and why. An anti-join returns the rows of the left table that have no pair on the right. There are two safe ways to write it. The first: LEFT JOIN and selecting rows where the right table's key IS NULL. LEFT JOIN keeps a row without a pair with NULLs in the right columns, and we keep exactly those. The second: NOT EXISTS with a subquery that checks for a pair. Both give the same result, and modern optimisers (PostgreSQL, MySQL 8.0.17+) plan them as an anti-join without multiplying rows.

The third way, NOT IN (SELECT …), reads the simplest but has a three-valued logic trap. x NOT IN (1, 2, NULL) expands to "x is not 1 AND not 2 AND not NULL". The last comparison gives UNKNOWN, so the whole expression never becomes true: at best UNKNOWN, and WHERE takes only true.

Example: an empty result that looks like "all is well". Users: Anna (1), Ivan (2), Olha (3). Orders: 100 and 101 belong to Anna, 102 to Ivan, 103 is a guest order with user_id = NULL. Someone writes:

SELECT id, email
FROM users
WHERE id NOT IN (SELECT user_id FROM orders);
-- 0 rows, although Olha has no orders

The query returns 0 rows. The conclusion "everyone has an order" would be a mistake: the subquery contains a NULL (the guest order), and for Olha the expression 3 NOT IN (1, 1, 2, NULL) is UNKNOWN. A test for "no orphans" passes and the defect stays. The fix:

-- NOT EXISTS: safe with NULL
SELECT u.id, u.email
FROM users u
WHERE NOT EXISTS (
  SELECT 1 FROM orders o WHERE o.user_id = u.id
);

-- LEFT JOIN + IS NULL: the same, test the right table key
SELECT u.id, u.email
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
WHERE o.id IS NULL;

Both queries return Olha. The fact that a NULL exists in orders.user_id is a finding too, but a different one: it is a guest order and should be asked about separately (WHERE user_id IS NULL).

Why NOT IN returns nobody

id NOT IN (1, 1, 2, NULL)
userresult
1 AnnaFALSE
2 IvanFALSE
3 OlhaUNKNOWN filtered
NOT EXISTS
userresult
3 OlhaTRUE
Figure 1. For Olha, NOT IN gives UNKNOWN because of the NULL in the list, and the row is dropped. NOT EXISTS finds her.

Which way to choose

NOT EXISTSNULLs in the data do not affect the resultLEFT JOIN … IS NULLtest a NOT NULL column of the right tableNOT IN (subquery)one NULL in the subquery and you get 0 rows
Figure 2. NOT EXISTS and LEFT JOIN … IS NULL are safe. NOT IN is safe only when the subquery is guaranteed to have no NULL.

Limits and alternatives. For an anti-join with LEFT JOIN, test a column that cannot be NULL in a real row, best of all the right table's primary key. If you test a nullable column (o.total IS NULL), real orders with an empty amount land in the result, which are false "orphans". A condition on the right table that is not part of the link goes in ON (for example "users without an active account": ON a.user_id = u.id AND a.status = 'active'), while IS NULL stays in WHERE; a separate lesson covers this. There is also EXCEPT: SELECT id FROM users EXCEPT SELECT user_id FROM orders returns only keys, not full rows, and treats NULLs as equal values. An anti-join on a composite key requires comparing all columns in NOT EXISTS or ON. On large tables speed depends on an index on the link column in the right table, and the anti-join result is usually small, so it is convenient to add as a check in automated tests: 0 rows are expected.

Common mistakes.

  • NOT IN with a subquery where NULL is possible: 0 rows, and the check wrongly "passes".
  • IS NULL on a column that allows NULL: the result has "orphans" that are not there.
  • Putting the right table's status condition in WHERE: the search turns into plain filtering.
  • Looking for "orphans" through INNER JOIN: such rows disappear from it by definition.
  • Not looking separately at NULL in the foreign key: guest or broken records stay out of sight.

Check yourself

SELECT * FROM users WHERE id NOT IN (SELECT user_id FROM orders) returned 0 rows, although SELECT COUNT(*) FROM users shows 3 users and one of them never bought anything. Name the most likely cause and the check.

Answer

orders.user_id contains NULL (a guest or broken order), and NOT IN returns nothing because of UNKNOWN. The check: SELECT COUNT(*) FROM orders WHERE user_id IS NULL. The fix: NOT EXISTS or LEFT JOIN … IS NULL.

To find users with no active account, someone writes LEFT JOIN accounts a ON a.user_id = u.id WHERE a.status IS NULL. Why is this query wrong?

Answer

It does not check for active. A user with only a closed account has status = closed, not NULL, and will not be in the result, while an account with an empty status gives a false match. The right way: move the active condition into ON (ON a.user_id = u.id AND a.status = 'active') and test the key in WHERE: WHERE a.id IS NULL.

In an interview. Junior: I find records without a pair with a LEFT JOIN and the condition that the right table's key IS NULL, or with NOT EXISTS. It is one of my main queries for integrity checks: for example users without an account or transactions without a log entry. Middle/Senior: I avoid NOT IN with a subquery: one NULL turns the result empty and hides the defect. For LEFT JOIN I test a column that cannot be NULL (the right table's primary key) and put pair conditions in ON. I add such queries to automated tests with 0 rows expected.

What is the difference between a condition in ON and in WHERE with a LEFT JOIN?

A condition in ON decides what counts as a pair, so left rows without a pair are kept, while WHERE filters the joined result. An ordinary comparison with a right-table column is UNKNOWN on rows without a pair, so WHERE drops them and the LEFT JOIN becomes an INNER one. Hence conditions on the right table go into ON, and WHERE keeps left-table filters and the IS NULL of an anti-join.

SQL · JOIN

The report should show all users and their active accounts, and only Anna is left. What broke the LEFT JOIN?

The report "all users and active accounts, if any" suddenly shows one user. The query is written with a LEFT JOIN, so everyone should remain. The difference is where the condition status = 'active' is written: in ON or in WHERE. One moved line changes the meaning of the query, and there is no error. This lesson explains when each condition runs and why it separates LEFT JOIN from INNER.

How it works and why. The ON condition is part of the join itself: it decides which rows of the right table count as a pair for a left row. If none passed, the left table still keeps the row with NULL on the right. WHERE runs after the join, when a "row with no pair" already has NULL in its columns. The condition a.status = 'active' on such a row gives UNKNOWN (NULL equals nothing), and WHERE drops it. The result: all rows without a pair vanished, and LEFT JOIN became INNER JOIN. This order is part of the logical sequence of a query: first FROM … JOIN … ON, then WHERE.

Example: from one user to three. Users Anna, Ivan, Olha. Accounts: 10 (Anna, active), 11 (Anna, closed), 12 (Ivan, closed). Olha has no account.

-- wrong: WHERE after the join drops rows with NULL
SELECT u.email, a.id AS account_id
FROM users u
LEFT JOIN accounts a ON a.user_id = u.id
WHERE a.status = 'active';
-- 1 row: only Anna

-- right: the pair condition in ON
SELECT u.email, a.id AS account_id
FROM users u
LEFT JOIN accounts a
  ON a.user_id = u.id AND a.status = 'active';
-- 3 rows: Anna with 10, Ivan and Olha with NULL

WHERE versus ON on the same data

LEFT JOIN with no filter
emailaccountstatus
anna10active
anna11closed dropped
ivan12closed dropped
olhaNULLNULL dropped
condition in ON
emailaccountstatus
anna10active
ivanNULLNULL
olhaNULLNULL
Figure 1. WHERE keeps only Anna’s row. The condition in ON keeps all users, but does not attach the closed account to Ivan.

Let us take it apart. The first query returns only Anna with account 10: the rows of Ivan and Olha are dropped, because closed = 'active' is false, and for Olha it is UNKNOWN. The second query keeps everyone, and Ivan is shown with NULL: a closed account does not count as a pair. If that is the report needed ("a user and their active account, if there is one"), only the second is right. A sign that the query is spoiled: in a report on "everyone" the row count equals that of an INNER JOIN.

Limits and alternatives. The rule "a condition on the right table goes in ON" applies where the left rows must be kept. There are three situations where WHERE on the right table is justified. First: INNER JOIN, where there is no difference between ON and WHERE. Second: the orphan search, where WHERE a.id IS NULL deliberately tests for NULL. Third: a filter that really must remove users without a matching account, that is an INNER JOIN is needed, and it is better written as one.

There is a reverse case that surprises people. A condition on the left table in ON does not remove left rows, because LEFT JOIN keeps them by definition:

-- a condition on the LEFT table in ON does not remove its rows
SELECT u.email, o.id
FROM users u
LEFT JOIN orders o
  ON o.user_id = u.id AND u.email = 'anna@test.com';
-- 4 rows: Anna 100, Anna 101, Ivan NULL, Olha NULL

-- to filter the left side you need WHERE
SELECT u.email, o.id
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
WHERE u.email = 'anna@test.com';

In the first query Ivan and Olha stay, and Ivan is shown with no order: the condition u.email = … only denied him a pair. Whoever writes such a condition usually wanted to filter users, and the result turns out wrong with no signal. For the left table the filter is always in WHERE. For FULL JOIN both sides are kept, so a condition in ON removes rows from neither, and a condition in WHERE on one side's column drops the rows that exist only in the other table (that column is NULL in them), so the FULL JOIN becomes a LEFT or RIGHT JOIN (conditions on both sides make it INNER).

Where to put the condition

Typical

WHERE a.status = 'active'

Filters the finished result. Rows without a pair disappear, LEFT JOIN becomes INNER.

Better

ON … AND a.status = 'active'

The condition is part of the pair search. All left rows are in place, NULL where there is no pair.

Figure 2. A condition on the right table in ON limits what is attached. In WHERE it filters out the result.

Common mistakes.

  • A condition on the right table of a LEFT JOIN in WHERE: rows without a pair vanish, LEFT JOIN becomes INNER.
  • A condition on the left table in ON in the hope of filtering it: the left side is not filtered.
  • Expecting "all users" from a report when the query has already turned into INNER: fewer rows than in the table and no error.
  • "Treating" the vanished rows by adding OR a.id IS NULL to WHERE: it works by accident and breaks when the data changes.
  • Not checking the row count of a LEFT JOIN: it is not smaller than the left table, and a smaller number means a wrong WHERE.

Check yourself

users has 100 rows. The query users u LEFT JOIN accounts a ON a.user_id = u.id WHERE a.status = 'active' returned 40 rows. Does it mean 60 users have no active account?

Answer

Not necessarily: 40 is rows, not users. If a user has two active accounts, they give two rows, so fewer than 40 users may have an active account and more than 60 have none. For a report on all 100, move the condition into ON: then there will be at least 100 rows.

Why does LEFT JOIN orders o ON o.user_id = u.id AND u.country = 'UA' return users from all countries?

Answer

A condition on the left table in ON only denies users from other countries a pair, and LEFT JOIN keeps them with NULL in the right columns. A country filter must be in WHERE.

In an interview. Junior: With LEFT JOIN a condition on the right table in ON only limits what is attached, and all left rows stay. The same condition in WHERE drops rows with NULL on the right, and LEFT JOIN effectively becomes INNER. Middle/Senior: ON works during the join, WHERE after it, and NULL gives UNKNOWN. So I write the pair condition for the right table in ON and a filter on the left in WHERE. The exception is an anti-join, where WHERE a.id IS NULL is deliberate. A query like this runs without errors and returns less data, so I check that the row count is not smaller than the left table.

Why did the row count grow after a JOIN and the sum double?

After a one-to-many JOIN the parent row is repeated once per pair, so sums over its columns are inflated. This shows when COUNT(*) is larger than COUNT(DISTINCT key). SUM(DISTINCT) does not fix it: it removes equal values, not duplicated orders. The child table is collapsed to one row per parent before the join.

SQL · JOIN

Revenue in the report is 150 and the orders table says 100. Nothing changed, a JOIN to payments was only added.

A join with payments was added to a query about orders to show how much is already paid. The sum of orders grew from 100 to 150. Nothing changed in the data and there is no error. The rows multiplied: one order had two payments and landed in the result twice. This lesson is about row multiplication (fan-out), how to notice it, why SUM(DISTINCT) does not save you and how to restructure the query. How this looks from the tester's side in reports is covered in the QA Fundamentals lesson on kinds of JOIN; here the mechanics go deeper.

How it works and why. JOIN outputs one row per pair. If the link is one-to-many (one order, several payments), the left row repeats as many times as it has pairs. The values in the repeats do not change, so every column of the left table counts as many times as there are pairs. SUM, COUNT and AVG over such a column are distorted. An aggregate is safe only for columns of the level that matches the finest table in the query. Hence the rule: aggregate at the level where each value occurs once.

Example: why 150. Orders: 100 (50), 101 (30), 102 (20). Payments: p1 (order 100, 25), p2 (order 100, 25), p3 (order 101, 30). The query:

-- total of orders: the table says 100
SELECT SUM(o.total) AS revenue
FROM orders o
LEFT JOIN payments p ON p.order_id = o.id;
-- 150: order 100 is counted twice

The result is 150: the row of order 100 is repeated twice (50 + 50), 101 once, and 102 once thanks to the LEFT JOIN. The true sum is 100. Diagnostics do not rely on guesses: they compare the row count with the number of distinct keys and find what multiplies:

-- how many rows and how many distinct orders
SELECT COUNT(*) AS rows_cnt, COUNT(DISTINCT o.id) AS orders_cnt
FROM orders o
LEFT JOIN payments p ON p.order_id = o.id;
-- 4 and 3: the link multiplies rows

-- who multiplies
SELECT order_id, COUNT(*) AS pay_cnt
FROM payments
GROUP BY order_id
HAVING COUNT(*) > 1;

How payments multiplied the orders

payments
idorder_idamount
p110025
p210025
p310130
orders LEFT JOIN payments
ordertotalpayment
10050p1
10050p2
10130p3
10220NULL
Figure 1. Order 100 has two payments, so its total 50 enters the result twice.

The fix depends on the question. If you need the sums of orders and payments together, first collapse payments to one row per order and then join:

-- first collapse payments to one row per order
SELECT SUM(o.total) AS revenue,
       SUM(COALESCE(p.paid, 0)) AS paid
FROM orders o
LEFT JOIN (
  SELECT order_id, SUM(amount) AS paid
  FROM payments
  GROUP BY order_id
) p ON p.order_id = o.id;
-- revenue 100, paid 80

Here each order occurs once, so SUM(o.total) gives 100 and the paid amount is 80. A second option, when payment sums are not needed: do not join at all and check that a payment exists with EXISTS. That does not multiply rows by definition.

Limits and alternatives. The temptation: SUM(DISTINCT o.total). On our set it gives 100 and looks like a fix, but only by coincidence: DISTINCT deduplicates values, not orders. If two different orders have the same amount 50, one of them vanishes and the sum is understated. COUNT(DISTINCT o.total) makes the same mistake. The right way is to deduplicate by key (COUNT(DISTINCT o.id) is safe), but that does not work for sums, so collapsing before the join or a subquery is needed. In PostgreSQL and MySQL 8 a CTE or a derived table fits. Another option: a scalar subquery in SELECT (SELECT SUM(amount) FROM payments p WHERE p.order_id = o.id) sums payments per order without a JOIN, so rows do not multiply.

An aggregate before and after the JOIN

Typical

JOIN, then SUM

Each left row repeats by the number of pairs. The sum is 150 instead of 100.

Better

collapse, then JOIN

Payments are reduced to one row per order. The sum is 100, payments separately 80.

Figure 2. Aggregate at the level where values do not repeat, and only then join.

A separate form of the problem is two one-to-many links in one query: an order with payments and with shipments. Each order produces a product of pairs "payment × shipment", so both payment sums and shipment sums are overstated. The cure is the same: collapse each "child" set on its own.

Common mistakes.

  • Aggregating a parent table column after a one-to-many JOIN: sums are overstated.
  • SUM(DISTINCT) as a "fix": it works on test data with different values and breaks when two amounts coincide.
  • Not comparing COUNT(*) with COUNT(DISTINCT key) after the join: the multiplication is invisible.
  • Joining two child tables to a parent in one query without collapsing: a product of pairs.
  • Believing the sum in a report is right because it looks plausible: a coincidence of two errors (a duplicate and a lost row) can produce the right number.

Check yourself

orders has 3 orders of 100 each and each has two payments. What does SUM(o.total) return after an INNER JOIN payments and why would SUM(DISTINCT o.total) give 100 here?

Answer

SUM(o.total) = 600, because each of the 3 orders is counted twice. SUM(DISTINCT o.total) = 100, because all three amounts are equal and DISTINCT keeps one value, while the real sum is 300. So DISTINCT gives a wrong result in the opposite direction.

How can one query tell you whether a JOIN multiplies rows, without knowing the schema?

Answer

Compare SELECT COUNT(*) with SELECT COUNT(DISTINCT o.id) for the same join (o is the left side). If the first number is bigger, the left row repeats. Find the source by grouping the right table by the link key with HAVING COUNT(*) > 1.

In an interview. Junior: In a one-to-many link each row of the "one" side repeats as many times as it has pairs, so sums over its columns after a JOIN are overstated. You must aggregate before the join or aggregate from the table where each value occurs once. Middle/Senior: Before an aggregate after a JOIN I compare COUNT(*) with COUNT(DISTINCT key) and look at the uniqueness of the join key. I collapse a child set in a subquery or CTE to one row per parent. I do not treat SUM(DISTINCT) as a fix: it deduplicates values, not rows.

What is a self join?

A self join joins a table to itself through two aliases when a row refers to another row of the same table, such as an employee to a manager. It is an ordinary INNER or LEFT JOIN, not a separate kind. The ON direction is read as a sentence: m.id = e.manager_id means "m is the manager of e". It sees one hierarchy level; deeper ones need a recursive CTE.

SQL · JOIN

Find employees who earn more than their manager. But the manager is also a row in employees. How?

In the employees table each row has a manager_id column that points to the id of another row of the same table. To compare an employee's salary with the manager's, both rows are needed in one result row. For that the table is joined to itself. This lesson is about how to read a self join, why it is easiest to write backwards and where it is used besides hierarchies.

How it works and why. A self join is not a separate kind of JOIN but an ordinary INNER or LEFT JOIN where both sides are the same table. For the database to tell them apart, each gets its own alias, and then the table plays two roles. For example e is the employee, m the manager, and the condition m.id = e.manager_id reads as "m is the manager of e". The meaning of the query depends on the role each alias has.

One table in two roles

e (employee)m (manager)OlenaPetroMaksIrynaOlenaPetroOne table in two roles: e and m.Olena has no manager: INNER drops her.
Figure 1. The arrow leads from an employee to their manager. Olena has no pair, because her manager_id is NULL.

Example: a plausible answer, backwards. Data: Olena (5000, no manager), Petro (4000, manager Olena), Maks (5500, manager Olena), Iryna (3000, manager Petro). A query with the direction swapped:

-- wrong: ON reversed (m.manager_id = e.id), direction swapped
SELECT e.name
FROM employees e
JOIN employees m ON m.manager_id = e.id
WHERE e.salary > m.salary;
-- Olena, Petro: they earn more than their SUBORDINATES

It runs and returns two people, and that looks plausible. But m.manager_id = e.id means that e is the boss here and m the subordinate, so the query answers "who earns more than a subordinate". The report would name the wrong people: Olena and Petro instead of Maks. The right version reads "m is the manager of e":

SELECT e.name AS employee, e.salary,
       m.name AS manager, m.salary AS manager_salary
FROM employees e
JOIN employees m ON m.id = e.manager_id
WHERE e.salary > m.salary;
-- Maks 5500 > Olena 5000

Self join and the salary filter

e LEFT JOIN m
employeesalarymanagertheir salary
Olena5000NULLNULL filtered
Petro4000Olena5000 filtered
Maks5500Olena5000
Iryna3000Petro4000 filtered
WHERE e.salary > m.salary
employeesalary
Maks5500
Figure 2. LEFT JOIN is shown for clarity: with JOIN Olena's row would not exist at all, and here the comparison with NULL gives UNKNOWN, Petro and Iryna earn less than their managers. Maks remains.

A practical check: before adding the filter, output both sides (e.name, m.name) and read a few rows aloud: "employee Petro, manager Olena". If the sentence is wrong, the ON is written backwards.

Limits and alternatives. If you do not need the manager's whole row but only the fact that one exists, EXISTS is enough. Two more cases are typical for a self join. The first: finding pairs of equal values, for example duplicate emails:

-- pairs of users with the same email
SELECT a.id AS id1, b.id AS id2, a.email
FROM users a
JOIN users b ON b.email = a.email AND a.id < b.id;
-- a.id < b.id: each pair once, no pair with itself

The condition a.id < b.id does two jobs: it removes the pair of a row with itself and keeps each pair once rather than in both directions (a, b) and (b, a). Without it the result would be twice as large and would contain "duplicates" that are merely mirrors. For large tables it is faster to group by email and take HAVING COUNT(*) > 1, but a self join shows both identifiers side by side. The second case: hierarchies. A self join climbs one level (an employee and their manager). For any depth, for example the whole chain up to the director, a recursive query is needed:

-- the whole hierarchy, any depth
WITH RECURSIVE chain AS (
  SELECT id, name, manager_id, 1 AS lvl
  FROM employees WHERE manager_id IS NULL
  UNION ALL
  SELECT e.id, e.name, e.manager_id, c.lvl + 1
  FROM employees e
  JOIN chain c ON e.manager_id = c.id
)
SELECT name, lvl FROM chain ORDER BY lvl;

Recursive CTEs exist in PostgreSQL and MySQL 8 but need care: if reporting loops in the data (A manages B, B manages A), those people silently drop out of the report: the walk from roots with manager_id IS NULL never reaches them. Infinite recursion comes from walking up from an employee or from a many-parent graph: MySQL stops it at cte_max_recursion_depth (1000 by default), PostgreSQL has the CYCLE clause. A loop in the data is itself a defect and is found with a separate check, for example WHERE id = manager_id for the simplest case. The top level needs a LEFT JOIN, because INNER JOIN, as we saw, drops a person with no manager.

Common mistakes.

  • Not giving the table aliases: the database rejects the query or the columns get mixed up.
  • Swapping the ON direction (m.manager_id = e.id instead of m.id = e.manager_id): the query answers another question and the result looks plausible.
  • INNER JOIN where the top-level boss is needed: a person with no manager vanishes.
  • Searching for pairs without a.id < b.id: each row matches itself and pairs repeat as mirrors.
  • Expecting the whole hierarchy from a self join: it sees only one level.

Check yourself

employees has 1000 rows and 1 of them has manager_id = NULL. How many rows do INNER JOIN and LEFT JOIN return with m.id = e.manager_id?

Answer

INNER: 999, because the employee with no manager finds no pair. LEFT: 1000, and the first row has NULL in the m columns. This assumes every manager_id points to an existing employee.

Three users share the same email. How many rows does JOIN users b ON b.email = a.email AND a.id < b.id return for that email?

Answer

Three rows: the pairs (1,2), (1,3), (2,3), that is C(3,2). Without a.id < b.id there would be 9 rows: 3 × 3, including each row paired with itself and the mirrored pairs.

In an interview. Junior: A self join joins a table to itself when a row refers to another row of the same table, like an employee to a manager. The table is included twice with different aliases. LEFT JOIN is needed so the top-level boss is not lost. Middle/Senior: I read ON as a sentence: "m is the manager of e", because the direction is easy to swap and the result stays plausible. To find duplicates I add a.id < b.id to remove mirrored pairs. A self join sees one level of a hierarchy, deeper ones need a recursive CTE, and I treat a loop in the data as a defect.

Types of JOIN and users without orders

JOIN kinds build pairs by the ON condition and differ only in the fate of rows without a pair. INNER drops them, LEFT keeps the left ones, RIGHT the right ones, FULL OUTER both, and CROSS has no condition and returns all combinations. Users without orders are found with LEFT JOIN and o.id IS NULL or NOT EXISTS; NOT IN is avoided because one NULL gives an empty result.

SQL · JOIN

An interviewer asks: show all kinds of JOIN and find users with no orders. Where do you start?

This is a typical question that is easy to answer with a memorised list and hard to answer in a way that shows understanding. An answer that works starts not with names but with one question: what should happen to a row that has no pair. This lesson gathers the JOIN topic into one shape of answer, with numbers on a concrete data set and with the trap that the interviewer usually looks for.

How it works and why. All kinds of JOIN build pairs of rows by the ON condition and differ only in the fate of rows without a pair. INNER drops them on both sides, LEFT keeps the left ones, RIGHT the right ones, FULL OUTER both, and CROSS has no condition and outputs all combinations. SELF JOIN is not a separate kind but an ordinary JOIN where a table is joined to itself through aliases. So the line of reasoning is the same for any of them: which pair am I looking for, whose rows must survive, how many rows do I expect.

Example: one data set, five results. Three users (Anna, Ivan, Olha) and four orders: 100 and 101 belong to Anna, 102 to Ivan, 103 is a guest order with user_id = NULL.

SELECT u.email, o.id FROM users u JOIN orders o       ON o.user_id = u.id;
SELECT u.email, o.id FROM users u LEFT JOIN orders o  ON o.user_id = u.id;
SELECT u.email, o.id FROM users u RIGHT JOIN orders o ON o.user_id = u.id;
SELECT u.email, o.id FROM users u FULL JOIN orders o  ON o.user_id = u.id;
SELECT u.email, o.id FROM users u CROSS JOIN orders o;

One data set, five kinds of JOIN

INNER: 3 rowspairs only: Anna ×2, IvanLEFT: 4 rows+ Olha with NULL (a user with no orders)RIGHT: 4 rows+ order 103 with NULL (no user)FULL OUTER: 5 rowsboth sides: Olha and order 103CROSS: 12 rowsno condition: 3 × 4 pairs
Figure 1. The difference in row counts is the difference in the fate of rows without a pair: Olha and order 103.

The numbers are useful as a self-check: INNER gives 3, because there are three pairs. LEFT adds Olha, because she is on the left. RIGHT adds order 103, because it is on the right. FULL OUTER adds both, so 3 + 1 + 1 = 5. CROSS ignores the link and gives 3 × 4 = 12. If the result does not match the expectation, the cause is almost always in one of three places: a NULL in the key (row 103), a duplicate of pairs (row multiplication) or a condition in the wrong place (ON or WHERE).

The second part of the question, users without orders, tests whether you know the NULL trap. The data holds order 103 with user_id = NULL, so the naive variant gives 0 rows:

-- users with no orders: Olha
SELECT u.id, u.email
FROM users u
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id);

-- NOT IN gives 0 rows, because orders.user_id has a NULL (order 103)
SELECT u.id, u.email
FROM users u
WHERE u.id NOT IN (SELECT user_id FROM orders);

The same search, two ways

Typical

NOT IN (subquery)

Because of the NULL in the subquery the result is empty. The conclusion "everyone bought something" is wrong.

Better

NOT EXISTS

Finds Olha. LEFT JOIN … IS NULL on the right table key gives the same.

Figure 2. The answer "NOT EXISTS or LEFT JOIN and IS NULL" shows that you know about NULL.

Limits and alternatives. Not every case is solved by a kind of JOIN. If you only need to check that a related record exists, EXISTS does not multiply rows. If you compare two sets of keys, there are EXCEPT and INTERSECT. Dialects differ: MySQL has no FULL OUTER JOIN, in PostgreSQL a JOIN without ON is an error and in MySQL it works as CROSS. It is also worth mentioning that the optimiser chooses the order and method itself, so the kind of JOIN defines the meaning of a query, not its speed: speed depends on indexes on the link columns.

Common mistakes.

  • Starting with a list of names instead of the question "what to do with a row without a pair".
  • A condition on the right table of a LEFT JOIN in WHERE: the query quietly becomes INNER.
  • A sum or count after a one-to-many JOIN without checking the row count.
  • NOT IN with a subquery where NULL is possible: an empty result that looks like "no orphans".
  • A forgotten link condition: a Cartesian product instead of pairs.
  • Promising FULL OUTER JOIN in MySQL: it does not exist.

Check yourself

Table A has 10 rows and B has 10. 7 pairs match by key, and the key is unique on both sides. How many rows do INNER, LEFT and FULL OUTER return?

Answer

INNER: 7. LEFT: 10 (7 pairs and 3 on the left with no pair). FULL OUTER: 13 (7 pairs, 3 only from A, 3 only from B). CROSS would give 100.

How does a CROSS JOIN with WHERE o.user_id = u.id differ from an INNER JOIN on the same users and orders?

Answer

The result is the same, 3 rows, because WHERE filters out all non-matching combinations. The planner runs both the same way, but INNER JOIN with ON reads unambiguously and a missing condition stands out. For LEFT JOIN such a swap is impossible: WHERE would remove the rows without a pair.

In an interview. Junior: INNER JOIN returns only rows that have a pair in both tables. LEFT JOIN returns all rows of the left table and NULL where there is no pair. RIGHT does the same for the right one, FULL returns everything from both sides, CROSS gives all combinations, and SELF JOIN joins a table to itself. I find users without orders with a LEFT JOIN and WHERE o.id IS NULL. Middle/Senior: I choose the kind of JOIN by what to do with a row without a pair, and I estimate the row count beforehand. I write an anti-join with NOT EXISTS or LEFT JOIN … IS NULL and avoid NOT IN, because a NULL in the subquery gives an empty result. I keep conditions on the right table of a LEFT JOIN in ON and aggregate carefully after a one-to-many JOIN.