Skip to content
Home/Resources/Data Analytics/SQL joins explained
Concept ยท Data Analytics

SQL joins explained with examples: inner, left, right, full, cross and self

Younus FardeenBy Younus FardeenUpdated 1 Dec 202612 min read
Short answer

A SQL join combines rows from two tables using a condition, usually matching keys. INNER JOIN keeps only matched rows. LEFT JOIN keeps every left row and fills gaps with NULL. RIGHT and FULL OUTER JOIN do the same for the right side or both. CROSS JOIN pairs every row with every row. A self join joins a table to itself.

On this pageWhich join keeps which rows: a decision tableThe two tables and every join, with outputSelf joins: a table joined to itselfThree mistakes that return wrong numbersPractice queries (with answers that ran)Frequently asked questions

This page uses two tables small enough to hold in your head, five employees and three departments, and runs every join type on them so you can see exactly which rows survive. Then it shows the three mistakes that cause most wrong answers in interviews and dashboards: duplicate keys that inflate totals, NULL keys that silently drop rows, and filters in the wrong place.

All code ran on SQLite 3.54.0 through Python's sqlite3 module. RIGHT JOIN and FULL OUTER JOIN need SQLite 3.39.0 or newer (released 25 June 2022, per the SQLite release history); MySQL has no FULL OUTER JOIN, which the text covers. For the wider interview set, see SQL interview questions; for the SQL dialect question, see SQL vs MySQL.

Which join keeps which rows: a decision table

Pick a join by asking one question: what should happen to a row that finds no match? The table below uses the data from the next section. Employees is the left table (5 rows), departments the right (3 rows). Neha has no department (a NULL key) and Legal has no employees.

JoinMatched pairsUnmatched left rows (Neha)Unmatched right rows (Legal)Rows returned here
INNER JOINKeptDroppedDropped4
LEFT JOINKeptKept, right columns NULLDropped5
RIGHT JOINKeptDroppedKept, left columns NULL5
FULL OUTER JOINKeptKept, right columns NULLKept, left columns NULL6
CROSS JOINEvery pairing, no conditionIncludedIncluded15 (5 x 3)
LEFT JOIN ... WHERE right key IS NULLDroppedKeptNot applicableAnti-join: only unmatched left rows

In everyday work you write INNER and LEFT joins almost every time. A RIGHT join is a LEFT join with the tables swapped, so many teams ban it for readability. FULL OUTER JOIN is for reconciliation: comparing two lists to see what is in one and not the other.

The two tables and every join, with output

The script creates employees(emp_id, name, dept_id, manager_id) and departments(dept_id, dept_name), then runs each join. Notice the three details: Neha's dept_id is NULL, Legal has no employee, and the ORDER BY clauses make the output order stable.

import sqlite3
print("SQLite", sqlite3.sqlite_version)   # RIGHT and FULL JOIN need 3.39.0 or newer
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE departments (dept_id INTEGER PRIMARY KEY, dept_name TEXT);
CREATE TABLE employees (emp_id INTEGER PRIMARY KEY, name TEXT, dept_id INTEGER, manager_id INTEGER);
INSERT INTO departments VALUES (1, 'Engineering'), (2, 'Sales'), (3, 'Legal');
INSERT INTO employees VALUES
 (1, 'Asha',  1, NULL),
 (2, 'Ravi',  1, 1),
 (3, 'Meera', 2, 1),
 (4, 'Karan', 2, 3),
 (5, 'Neha',  NULL, 3);
