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

SQL › JOIN

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.

More articles in this chapter