Skip to main content
CodeOath

Chapter 1 · About 12 minFree

Joins: which rows survive

Learn which rows each join keeps or drops, and how the wrong join quietly changes a report's totals, with self joins, non-equi joins and the cross join.

Published by Hem Mankad, founder of CodeOath and a software engineer for more than eight years. Prepared with AI assistance.

The Monday report

Nobody in Monday's 9am leadership meeting will read your SQL. They will look at a slide, nod, and decide something. That is why a wrong number here costs more than most bugs. A crashed script gets noticed at once. A query that drops a department, skips a row with a missing value, or returns zero rows when the honest answer was "everyone" raises no error. It makes a slide, and a wrong slide looks as sure of itself as a right one.

You have just inherited that report. Every Monday, five small queries run against two tables and turn into five slides:

  1. How big each team is.
  2. Who might be underpaid next to a teammate.
  3. Who earns the most on each team.
  4. Which teams have seats nobody has filled.
  5. A log of the last correction payroll made.

This is the one running example for the whole track. Every query you meet is one of these five, or a fix to one of them. You can run every statement in this track yourself. Paste the block below into any SQLite shell, which means the sqlite3 command line or any SQLite console. It starts by printing the SQLite version, because this track needs version 3.39 or newer. Window functions need 3.25, NULLS FIRST and NULLS LAST need 3.30, and RIGHT and FULL OUTER JOIN need 3.39. Each chapter says again where it first uses one of them.

SELECT sqlite_version();   -- should print 3.39.0 or higher

CREATE TABLE Departments (
  dept_id INTEGER PRIMARY KEY,
  dept TEXT NOT NULL
);

CREATE TABLE Employees (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  dept TEXT NOT NULL,
  salary INTEGER
);

INSERT INTO Departments (dept_id, dept) VALUES
  (1, 'Sales'), (2, 'IT'), (3, 'HR'), (4, 'Finance');

INSERT INTO Employees (id, name, dept, salary) VALUES
  (1, 'Alice', 'Sales', 50000),
  (2, 'Bob', 'Sales', 60000),
  (3, 'Carol', 'IT', 70000),
  (4, 'Dave', 'IT', NULL),
  (5, 'Eve', 'HR', 55000);

Two facts are baked into this data on purpose. You will trip over both of them again and again, in places that look unrelated.

  • Finance has a budget and nobody in it yet. The job is open. The seat is real. The person does not exist.
  • Dave started this week. He has a badge, a desk and a row in Employees. He has no number in salary, because payroll's paperwork has not cleared. That is not 0 and it is not blank. The value is missing.

A lot of wrong numbers in a report like this trace back to one of those two facts.

Join types and what each one keeps

Diagram comparing INNER, LEFT, RIGHT, and FULL OUTER JOIN using overlapping Departments and Employees circles

Slide one is the simplest thing on the report: headcount by department. You write the obvious query.

SELECT d.dept, COUNT(e.id) AS employee_count
FROM Departments d
JOIN Employees e ON d.dept = e.dept
GROUP BY d.dept;

Three rows come back: HR 1, IT 2, Sales 2. Finance is not there. It does not show as "Finance: 0". It is missing. For a slide that should list every department, a missing row is worse than a wrong number, because nothing in the output looks incomplete. You would have to already know that Finance exists.

A plain JOIN is an INNER JOIN. Every engine treats the bare word JOIN that way. An inner join keeps a row only when both sides have a match. Finance has no rows in Employees, so it is dropped before GROUP BY ever runs. There is nothing left to count, so no zero can appear.

Every join type answers one question for each row: this row has no partner on the other side, so does it survive or get dropped?

JoinWhat survives
INNER JOINOnly rows that found a partner on the other side
LEFT JOINEvery row from the left table. Unmatched rows get NULL in the right-hand columns
RIGHT JOINThe mirror image: every row from the right table, NULL on the left where nothing matches
FULL OUTER JOINEvery row from both tables, paired where a partner exists and NULL-filled where it does not

Change the keyword and Finance comes back:

SELECT d.dept, e.name
FROM Departments d
LEFT JOIN Employees e ON d.dept = e.dept;
-- Finance | NULL   (the row exists now, with no employee to attach)