""")
def show(title, sql):
    print("--", title)
    for row in db.execute(sql): print("  ", row)

show("INNER JOIN", """SELECT e.name, d.dept_name FROM employees e
  INNER JOIN departments d ON d.dept_id = e.dept_id ORDER BY e.emp_id""")
show("LEFT JOIN", """SELECT e.name, d.dept_name FROM employees e
  LEFT JOIN departments d ON d.dept_id = e.dept_id ORDER BY e.emp_id""")
show("RIGHT JOIN", """SELECT e.name, d.dept_name FROM employees e
  RIGHT JOIN departments d ON d.dept_id = e.dept_id ORDER BY d.dept_id, e.emp_id""")
show("FULL OUTER JOIN", """SELECT e.name, d.dept_name FROM employees e
  FULL OUTER JOIN departments d ON d.dept_id = e.dept_id ORDER BY e.emp_id, d.dept_id""")
show("LEFT JOIN anti-join: departments with no employees", """SELECT d.dept_name FROM departments d
  LEFT JOIN employees e ON e.dept_id = d.dept_id WHERE e.emp_id IS NULL""")
show("CROSS JOIN (first 4 of all pairs)", """SELECT e.name, d.dept_name FROM employees e
  CROSS JOIN departments d ORDER BY e.emp_id, d.dept_id LIMIT 4""")
print("CROSS JOIN rows:", db.execute("SELECT COUNT(*) FROM employees CROSS JOIN departments").fetchone()[0])
SQLite 3.54.0
-- INNER JOIN
   ('Asha', 'Engineering')
   ('Ravi', 'Engineering')
   ('Meera', 'Sales')
   ('Karan', 'Sales')
-- LEFT JOIN
   ('Asha', 'Engineering')
   ('Ravi', 'Engineering')
   ('Meera', 'Sales')
   ('Karan', 'Sales')
   ('Neha', None)
-- RIGHT JOIN
   ('Asha', 'Engineering')
   ('Ravi', 'Engineering')
   ('Meera', 'Sales')
   ('Karan', 'Sales')
   (None, 'Legal')
-- FULL OUTER JOIN
   (None, 'Legal')
   ('Asha', 'Engineering')
   ('Ravi', 'Engineering')
   ('Meera', 'Sales')
   ('Karan', 'Sales')
   ('Neha', None)
-- LEFT JOIN anti-join: departments with no employees
   ('Legal',)
-- CROSS JOIN (first 4 of all pairs)
   ('Asha', 'Engineering')
   ('Asha', 'Sales')
   ('Asha', 'Legal')
   ('Ravi', 'Engineering')
CROSS JOIN rows: 15
  • INNER JOIN returned 4 rows: Neha and Legal are both missing, so a report built on it silently under-counts employees and hides empty departments.
  • LEFT JOIN kept Neha with None (SQL NULL) as her department. This is the join to use when the left table is the thing you are counting.
  • RIGHT JOIN kept Legal with a NULL employee. FULL OUTER JOIN kept both. In SQLite, NULLs sort first in ascending order, so Legal appears at the top of the full join; PostgreSQL sorts NULLs last by default.
  • Anti-join: LEFT JOIN ... WHERE e.emp_id IS NULL found Legal, the department with no staff. NOT EXISTS is the equivalent and is often preferred for clarity.
  • CROSS JOIN gave 15 rows, 5 x 3. Use it on purpose for generating combinations such as every product with every month, never by forgetting an ON clause.

MySQL has INNER, LEFT, RIGHT and CROSS joins but no FULL OUTER JOIN. The usual workaround is LEFT JOIN ... UNION ... RIGHT JOIN. PostgreSQL supports all of them. Older SQLite (before 3.39.0) matches MySQL here, so check sqlite3.sqlite_version, which the script prints on its first line.

You may also see JOIN ... USING (dept_id), which merges the shared column, and NATURAL JOIN, which joins on every column with the same name. Avoid NATURAL in real code: adding a column named created_at to both tables changes the join without any error.

Self joins: a table joined to itself

A self join uses the same table twice under different aliases. Two classic uses are hierarchies (employee and manager) and comparisons between rows of the same table. In the second query, a.emp_id < b.emp_id stops each pair appearing twice and stops a person pairing with themselves.

import sqlite3
print("SQLite", sqlite3.sqlite_version)   # RIGHT and FULL JOIN need 3.39.0 or newer
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE departments (dept_id INTEGER PRIMARY KEY, dept_name TEXT);
CREATE TABLE employees (emp_id INTEGER PRIMARY KEY, name TEXT, dept_id INTEGER, manager_id INTEGER);
INSERT INTO departments VALUES (1, 'Engineering'), (2, 'Sales'), (3, 'Legal');
INSERT INTO employees VALUES
 (1, 'Asha',  1, NULL),
 (2, 'Ravi',  1, 1),
 (3, 'Meera', 2, 1),
 (4, 'Karan', 2, 3),
 (5, 'Neha',  NULL, 3);
""")
def show(title, sql):
    print("--", title)
    for row in db.execute(sql): print("  ", row)

show("SELF JOIN: employee and manager", """SELECT e.name AS employee, m.name AS manager
  FROM employees e LEFT JOIN employees m ON m.emp_id = e.manager_id ORDER BY e.emp_id""")
show("SELF JOIN: pairs in the same department", """SELECT a.name, b.name FROM employees a
  JOIN employees b ON a.dept_id = b.dept_id AND a.emp_id < b.emp_id""")

