Thuta Learning
SQL
AdvancedData & DatabasesBeginner

INNER JOIN

SQLLesson 1825 min

What you'll walk away with

  • Write a clear INNER JOIN between a foreign key and a primary key using aliases
  • Predict that INNER JOIN drops unmatched rows, including rows with a NULL foreign key
  • Chain three tables with INNER JOIN and filter the result with WHERE
  • Spot and fix the row multiplication that inflates aggregates when two child tables are joined at once

Explain it simply

Explain it simply

INNER JOIN works like the person checking names at a party's door. Someone arrives holding an invitation (an order), and gets in only if their name is found on the guest list (customers). An invitation whose name is not on the list, and a guest who brought no invitation, both stay outside.

That makes INNER JOIN the natural choice for questions that only make sense when both sides exist, like "each order with its customer's name". It is the most common join, and writing a bare JOIN gives you an INNER JOIN.

Problem → Why → Solution

The problem: a confused column and a vanished order

You write a query to show customer 3's orders and PostgreSQL refuses with "column reference \"customer_id\" is ambiguous": both tables have customer_id, so it cannot tell which one WHERE customer_id = 3 means. After fixing that, you list all orders with names, and although the orders table holds four orders, the result shows only three.

orders_with_names.sql
SELECT order_id, customer_name
FROM orders
JOIN customers ON customers.customer_id = orders.customer_id
WHERE customer_id = 3;
-- ERROR: column reference "customer_id" is ambiguous

SELECT COUNT(*) FROM orders;                       -- 4
SELECT COUNT(*) FROM orders
JOIN customers ON customers.customer_id = orders.customer_id;  -- 3 ?!

What is going on?

The first error comes from writing a column without its table name or alias; o.customer_id fixes it. The second is not a bug but the meaning of INNER JOIN: order 10311 was a guest checkout with a NULL customer_id. Comparing NULL with anything is never true, so the order has no matching customer and is dropped. If you need that order in the result, INNER JOIN is the wrong tool.

Core concept: the ON condition defines a match

In an INNER JOIN, one output row is one left row paired with one right row for which the ON condition is true. Every pair that makes the condition false or NULL (unknown) disappears. That is why rows with a NULL foreign key never appear in an INNER JOIN. INNER JOIN is also symmetric: orders JOIN customers and customers JOIN orders return the same set of rows, only the column order differs.

Once several tables are involved, writing every column as alias.column is a good habit. In FROM orders AS o the AS is optional, and short aliases such as o, c and s keep the query readable. After you give a table an alias, its original name can no longer be used in that query, so orders.order_id becomes an error. A column that exists in only one table runs fine without an alias, but the query breaks on the day someone adds a column with the same name to another table.

Joins can be chained: FROM orders JOIN customers ON ... JOIN shippers ON .... Each JOIN connects the result so far to one more table. With only INNER JOINs, a row that fails to match at any step never reaches the final result.

For an INNER JOIN, a filter placed in ON and the same filter placed in WHERE give identical results, but keeping the linking condition (key = key) in ON and the "which rows do I want" filter in WHERE makes the query easier to read. With LEFT JOIN the two placements stop being equivalent, as the next lesson shows.

Mental model: both sides must answer
  1. Take one order row
  2. Look for customers matching ON
  3. Emit one row per match found
  4. No match (or NULL key): drop it

Every row an INNER JOIN returns has real data from both sides; the join itself never invents NULLs.

General pattern

sql
SELECT c.column_name, p.column_name, x.column_name
FROM child_table AS c
INNER JOIN parent_table AS p
  ON p.primary_key = c.foreign_key
INNER JOIN other_table AS x
  ON x.primary_key = c.other_key
WHERE filter_condition
ORDER BY sort_column;

Start from the child table that holds the foreign keys and attach each parent table in turn. ON links the keys, WHERE filters the rows you want, and the INNER keyword is optional.

Example: every order with its customer's name

The orders table holds four orders, and order 10311 has a NULL customer_id because it was a guest checkout. The INNER JOIN below pairs each order with its customer's name; watch how many rows come back.

inner_join.sql
SELECT o.order_id,
       c.customer_name,
       o.order_date
FROM orders AS o
INNER JOIN customers AS c
  ON c.customer_id = o.customer_id
ORDER BY o.order_id;

Code breakdown

  1. Lines 1-3SELECT o.order_id,

    Every column carries its alias: order_id and order_date come from orders (o), customer_name from customers (c).

  2. Line 4FROM orders AS o

    Starting from the child table that owns the foreign key makes one output row mean "one order".

  3. Lines 5-6ON c.customer_id = o.customer_id

    Links the foreign key o.customer_id to the primary key c.customer_id. Order 10311's NULL equals no customer_id, so that order is dropped.

  4. Line 7ORDER BY o.order_id;

    Join output has no guaranteed order, so always add ORDER BY. The result has 3 rows, with Antonio Moreno appearing once per order.

You should see
 order_id | customer_name  | order_date
----------+----------------+------------
    10308 | Ana Trujillo   | 1996-09-18
    10309 | Antonio Moreno | 1996-09-19
    10310 | Antonio Moreno | 1996-09-20
(3 rows)

Chaining a third table

