Joins and Subqueries Without Multiplying Rows
Load the full store schema, combine customers, orders and items with inner, outer and self joins, and answer questions with IN, EXISTS and correlated subqueries.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: inner join — matched pairs only
- Step 2: left and full joins — row-count arithmetic
- Step 3: join fan-out — when counting lies
- Step 4: self join and cross join
- Step 5: subqueries — scalar, IN, EXISTS and back
- Troubleshooting
- Check your understanding
- Apply it
- Review prompt
Lessons of SQL Fundamentals
- Tables, Rows and a First Session in psql Concept · 20 min
- Filtering, Sorting and the NULL Trap Worked example · 25 min
- Joins and Subqueries Without Multiplying Rows Lab · 30 min
- Turning Rows into Business Metrics Lab · 25 min
- Tables, Views and Changing Data Safely Lab · 25 min
- Check: Answer Questions About an Unseen Schema Knowledge check · 10 questions
What you will learn
- Combine tables with inner, left, full and self joins and explain row-count changes caused by join cardinality.
- Answer questions with scalar, IN, EXISTS and correlated subqueries, and rewrite a correlated subquery as a join or anti-join that returns the same rows.
01. Goal and setup
Orders so far lived alone; real questions need several tables at once. Which customers ordered a monitor? Who never ordered? How many rows will this join return? This lab gives you rules of thumb for all three. You will load the complete store schema, practise every join kind, watch joins multiply rows, and express the same question as a subquery and as a join — then prove they agree.
You need: the PostgreSQL container from the first lesson, with psql connected to the store database. Save the schema and the data below as store-seed.sql and load the file: it replaces the two tables you built so far (the customers table gains a referred_by column for the self join) and adds two new ones — orders (one row per purchase, with a nullable customer_id for guest checkouts) and order_items (one row per product in an order, the pattern that keeps one value per cell):
DROP TABLE IF EXISTS order_items, orders, products, customers CASCADE;
CREATE TABLE customers (
id integer PRIMARY KEY,
name text NOT NULL,
email text NOT NULL UNIQUE,
country text,
joined_at date NOT NULL,
referred_by integer
);
CREATE TABLE products (
id integer PRIMARY KEY,
name text NOT NULL,
category text NOT NULL,
price numeric(10,2) NOT NULL
);
CREATE TABLE orders (
id integer PRIMARY KEY,
customer_id integer REFERENCES customers(id),
status text NOT NULL,
created_at date NOT NULL,
shipped_at date
);
CREATE TABLE order_items (
order_id integer NOT NULL REFERENCES orders(id),
product_id integer NOT NULL REFERENCES products(id),
quantity integer NOT NULL,
unit_price numeric(10,2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);INSERT INTO customers (id, name, email, country, joined_at, referred_by) VALUES
(1, 'Amara Ndiaye', '[email protected]', 'SN', '2026-01-12', NULL),
(2, 'Ben Carter', '[email protected]', NULL, '2026-02-03', 1),
(3, 'Clara Ruiz', '[email protected]', 'ES', '2026-03-21', 1),
(4, 'Dmitri Volkov', '[email protected]', NULL, '2026-03-29', 2),
(5, 'Elin Johansson', '[email protected]', 'SE', '2026-04-15', 3),
(6, 'Farid Haddad', '[email protected]', 'ES', '2026-05-02', 5);
INSERT INTO products (id, name, category, price) VALUES
(1, 'USB-C cable', 'accessories', 9.90),
(2, 'Mechanical keyboard', 'peripherals', 89.00),
(3, 'Mouse pad', 'accessories', 12.50),
(4, '27-inch monitor', 'displays', 249.00),
(5, 'Webcam 1080p', 'peripherals', 45.00),
(6, 'Laptop stand', 'accessories', 29.00),
(7, 'HDMI cable 2m', 'accessories', 12.50),
(8, 'USB-C dock', 'peripherals', 129.00);
INSERT INTO orders (id, customer_id, status, created_at, shipped_at) VALUES
(1, 1, 'shipped', '2026-06-14', '2026-06-15'),
(2, 2, 'paid', '2026-07-02', NULL),
(3, 3, 'shipped', '2026-07-18', '2026-07-19'),
(4, 1, 'cancelled', '2026-08-01', NULL),
(5, 5, 'paid', '2026-08-30', NULL),
(6, 3, 'shipped', '2026-08-21', '2026-08-22'),
(7, 5, 'cancelled', '2026-09-22', NULL),
(8, NULL, 'paid', '2026-09-04', NULL),
(9, 6, 'shipped', '2026-09-10', '2026-09-11'),
(10, 2, 'shipped', '2026-09-16', '2026-09-17');
INSERT INTO order_items (order_id, product_id, quantity, unit_price) VALUES
(1, 1, 2, 9.90), (1, 6, 1, 29.00),
(2, 2, 1, 89.00), (2, 3, 2, 12.50),
(3, 4, 1, 249.00), (3, 7, 1, 12.50),
(4, 3, 1, 12.50),
(5, 5, 1, 45.00),
(6, 2, 1, 89.00),
(7, 4, 1, 249.00),
(8, 1, 1, 9.90),
(9, 4, 1, 249.00), (9, 5, 1, 45.00),
(10, 6, 1, 29.00), (10, 3, 3, 12.50);docker exec -i sql-lab psql -U postgres -d store < store-seed.sqlNOTICE: table "order_items" does not exist, skipping
NOTICE: table "orders" does not exist, skipping
DROP TABLE
CREATE TABLE
CREATE TABLE
CREATE TABLE
CREATE TABLE
INSERT 0 6
INSERT 0 8
INSERT 0 10
INSERT 0 1502. Step 1: inner join — matched pairs only
A join answers "rows from A, with matching rows from B attached". The ON clause defines what matching means, and each table gets a short alias (c, o) so columns are unambiguous. Start with the default JOIN, an inner join: every pair that matches, and nothing else:
SELECT o.id, c.name, o.status
FROM customers c
JOIN orders o ON o.customer_id = c.id
ORDER BY o.id; id | name | status
----+----------------+-----------
1 | Amara Ndiaye | shipped
2 | Ben Carter | paid
3 | Clara Ruiz | shipped
4 | Amara Ndiaye | cancelled
5 | Elin Johansson | paid
6 | Clara Ruiz | shipped
7 | Elin Johansson | cancelled
9 | Farid Haddad | shipped
10 | Ben Carter | shipped
(9 rows)Two rows are missing. Order 8 has customer_id NULL — a guest checkout that matches no customer — and Dmitri has no order. An inner join drops both, which is precisely what you want for "show me purchases with their buyer" and precisely wrong for "show me every customer".
03. Step 2: left and full joins — row-count arithmetic
A left join keeps every row of the left table, padding missing matches with NULLs; a full join keeps every row of both sides. Instead of eyeballing long results, count. The query below uses three scalar subqueries — one-value SELECTs inside the SELECT list, each wrapped in its own parentheses:
SELECT
(SELECT count(*) FROM customers c
JOIN orders o ON o.customer_id = c.id) AS inner_pairs,
(SELECT count(*) FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id) AS left_rows,
(SELECT count(*) FROM customers c
FULL JOIN orders o ON o.customer_id = c.id) AS full_rows; inner_pairs | left_rows | full_rows
-------------+-----------+-----------
9 | 10 | 11
(1 row)Read the arithmetic: 9 matched pairs; the left join adds Dmitri (10); the full join adds the guest order too (11). When IDs are unique within each table, an inner join returns one row per pair, and each outer side adds its unmatched rows, NULL-padded. Look at the two orphans directly — a full join with a filter for unmatched rows on either side is the standard "what is missing here?" query:
SELECT c.name, o.id AS order_id, o.status
FROM customers c
FULL JOIN orders o ON o.customer_id = c.id
WHERE c.id IS NULL OR o.id IS NULL
ORDER BY o.id; name | order_id | status
---------------+----------+--------
| 8 | paid
Dmitri Volkov | |
(2 rows)04. Step 3: join fan-out — when counting lies
Joins across a one-to-many relationship multiply: an order joins to each of its items, so an order with three items appears three times. That is correct and useful — until you aggregate. Count "orders per customer" naively and you count items, not orders:
SELECT c.name,
count(*) AS joined_rows,
count(DISTINCT o.id) AS orders
FROM customers c
JOIN orders o ON o.customer_id = c.id
JOIN order_items i ON i.order_id = o.id
GROUP BY c.name
ORDER BY c.name; name | joined_rows | orders
----------------+-------------+--------
Amara Ndiaye | 3 | 2
Ben Carter | 4 | 2
Clara Ruiz | 3 | 2
Elin Johansson | 2 | 2
Farid Haddad | 2 | 1
(5 rows)Ben has two orders, but count(*) says four, because each of his orders joins to two items. The same trap inflates sums: adding an order-total column after joining to items would add it once per item. Two reliable fixes:
- Count with
count(DISTINCT o.id)when you must keep the wide join. - Better, aggregate first, join after: build one row per order (or per customer) in a subquery in
FROM, then join that result. The metrics lesson practises exactly this pattern.
Always sanity-check a joined aggregate: does the row count match the grain you expected?
05. Step 4: self join and cross join
A self join uses one table in two roles. customers.referred_by points at another customer, so joining customers to customers — as c and as referrer r — lists everyone with their referrer, and a left join keeps Amara, who was referred by nobody:
SELECT c.name AS customer, r.name AS referred_by
FROM customers c
LEFT JOIN customers r ON r.id = c.referred_by
ORDER BY c.id; customer | referred_by
----------------+----------------
Amara Ndiaye |
Ben Carter | Amara Ndiaye
Clara Ruiz | Amara Ndiaye
Dmitri Volkov | Ben Carter
Elin Johansson | Clara Ruiz
Farid Haddad | Elin Johansson
(6 rows)A cross join is the Cartesian product — every row of one side paired with every row of the other. It is rarely what you want by accident (a fan-out of the whole tables) and occasionally exactly right, for instance to enumerate combinations like countries and categories:
SELECT c.country, p.category
FROM (SELECT DISTINCT country FROM customers
WHERE country IS NOT NULL) c
CROSS JOIN (SELECT DISTINCT category FROM products) p
ORDER BY 1, 2; country | category
---------+-------------
ES | accessories
ES | displays
ES | peripherals
SE | accessories
SE | displays
SE | peripherals
SN | accessories
SN | displays
SN | peripherals
(9 rows)Three known countries times three categories is nine rows — the whole grid, ready to be left-joined against real sales to spot empty combinations. If a cross join surprises you in a query you did not write, look for a missing join condition.
06. Step 5: subqueries — scalar, IN, EXISTS and back
A subquery is a query inside another query, and it comes in three shapes: scalar (one row, one column — you already used three as counters), table (a result used where a table fits, like the FROM (...) blocks above), and row (one row with several columns, compared as a tuple). The classic use of a scalar subquery is a threshold computed from the data itself:
SELECT name, price FROM products WHERE price = (SELECT max(price) FROM products); name | price
-----------------+--------
27-inch monitor | 249.00
(1 row)IN compares against a list subquery: which customers bought a monitor? Write it as prose first — customers whose id appears among the customer ids of non-cancelled orders containing a monitor:
SELECT name FROM customers
WHERE id IN (
SELECT o.customer_id
FROM orders o
JOIN order_items i ON i.order_id = o.id
JOIN products p ON p.id = i.product_id
WHERE p.name = '27-inch monitor'
AND o.status <> 'cancelled')
ORDER BY name; name
--------------
Clara Ruiz
Farid Haddad
(2 rows)Elin is absent because her monitor order was cancelled — subqueries compose, so business rules like "not cancelled" live in one place. Now the negative question, and the most reliable trap in this whole skill. Which customers have never ordered? The obvious NOT IN returns nothing:
SELECT name FROM customers
WHERE id NOT IN (SELECT customer_id FROM orders); name
------
(0 rows)The subquery returns the customer ids of every order — 1, 2, 3, 5, 6 — plus the guest order's NULL — and you know from the NULL lesson that x <> NULL is UNKNOWN. NOT IN demands every comparison be true, one NULL makes that impossible, so no row survives. NOT EXISTS asks the question directly — "is there no order for this customer?" — and NULLs cannot break it: inside the subquery, o.customer_id = c.id with a NULL is UNKNOWN, so that order row simply does not match, and NOT EXISTS only asks whether any matching row exists:
SELECT name FROM customers c
WHERE NOT EXISTS (
SELECT 1 FROM orders o
WHERE o.customer_id = c.id); name
---------------
Dmitri Volkov
(1 row)This is a correlated subquery: the inner SELECT mentions c.id from the outer row, so it is evaluated per customer. The same idea works in the positive direction and in the other table — products nobody has bought yet:
SELECT name FROM products p
WHERE NOT EXISTS (
SELECT 1 FROM order_items i
WHERE i.product_id = p.id); name
------------
USB-C dock
(1 row)Every NOT EXISTS has an equivalent anti-join: left-join to the other table, keep the rows where the join found nothing, detected as NULL in a column that is never NULL on real matches — the primary key works well:
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL; name
---------------
Dmitri Volkov
(1 row)One row, same as NOT EXISTS — the two forms agree by definition, and you can rewrite either into the other. Correlated subqueries also answer existence flags: orders containing a bulk line (quantity two or more), one row per order:
SELECT o.id, o.status
FROM orders o
WHERE EXISTS (
SELECT 1 FROM order_items i
WHERE i.order_id = o.id AND i.quantity >= 2)
ORDER BY o.id; id | status
----+---------
1 | shipped
2 | paid
10 | shipped
(3 rows)Rewritten as a plain join, the same question needs DISTINCT, because an order with two bulk lines would come back twice — watch for that whenever you turn EXISTS into a join:
SELECT DISTINCT o.id, o.status
FROM orders o
JOIN order_items i ON i.order_id = o.id
WHERE i.quantity >= 2
ORDER BY o.id; id | status
----+---------
1 | shipped
2 | paid
10 | shipped
(3 rows)07. Troubleshooting
08. Check your understanding
09. Apply it
Push the practice project forward on the store schema:
- List every customer with their number of orders, showing 0 for Dmitri (LEFT JOIN, then
count(o.id)). - Rewrite the never-sold-products query from
NOT EXISTSas a LEFT JOIN anti-join, and check both returnUSB-C dock. - Find orders in which no item has a quantity above 1 using
NOT EXISTS, then rewrite it as a join and explain why the join version needs care.
Schema design questions — which tables, which keys — belong to the relational data modelling skill; making these queries fast on large tables belongs to query optimization.
10. Review prompt
Without looking back:
- With unique IDs on both sides, how do you predict the row count of an inner, left or full join?
- Why did
count(*)after joining customers-orders-order_items overstate the number of orders, and what are the two fixes? - Why does
NOT IN (SELECT customer_id FROM orders)return no rows on this data, and which two forms answer the question correctly? - When does rewriting
EXISTSas a join needDISTINCT, and why?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.