# NULL keys never match, not even NULL = NULL
print("NULL = NULL gives:", db.execute("SELECT NULL = NULL").fetchone()[0])
print("Neha rows in INNER JOIN:", db.execute(
  "SELECT COUNT(*) FROM employees e JOIN departments d ON d.dept_id = e.dept_id WHERE e.name = 'Neha'").fetchone()[0])

# ON vs WHERE in a LEFT JOIN
show("filter in ON (keeps every employee)", """SELECT e.name, d.dept_name FROM employees e
  LEFT JOIN departments d ON d.dept_id = e.dept_id AND d.dept_name = 'Sales' ORDER BY e.emp_id""")
show("filter in WHERE (turns it into an inner join)", """SELECT e.name, d.dept_name FROM employees e
  LEFT JOIN departments d ON d.dept_id = e.dept_id WHERE d.dept_name = 'Sales' ORDER BY e.emp_id""")
SQLite 3.54.0
-- SELF JOIN: employee and manager
   ('Asha', None)
   ('Ravi', 'Asha')
   ('Meera', 'Asha')
   ('Karan', 'Meera')
   ('Neha', 'Meera')
-- SELF JOIN: pairs in the same department
   ('Asha', 'Ravi')
   ('Meera', 'Karan')
NULL = NULL gives: None
Neha rows in INNER JOIN: 0
-- filter in ON (keeps every employee)
   ('Asha', None)
   ('Ravi', None)
   ('Meera', 'Sales')
   ('Karan', 'Sales')
   ('Neha', None)
-- filter in WHERE (turns it into an inner join)
   ('Meera', 'Sales')
   ('Karan', 'Sales')

The manager query uses LEFT JOIN so Asha, who has no manager, still appears with None. An INNER JOIN there would drop the top of the hierarchy, a common interview slip. The output also shows the two remaining traps in this page, covered next.

Three mistakes that return wrong numbers

1. NULL keys never match

In the output above, NULL = NULL returned None, not true, so Neha has zero rows in the INNER JOIN. If your key can be NULL and the rows matter, use a LEFT JOIN or clean the key first. To compare columns that may be NULL, SQLite has IS and IS NOT; PostgreSQL has IS NOT DISTINCT FROM; MySQL has the <=> operator.

2. A filter on the right table in WHERE turns a LEFT JOIN into an INNER JOIN

The last two queries of the previous script show it. Putting d.dept_name = 'Sales' in ON kept all five employees and filled None for non-Sales. Putting it in WHERE removed everyone whose department was NULL or different, leaving only Meera and Karan. Rule: conditions that decide whether a match exists go in ON; conditions that remove final rows go in WHERE.

3. Join explosion: duplicate keys multiply rows

If the other side has several rows per key, each left row is repeated. Here an order paid in two instalments is joined to its payments, and summing the order amount counts it twice.

import sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE orders (order_id INTEGER PRIMARY KEY, amount INTEGER);
CREATE TABLE payments (payment_id INTEGER PRIMARY KEY, order_id INTEGER, paid INTEGER);
INSERT INTO orders VALUES (1, 1000), (2, 500);
INSERT INTO payments VALUES (1, 1, 600), (2, 1, 400), (3, 2, 500);   -- order 1 was paid in two parts
""")
print("true revenue:  ", db.execute("SELECT SUM(amount) FROM orders").fetchone()[0])
print("after the join:", db.execute(
  "SELECT SUM(o.amount) FROM orders o JOIN payments p ON p.order_id = o.order_id").fetchone()[0])
print("fix, aggregate the many side first:", db.execute("""
  SELECT SUM(o.amount) FROM orders o
  JOIN (SELECT order_id, SUM(paid) AS paid FROM payments GROUP BY order_id) p ON p.order_id = o.order_id""").fetchone()[0])
true revenue:   1500
after the join: 2500
fix, aggregate the many side first: 1500

True revenue is 1,500 but the join reported 2,500, because order 1 (1,000) matched two payment rows. Two defences: before joining, aggregate the many side down to one row per key, as the fix does, or count DISTINCT ids rather than rows. Always compare COUNT(*) before and after a join; if it grows when you expected one row per entity, you have a one-to-many join.

Practice queries (with answers that ran)

Try each one on the same two tables before reading the answer below. They map to the questions interviewers set most often, and the data analyst interview questions page has more in the same style.

  1. List employees with no department.
  2. Show headcount per department, including departments with nobody in them.
  3. Show each manager and how many people report to them.
  4. Find employees who work in a different department from their manager.
import sqlite3
print("SQLite", sqlite3.sqlite_version)   # RIGHT and FULL JOIN need 3.39.0 or newer
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE departments (dept_id INTEGER PRIMARY KEY, dept_name TEXT);
CREATE TABLE employees (emp_id INTEGER PRIMARY KEY, name TEXT, dept_id INTEGER, manager_id INTEGER);
INSERT INTO departments VALUES (1, 'Engineering'), (2, 'Sales'), (3, 'Legal');
INSERT INTO employees VALUES
 (1, 'Asha',  1, NULL),
 (2, 'Ravi',  1, 1),
 (3, 'Meera', 2, 1),
 (4, 'Karan', 2, 3),
 (5, 'Neha',  NULL, 3);
""")
def show(title, sql):
    print("--", title)
    for row in db.execute(sql): print("  ", row)