Each order also stores a shipper_id. One more JOIN brings in the shipper's name, and WHERE keeps only orders from customers in Mexico. The result is three rows: 10308 (Speedy Express), 10309 (United Package) and 10310 (Speedy Express).

three_tables.sql
SELECT o.order_id, c.customer_name, s.shipper_name
FROM orders AS o
JOIN customers AS c ON c.customer_id = o.customer_id
JOIN shippers  AS s ON s.shipper_id  = o.shipper_id
WHERE c.country = 'Mexico'
ORDER BY o.order_id;

When a join multiplies rows

Order 1 has two items (Coffee and Tea) and two payments (25.00 and 15.00), so the total paid should be 40.00. Join order_items and payments at the same time, though, and every item pairs with every payment: 2 x 2 = 4 rows, and SUM(p.paid) reports 80.00, double the truth. No error is raised, which is what makes this bug so dangerous.

fan_out.sql
-- wrong: 80.00, each payment is repeated once per item
SELECT SUM(p.paid) AS total_paid
FROM orders AS o
JOIN order_items AS i ON i.order_id = o.order_id
JOIN payments    AS p ON p.order_id = o.order_id;

-- right: 40.00, aggregate payments without the item join
SELECT SUM(p.paid) AS total_paid
FROM payments AS p
WHERE p.order_id = 1;

Rule of thumb

Never join two one-to-many child tables of the same parent in one step. Aggregate each child table separately first, with a subquery or CTE, and then join the totals. You will meet that technique again in the subqueries and CTEs lesson.

In real projects

Where this shows up in real projects

Every invoice, receipt and order-confirmation email is an INNER JOIN: each order line is linked to a product name and price, and to the customer's address. In such documents a row missing its partner is really broken data, so dropping it is correct. Permission checks also use join chains such as users JOIN memberships JOIN projects to answer "may this user open this project?"

In production, join speed depends heavily on indexes over foreign-key columns. PostgreSQL creates an index for every primary key automatically but not for foreign keys, so columns like orders.customer_id need their own CREATE INDEX. The fan-out bug also turns up in reports regularly, so it pays to have a test that checks a joined total against the same total computed from the source table alone.

Common mistakes

Common mistakes

1. Unqualified column names

Writing WHERE customer_id = 3 when both tables have customer_id gives an "ambiguous" error. Using the original name orders.customer_id after aliasing the table fails too, with "invalid reference to FROM-clause entry". Once a table has an alias, always use the alias.

2. Summing after joining two child tables

Joining orders to items and orders to payments in one query multiplies rows, doubling or tripling the sums. After a join, compare COUNT(*) with the source table's row count; if it is larger, something is multiplying.

3. Not noticing dropped rows

Computing order revenue from orders JOIN customers silently loses the money from guest checkouts with a NULL customer_id. When a report must include every row of the source table, use LEFT JOIN rather than INNER JOIN.

Mini challenge

Mini challenge: database course enrollments

There are three tables: students, courses and enrollments. List the student name, course title and enrollment date for every enrollment in a course from the 'Databases' category.

  • Start from enrollments and attach students and courses with INNER JOIN
  • Qualify every column with an alias
  • Keep only courses whose category is 'Databases'
  • Sort by enrolled_on
db_enrollments.sql
SELECT -- TODO: student name, course title, enrollment date
FROM enrollments AS e
-- TODO: join students on student_id
-- TODO: join courses on course_id
-- TODO: keep only the 'Databases' category
-- TODO: sort by enrollment date
;

Expected: Three rows, without the Intro to Python enrollment: full_name | title | enrolled_on -----------+-------------------+------------- Aung Aung | SQL Basics | 2024-01-05 Moe Moe | SQL Basics | 2024-01-20 Moe Moe | PostgreSQL Tuning | 2024-02-01 (3 rows)

Show hint

enrollments is the child table and owns two foreign keys, student_id and course_id. Each JOIN links one foreign key to its parent's primary key. Nilar is not enrolled anywhere, so she must not appear.

Show solution
db_enrollments.sql
SELECT s.full_name, c.title, e.enrolled_on
FROM enrollments AS e
JOIN students AS s ON s.student_id = e.student_id
JOIN courses  AS c ON c.course_id  = e.course_id
WHERE c.category = 'Databases'
ORDER BY e.enrolled_on;

Quick quiz 1 / 3

orders has 10 rows; 2 have a NULL customer_id and the rest point at existing customers. How many rows does orders INNER JOIN customers return?

Quick quiz 2 / 3

After FROM orders AS o JOIN customers AS c ON c.customer_id = o.customer_id, which WHERE clause causes an error?

Quick quiz 3 / 3

An order has 3 items and 2 payments. Joining orders, items and payments and then computing SUM(p.paid) adds each payment how many times?

What to remember

  • INNER JOIN returns only pairs where ON is true, so rows with a NULL foreign key disappear.
  • With several tables, write every column as alias.column; once aliased, the original table name is off limits.
  • Joins chain naturally, and for INNER JOIN a filter in ON behaves the same as one in WHERE.
  • Joining two child tables at once multiplies rows, so aggregate each one separately first.

PostgreSQL SQL Tutorial — PostgreSQL Global Development Group

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

INNER JOIN | Thuta Learning