LEFT JOIN means "keep every row from Departments, whatever happens." When Employees has nothing to match, the database keeps the department and fills every Employees column with NULL. Here is what the join produces before anything is counted:

deptname
SalesAlice
SalesBob
ITCarol
ITDave
HREve
FinanceNULL

(Row order may differ on your screen. Order is not part of the promise unless you write ORDER BY.) Dave appears because he has a row, even though his salary is missing. Finance appears once, with nothing beside it. That is six rows from a table of five employees and four departments. A habit worth building: before you trust a join, work out how many rows you expect and compare. Five employees, each in one real department, plus Finance with nobody, makes six. If the output had said four, or twenty, you would know to stop and look. Now use the join in the headcount query and Finance finally shows up:

SELECT d.dept, COUNT(e.id) AS employee_count
FROM Departments d
LEFT JOIN Employees e ON d.dept = e.dept
GROUP BY d.dept;
-- Finance | 0

Now look closely at why that 0 is right. The query counts e.id. For Finance, the join made up one row, and in that row e.id is NULL, because there is no employee to have an id. COUNT(column) skips NULL, so Finance gets 0.

Change COUNT(e.id) to COUNT(*) and Finance gets 1. The star counts rows, whatever is in them, and the join did hand back one row for Finance. Both numbers are true answers, but to different questions. Only one of them is "how many people work in Finance". Whenever you count across a LEFT JOIN, ask yourself: am I counting the thing I care about, or just the rows the join produced?

RIGHT JOIN is the same idea with the tables swapped. You will rarely see it on purpose.

SELECT d.dept, e.name
FROM Employees e
RIGHT JOIN Departments d ON d.dept = e.dept;
-- same result as the LEFT JOIN above, with the two tables swapped in FROM

Every row of Departments, the table on the right of this join, survives. Most style guides say to avoid RIGHT JOIN. Swapping the tables and writing LEFT JOIN says the same thing and reads left to right, the way people read.

A rule of thumb for the report. Start from the table whose rows must all appear, here Departments, and LEFT JOIN the table that may or may not have matches. Use INNER JOIN only when a row with no partner should really disappear. Read the join aloud before you run it: "every department, with its employees if it has any." If the sentence you say is not the sentence the slide needs, change the join.

FULL OUTER JOIN, and what to do without it

LEFT JOIN answers "which departments have no employees?" It says nothing about the opposite problem: an employee whose dept matches nothing in Departments. A headcount report for leadership should catch both. FULL OUTER JOIN catches both in one query:

SELECT d.dept, e.name
FROM Departments d
FULL OUTER JOIN Employees e ON d.dept = e.dept;

On today's five rows this matches the LEFT JOIN result, because every Employees.dept value exists in Departments. Now suppose a bulk import adds a sixth row with a typo, 'Sale' instead of 'Sales'. Do not run this against the shared table. It is here to show the idea:

-- hypothetical: INSERT INTO Employees (id, name, dept, salary) VALUES (6, 'Frank', 'Sale', 48000);
SELECT d.dept, e.name
FROM Departments d
FULL OUTER JOIN Employees e ON d.dept = e.dept;
-- Finance | NULL    (the empty-department case, as before)
-- NULL    | Frank   (new: an employee whose dept matches nothing)

The NULL | Frank row is why FULL OUTER JOIN is worth knowing. A LEFT JOIN starting from Departments would never show Frank, because Departments has never heard of him. He would vanish the way Finance vanished from the first query, only from the other side. One query run once catches a data problem on either side.

Postgres, SQL Server and SQLite 3.39 or later support FULL OUTER JOIN. Your SQLite does too if the version printed above is 3.39 or newer. Some engines do not, so check yours. Where it is missing, take a LEFT JOIN from each side and stack the results with UNION, which drops exact duplicates:

SELECT d.dept, e.name FROM Departments d LEFT JOIN Employees e ON d.dept = e.dept
UNION
SELECT d.dept, e.name FROM Employees e LEFT JOIN Departments d ON d.dept = e.dept;

Every employee who matched a department shows up in both halves, and UNION keeps one copy of each. That is why plain UNION is the right word here, and UNION ALL, which keeps duplicates, is not. On the table with Frank in it, you get the same two rows that needed attention, Finance with no one and Frank with no department. More typing, same answer. Use the native version when your engine has it.

