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

QA Fundamentals › SQL for QA

What kinds of JOIN are there?

JOIN kinds differ in how they treat an unmatched row: INNER drops it, LEFT and RIGHT keep their side with NULLs, FULL keeps both, CROSS pairs everything. A one-to-many join multiplies rows and inflates sums. A condition on the right table of a LEFT JOIN goes in ON; orphans are found with LEFT JOIN … IS NULL or NOT EXISTS, not NOT IN, which breaks on NULL.

QA Fundamentals · SQL for QA

After adding a JOIN the report total became bigger than the total in the table. Why?

A tester reconciles total revenue: the transactions table says 250, while a query with a JOIN to the audit log shows 300. It looks like an error in the data or in the system. In fact the query counted one transaction twice, because the log has two entries for it, and did not count another at all, because the log has none for it. This lesson is about how JOIN works, how its kinds differ and which mistakes it adds to checks.

How it works and why. The relational model splits data across tables: transactions in one, audit log entries in another, and the link is the transaction_id column. JOIN puts them back together: for each row of the left table it looks in the right one for rows that satisfy the ON condition and outputs one result row per pair. The kinds of JOIN differ in what happens to rows with no pair, and everything people expect from them follows from that.

Pairs of rows and a row with no pair

transactionsaudit_logt1t2t3a1 → t1a2 → t1a3 → t2t3 has no pair: INNER JOIN drops it,LEFT JOIN keeps it with NULLs on the right.
Figure 1. Each arrow is a result row. Row t1 has two entries, so it gives two rows. Row t3 has no pair.
KindWhat it returnsWhat QA uses it for
INNER JOINonly rows that have a pair in both tablescombine data when the link is mandatory
LEFT JOINall rows of the left; from the right the pair if there is one, otherwise NULLfind records without related data ("orphans")
RIGHT JOINthe mirror of LEFTrarely: the same is easier to write as LEFT with the tables swapped
FULL JOINall rows of both tables, with NULL where there is no paircompare two sets and see mismatches on both sides
CROSS JOINall possible pairs without a conditiongenerate combinations for test data

A special case, the self join: a table is joined to itself, for example an employee and their manager, or finding two records with the same value. MySQL has no FULL JOIN: it is replaced by a UNION of two LEFT JOINs. Choosing the kind is an answer to the question "what do I do with a row that has no pair": drop it, keep it with NULL or show it from both sides.

Example: the sum that grew, and orphans. The initial query and its result on a simplified data set (three transactions, two log entries for t1, one for t2, none for t3):

-- transactions: t1 = 100, t2 = 100, t3 = 50 (250 in total)
-- audit_log: two entries for t1, one for t2
SELECT SUM(t.amount)
FROM transactions t
JOIN audit_log a ON a.transaction_id = t.id;
-- 300: t1 counted twice, t3 is gone

Let us take it apart. For t1 there are two log entries, so its row is duplicated in the result and 100 is added twice. For t3 there is no entry, INNER JOIN drops it, and 50 disappears. A coincidence of two errors (an overstatement and an understatement) is especially dangerous, because the total looks plausible. This is "row multiplication" (fan-out): a one-to-many join repeats the left row as many times as there are right rows. The rule: before aggregating after a JOIN, think about how many rows will appear and whether the values you sum get duplicated. The fix depends on the goal:

-- the sum without a join: the source of truth is 250
SELECT SUM(amount) FROM transactions;

-- transactions with no audit entry (t3)
SELECT t.id, t.amount
FROM transactions t
LEFT JOIN audit_log a ON a.transaction_id = t.id
WHERE a.id IS NULL;

-- the same with NOT EXISTS (safer with NULL)
SELECT t.id, t.amount
FROM transactions t
WHERE NOT EXISTS (
  SELECT 1 FROM audit_log a WHERE a.transaction_id = t.id
);

The sum is taken from one table, where each transaction counts once. And the orphan search shows that t3 has no audit log entry: if it is mandatory by the requirement, it is a defect. The second query with LEFT JOIN … IS NULL and the third with NOT EXISTS give the same result. The third is more reliable, especially compared with NOT IN (SELECT …): if the subquery contains even one NULL, NOT IN returns no rows at all, and the check silently "passes".

The result on the same data

INNER JOIN

3 rows

t1, t1, t2. Transaction t3 vanished, and t1 appeared twice.

LEFT JOIN

4 rows

t1, t1, t2, t3. For t3 the right columns are NULL: that is what orphans are found by.

Figure 2. Both variants are right: they answer different questions. The difference is what to do with a row that has no pair.

Limits and alternatives. LEFT JOIN has one more subtlety: a condition on the right table belongs in ON, not in WHERE. A condition in WHERE on the right table drops rows with NULL and turns LEFT JOIN into INNER, and transactions with no event vanish from the report:

-- wrong: WHERE on the right table makes LEFT effectively INNER
SELECT t.id, a.event
FROM transactions t
LEFT JOIN audit_log a ON a.transaction_id = t.id
WHERE a.event = 'approved';

-- right: the condition in ON, transactions with no event stay
SELECT t.id, a.event
FROM transactions t
LEFT JOIN audit_log a
  ON a.transaction_id = t.id AND a.event = 'approved';

Besides JOIN, to check "is there a related record" EXISTS often fits, without duplicating rows. To compare two sets of values, use UNION or EXCEPT (MINUS in some databases). JOIN performance depends on indexes on the link columns, and on large tables of a shared environment a query with a stray CROSS JOIN can grow into hundreds of millions of rows, so start by limiting the selection.

Common mistakes.

  • Aggregating after a one-to-many JOIN without checking the row count: sums and counts are overstated.
  • Using INNER JOIN where you look for "what is missing": a row with no pair just disappears from the result.
  • Writing the condition on the right table of a LEFT JOIN in WHERE: the join quietly becomes INNER.
  • NOT IN with a subquery that contains NULL: an empty result that looks like "no orphans".
  • Forgetting the ON condition or writing it wrongly: a Cartesian product, millions of rows.
  • Not knowing that MySQL has no FULL JOIN: a UNION of two LEFT JOINs is needed.

Check yourself

The orders table has 100 orders and order_items has 3 items for each. How many rows does SELECT * FROM orders o JOIN order_items i ON i.order_id = o.id return, and what happens to SUM(o.total)?

Answer

There will be 300 rows if every order has exactly 3 items. Each row of orders is repeated as many times as it has items, so SUM(o.total) grows threefold against the real sum. For the sum of orders do not join with items, or aggregate separately.

How do you find customers who have no orders at all, and why is NOT EXISTS better than NOT IN?

Answer

LEFT JOIN orders ON orders.customer_id = customers.id WHERE orders.id IS NULL, or NOT EXISTS (SELECT 1 FROM orders WHERE customer_id = customers.id). NOT IN (SELECT customer_id FROM orders) returns an empty result when at least one customer_id in the subquery is NULL, and the mistake stays unnoticed.

In an interview. Junior: INNER JOIN returns only rows that have a pair in both tables, LEFT JOIN returns all rows of the left one and from the right one if there is a pair. I often use LEFT JOIN with a NULL check to find records with no mandatory related data, for example transactions with no audit log entry. Middle/Senior: I choose the kind of JOIN by what to do with a row that has no pair. I watch for row multiplication in one-to-many links: before summing after a JOIN I check the row count. I keep a condition on the right table of a LEFT JOIN in ON, use LEFT JOIN … IS NULL or NOT EXISTS to find orphans and avoid NOT IN because of NULL. I know FULL JOIN is emulated through UNION in MySQL.

More articles in this chapter