Joining Tables · Lesson 26 of 64

SQL INNER JOIN

What you will learn

  • How to write JOIN ... ON to match child rows with their parent
  • How table aliases keep the query short and clear
  • How to filter, sort and count a joined result
  • How to know how many rows a join should return

This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Edit any query and press Run. Reset data puts the original rows back.

1. The basic join

JOIN ... ON combines two tables. After FROM come the first table, the word JOIN, the second table and an ON condition that says which rows go together:

SELECT o.order_id, o.order_date, c.first_name, c.last_name
FROM orders AS o
JOIN customers AS c ON c.customer_id = o.customer_id
ORDER BY o.order_id LIMIT 5;
order_id  order_date  first_name  last_name
--------  ----------  ----------  ---------
       1  2025-04-23  Dana        Wang
       2  2024-01-21  Ugo         Das
       3  2025-05-03  Jin         Bianchi
       4  2026-08-18  Sara        Nair
       5  2024-05-26  Bruno       Zhang
(5 rows)
SELECT a.account_id, a.account_type, c.full_name, c.city
FROM accounts AS a
JOIN customers AS c ON c.customer_id = a.customer_id
ORDER BY a.account_id LIMIT 5;
account_id  account_type  full_name      city
----------  ------------  -------------  ------
         1  checking      Leo Kumar      Hanoi
         2  savings       Hana Kim       Manila
         3  savings       Vera Banerjee  Leeds
         4  checking      Olga Garcia    Lagos
         5  checking      Amir Singh     Pune
(5 rows)
SELECT s.section_id, s.term, c.code, c.title
FROM sections AS s
JOIN courses AS c ON c.course_id = s.course_id
ORDER BY s.section_id LIMIT 5;
section_id  term         code     title
----------  -----------  -------  ----------------------
         1  2025-Autumn  MATH101  Foundations of Algebra
         2  2025-Spring  MATH201  Geometry
         3  2025-Autumn  MATH201  Geometry
         4  2026-Spring  MATH201  Geometry
         5  2025-Spring  MATH301  Statistics
(5 rows)

Each row of the result is a child row together with the details of its own parent. The columns come from both tables, so each one is written with its table's alias (o.order_id, c.first_name).

JOIN on its own means INNER JOIN: only rows that have a match in both tables are kept. You may write INNER JOIN to be explicit; it means the same.

2. Table aliases

orders AS o gives the table a short name for this query (lesson 1.4). Once a table has an alias, use the alias everywhere in the query. Aliases make the query shorter and are required when the same table appears twice (lesson 4.6). Choose short names that hint at the table (o for orders, c for customers).

3. Which side is which

The order of the tables in JOIN does not change the result of an inner join; only the order of the columns you write does. This query gives the same rows as the first, with the other table first:

SELECT c.first_name, c.last_name, o.order_id, o.order_date
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id
ORDER BY o.order_id LIMIT 5;
first_name  last_name  order_id  order_date
----------  ---------  --------  ----------
Dana        Wang              1  2025-04-23
Ugo         Das               2  2024-01-21
Jin         Bianchi           3  2025-05-03
Sara        Nair              4  2026-08-18
Bruno       Zhang             5  2024-05-26
(5 rows)
SELECT c.full_name, c.city, a.account_id, a.account_type
FROM customers AS c
JOIN accounts AS a ON a.customer_id = c.customer_id
ORDER BY a.account_id LIMIT 5;
full_name      city    account_id  account_type
-------------  ------  ----------  ------------
Leo Kumar      Hanoi            1  checking
Hana Kim       Manila           2  savings
Vera Banerjee  Leeds            3  savings
Olga Garcia    Lagos            4  checking
Amir Singh     Pune             5  checking
(5 rows)
SELECT c.code, c.title, s.section_id, s.term
FROM courses AS c
JOIN sections AS s ON s.course_id = c.course_id
ORDER BY s.section_id LIMIT 5;
code     title                   section_id  term
-------  ----------------------  ----------  -----------
MATH101  Foundations of Algebra           1  2025-Autumn
MATH201  Geometry                         2  2025-Spring
MATH201  Geometry                         3  2025-Autumn
MATH201  Geometry                         4  2026-Spring
MATH301  Statistics                       5  2025-Spring
(5 rows)

4. Filter and sort a join

WHERE and ORDER BY work on the joined result, and can use columns of either table:

SELECT s.order_id, s.order_date, p.first_name, p.last_name
FROM orders AS s
JOIN customers AS p ON p.customer_id = s.customer_id
WHERE s.status = 'cancelled'
ORDER BY s.order_id LIMIT 5;
order_id  order_date  first_name  last_name
--------  ----------  ----------  ---------
      16  2025-08-11  Nico        Fischer
      40  2025-05-21  Hugo        Diaz
      43  2025-07-30  Vera        Mahmud
      70  2025-12-12  Arjun       Wang
      83  2026-02-21  Vik         Perez
(5 rows)
SELECT s.account_id, s.account_type, p.full_name, p.city
FROM accounts AS s
JOIN customers AS p ON p.customer_id = s.customer_id
WHERE s.account_type = 'savings'
ORDER BY s.account_id LIMIT 5;
account_id  account_type  full_name      city
----------  ------------  -------------  ------
         2  savings       Hana Kim       Manila
         3  savings       Vera Banerjee  Leeds
         7  savings       Ugo Ahmed      Accra
         8  savings       Ana Nguyen     Hanoi
         9  savings       Noah Tanaka    Manila