Self joins and non-equi joins

Slide two is a pay-equity check. It flags anyone who may be underpaid next to a teammate, so a manager can find out whether there is a real reason for the gap.

There is no second table. A "teammate" is just another row of Employees with the same dept. So you join the table to itself, giving it two aliases as you would for two different tables. That is a self join. The aliases are not decoration. Without e1 and e2, the database could not tell which copy of Employees a column such as salary belongs to. Read e1 as "this employee" and e2 as "the teammate I am comparing against".

-- for every employee, find a teammate in the same department who earns more
SELECT e1.name AS employee, e2.name AS out_earned_by
FROM Employees e1
JOIN Employees e2 ON e1.dept = e2.dept AND e2.salary > e1.salary;
employee | out_earned_by
---------|---------------
Alice    | Bob

One row. Alice in Sales earns 50,000 and Bob earns 60,000. That is a fair flag, worth a manager's five minutes.

Now look at what is missing. IT has Carol at 70,000 and Dave with a NULL salary. You might expect a row pairing them. Nothing appears for IT at all, and nothing tells you why.

The reason is the comparison e2.salary > e1.salary. When either side of > is NULL, the answer is neither true nor false. It is a third thing, and a join keeps a row only when the condition is true. Dave is never compared and found too low. He is skipped as if nobody had asked. The next chapter explains this third answer properly.

This query has a second name as well. It is a non-equi join, because the operator doing the matching is >, not =. Nothing in JOIN ... ON demands equality. Any condition that comes out true or false works, including <= and BETWEEN. Non-equi joins are common outside HR data too. Which shift does this timestamp fall inside? Which pricing tier does this order size belong to? Anywhere two rows relate by range instead of by exact match.

The two names are independent. This query happens to be both, but neither needs the other. You could self-join Employees on plain equality, matching every pair of people in the same department with no pay comparison at all. You could also write a non-equi join between two different tables, such as matching an order amount against a PayBands table with min_amount and max_amount columns. The pay-equity query is both because the question needed both: comparing employees to each other makes it a self join, and asking who earns more than whom makes it non-equi.

Cross joins and the Cartesian product

Slide one went wrong in another way before the INNER JOIN dropped Finance. The very first draft was written in a hurry, the night before the first Monday meeting:

-- draft zero of slide one
SELECT e.name, d.dept
FROM Employees e, Departments d;

Two tables in FROM, separated by a comma, with no ON and no WHERE. It ran without complaint and returned twenty rows: five employees times four departments, every possible pairing. That is not a headcount. It is a CROSS JOIN, even though the word never appears. With no condition tying the tables together, every row on one side pairs with every row on the other, and you get (rows in A) × (rows in B).

SELECT e.name, d.dept
FROM Employees e
CROSS JOIN Departments d;
-- 5 employees × 4 departments = 20 rows, on purpose this time

Real uses exist. You might cross every date in a range with every hour of the day to give a scheduling tool a full grid of slots. They are rare, and headcount reporting is not one of them. What happens far more often is the accident you just saw: two tables listed with a comma, and nobody added the condition. The output does not look broken. Twenty rows is a believable size for a small report, nothing like an error message or an empty result.

That is the case for always writing JOIN ... ON, and for avoiding the comma form. Some engines refuse a JOIN that has no ON, which protects you. Do not count on it. Try this in your SQLite shell:

SELECT COUNT(*) FROM Employees e JOIN Departments d;
-- 20: SQLite treats the missing ON as a cross join and runs it

Forget the condition and the query can run, return a wrong answer, and wait for someone downstream to notice. The row-count habit from earlier is your other defence: five employees times four departments is twenty, and twenty is not a headcount. Writing the ON every time, even when you think it is obvious, is the habit that stops it.

Try it yourself in your SQLite shell. Run the headcount query with JOIN, then with LEFT JOIN, then with COUNT(*) instead of COUNT(e.id). Write down what changes for Finance each time before you look at the output. Guessing first, then checking, is what makes the three behaviours stick.

Practice

Practice in this chapter

  1. Select Every Sales EmployeeEasySQLNot started
  2. Employee Count Per DepartmentEasySQLNot started
Coming: the guide answers questions in a later release.