# Practice answers
show("1. Employees with no department", "SELECT name FROM employees WHERE dept_id IS NULL")
show("2. Headcount per department, including empty ones", """SELECT d.dept_name, COUNT(e.emp_id) AS headcount
  FROM departments d LEFT JOIN employees e ON e.dept_id = d.dept_id GROUP BY d.dept_id ORDER BY d.dept_id""")
show("3. Managers and how many people report to them", """SELECT m.name, COUNT(*) AS reports
  FROM employees e JOIN employees m ON m.emp_id = e.manager_id GROUP BY m.emp_id ORDER BY reports DESC, m.name""")
show("4. Employees working in a different department from their manager", """SELECT e.name FROM employees e
  JOIN employees m ON m.emp_id = e.manager_id WHERE e.dept_id IS NOT m.dept_id""")
SQLite 3.54.0
-- 1. Employees with no department
   ('Neha',)
-- 2. Headcount per department, including empty ones
   ('Engineering', 2)
   ('Sales', 2)
   ('Legal', 0)
-- 3. Managers and how many people report to them
   ('Asha', 2)
   ('Meera', 2)
-- 4. Employees working in a different department from their manager
   ('Meera',)
   ('Neha',)

Check the traps. Question 2 needs COUNT(e.emp_id) rather than COUNT(*): counting the right-hand column gives Legal zero instead of one. Question 4 uses IS NOT so that Neha, whose own department is NULL, is included; with <> she would vanish. To practise on real data, build the joins into a project from SQL projects for beginners or the ideas in free data analytics tools.

Frequently asked questions

What are the types of joins in SQL?

The main types are INNER JOIN, LEFT (OUTER) JOIN, RIGHT (OUTER) JOIN, FULL (OUTER) JOIN, CROSS JOIN and the self join, which is any of the others used with one table twice. INNER keeps matches only; LEFT and RIGHT also keep unmatched rows from one side; FULL keeps both; CROSS returns every pair.

What is the difference between INNER JOIN and LEFT JOIN?

INNER JOIN returns only rows with a match in both tables. LEFT JOIN returns every row from the left table, and where there is no match the right-hand columns are NULL. In the example, the inner join returned 4 employees and the left join returned all 5, including Neha.

What is a self join and when do you use it?

A self join joins a table to itself using aliases. Use it for hierarchies such as employee and manager, for comparing rows in the same table, or for finding pairs, for example two employees in the same department. Use a LEFT self join when the top of the hierarchy has no parent.

What is a cross join?

A cross join returns the Cartesian product: every row of the first table paired with every row of the second, with no ON condition. Two tables of 5 and 3 rows give 15 rows. It is useful for generating combinations, but forgetting a join condition produces one by accident and can return millions of rows.

Does MySQL support FULL OUTER JOIN?

MySQL does not have a FULL OUTER JOIN keyword. You combine a LEFT JOIN and a RIGHT JOIN with UNION to get the same result. PostgreSQL supports FULL OUTER JOIN directly, and SQLite added RIGHT and FULL OUTER JOIN in version 3.39.0, released on 25 June 2022.

Why does my join return more rows than the original table?

Because the other table has more than one row for the same key, so each left row repeats once per match. This is called join explosion and it inflates SUM and COUNT. Aggregate the many side to one row per key first, or use DISTINCT carefully, and compare row counts before and after the join.

What is faster, a join or a subquery?

There is no universal answer. Modern optimisers often turn equivalent subqueries into joins and produce the same plan. Choose the form that is clearer to read, then check the plan with EXPLAIN. Missing indexes on join keys matter far more than the syntax: see indexing in databases.

Continue learning

Interview prep

SQL interview questions

40 questions, one practice schema, every result run on SQLite

11 min read
Concept

SQL window functions

Ranking, LAG, running totals and gaps and islands, with real SQLite output

7 min read
Concept

Indexing in databases

Query plans and timings on 200,000 rows, composite, covering, clustered

8 min read