(5 rows)
SELECT s.section_id, s.term, p.code, p.title
FROM sections AS s
JOIN courses AS p ON p.course_id = s.course_id
WHERE s.term = '2025-Spring'
ORDER BY s.section_id LIMIT 5;
section_id  term         code     title
----------  -----------  -------  ---------------
         2  2025-Spring  MATH201  Geometry
         5  2025-Spring  MATH301  Statistics
         7  2025-Spring  SCI101   General Science
         8  2025-Spring  SCI201   Chemistry
        10  2025-Spring  SCI202   Physics
(5 rows)

(The alias of the child is s in this query, so the condition above uses the same alias.)

5. How many rows to expect

Count the rows of the join and compare with the child table. In an inner join every child row has exactly one parent (a foreign key points to one parent), so the join has as many rows as the child table, unless some child rows have no parent:

SELECT (SELECT COUNT(*) FROM orders) AS child_rows,
       (SELECT COUNT(*) FROM orders AS s JOIN customers AS p ON p.customer_id = s.customer_id) AS joined_rows;
child_rows  joined_rows
----------  -----------
      2600         2600
(1 row)
SELECT (SELECT COUNT(*) FROM accounts) AS child_rows,
       (SELECT COUNT(*) FROM accounts AS s JOIN customers AS p ON p.customer_id = s.customer_id) AS joined_rows;
child_rows  joined_rows
----------  -----------
       450          450
(1 row)
SELECT (SELECT COUNT(*) FROM sections) AS child_rows,
       (SELECT COUNT(*) FROM sections AS s JOIN courses AS p ON p.course_id = s.course_id) AS joined_rows;
child_rows  joined_rows
----------  -----------
        41           41
(1 row)

The two numbers are equal. If the join returned more rows than the child table, a join condition is probably wrong (for example it matched several parents). If it returned fewer, some child rows had no parent. Checking the counts is the quickest way to catch a bad join.

6. Joining and aggregating

A join followed by GROUP BY answers "per parent" questions, such as how many children each parent has:

SELECT c.customer_id, c.first_name, c.last_name, COUNT(*) AS orders
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.first_name, c.last_name
ORDER BY orders DESC, c.customer_id LIMIT 5;
customer_id  first_name  last_name  orders
-----------  ----------  ---------  ------
         72  Hugo        Silva          17
        292  Tara        Ahmed          17
        134  Quinn       Kamau          15
         42  Isla        Diaz           14
        199  Arjun       Wang           14
(5 rows)
SELECT c.customer_id, c.full_name, COUNT(*) AS accounts, SUM(a.balance_cents) AS total_cents
FROM customers AS c
JOIN accounts AS a ON a.customer_id = c.customer_id
GROUP BY c.customer_id, c.full_name
ORDER BY total_cents DESC, c.customer_id LIMIT 5;
customer_id  full_name    accounts  total_cents
-----------  -----------  --------  -----------
         96  Rosa Kumar          7      1189699
        260  Arjun Sato          4      1066703
        133  Leo Alvarez         4       862817
        234  Uma Reyes           5       862000
        119  Chen Varga          4       833895
(5 rows)
SELECT c.course_id, c.code, c.title, COUNT(*) AS sections
FROM courses AS c
JOIN sections AS s ON s.course_id = c.course_id
GROUP BY c.course_id, c.code, c.title
ORDER BY sections DESC, c.course_id LIMIT 5;
course_id  code     title            sections
---------  -------  ---------------  --------
        2  MATH201  Geometry                3
        7  SCI301   Biology                 3
        9  LANG102  Reading Circle          3
       10  LANG201  Second Language         3
       11  HUM101   World History           3
(5 rows)

Notice that GROUP BY lists every plain column of the SELECT (lesson 3.2). Only parents with at least one child appear; parents with none are dropped by the inner join. Lesson 4.3 shows how to keep them.

Worked example: write a join in four steps

"List each account with the name of its owner."

Step Question Answer
1 Which table has the rows I list? accounts, alias a
2 Which table has the extra detail? customers, alias c
3 Which columns match? a.customer_id = c.customer_id
4 Which columns do I show? a.account_id, c.full_name

Result: SELECT a.account_id, c.full_name FROM accounts AS a JOIN customers AS c ON c.customer_id = a.customer_id. The tables are from the Bank sample.

Common mistakes

  • Forgetting the ON condition, or putting the wrong columns in it.
  • Not using the alias after defining one.
  • Selecting a column name that exists in both tables without the alias (lesson 4.8).
  • Expecting parents without children to appear in an inner join.
  • Not checking the row count against the child table.

Key takeaways

  • FROM child JOIN parent ON child.key = parent.key pairs each child row with its parent.
  • JOIN means INNER JOIN: only rows with a match on both sides.
  • Aliases shorten the query and are needed when a table is used twice.
  • A join on a foreign key returns as many rows as the child table.
  • GROUP BY after a join answers "per parent" questions.

Practice

1. Write the join that shows each order with its customer's last name.

Show answer

SELECT o.order_id, c.last_name FROM orders AS o JOIN customers AS c ON c.customer_id = o.customer_id;

2. What does INNER JOIN keep?

Show answer

Only the rows that have a match in both tables.

3. A child table has 2,600 rows. How many rows should its inner join with the parent have?

Show answer

2,600, if every child row has exactly one parent.

4. Why use table aliases?

Show answer

They make the query shorter and clearer, and they are required when the same table is used twice.

5. Does the order of the tables in an inner join change its rows?

Show answer

No. The same rows are returned; only the order of the columns you write may differ.

6. What happens to a parent that has no children in an inner join?

Show answer

It does not appear in the result.