Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 30 min · revision 2

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

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):

SQL · store-seed.sql (schema)
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)
);
SQL · store-seed.sql (data, append to the file)
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);
Terminal
docker exec -i sql-lab psql -U postgres -d store < store-seed.sql
Expected output (first run; a re-run prints no NOTICE lines)
NOTICE:  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 15

02. 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:

SQL · store=#
SELECT o.id, c.name, o.status
FROM customers c
JOIN orders o ON o.customer_id = c.id
ORDER BY o.id;
Expected output
 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:

SQL · store=#
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;
Expected output
 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:

SQL · store=#
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;
Expected output
     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:

SQL · store=#
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;
Expected output
      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:

SQL · store=#
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;
Expected output
    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:

SQL · store=#
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;
Expected output
 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:

SQL · store=#
SELECT name, price FROM products WHERE price = (SELECT max(price) FROM products);
Expected output
      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:

SQL · store=#
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;
Expected output
     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:

SQL · store=# — returns no rows
SELECT name FROM customers
WHERE id NOT IN (SELECT customer_id FROM orders);
Expected output
 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:

SQL · store=#
SELECT name FROM customers c
WHERE NOT EXISTS (
  SELECT 1 FROM orders o
  WHERE o.customer_id = c.id);
Expected output
     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:

SQL · store=#
SELECT name FROM products p
WHERE NOT EXISTS (
  SELECT 1 FROM order_items i
  WHERE i.product_id = p.id);
Expected output
    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:

SQL · store=#
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;
Expected output
     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:

SQL · store=#
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;
Expected output
 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:

SQL · store=#
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;
Expected output
 id | status  
----+---------
  1 | shipped
  2 | paid
 10 | shipped
(3 rows)

07. Troubleshooting

08. Check your understanding

Practice check · 3 questions

Joins and subqueries

Reason about row counts and pick the right shape.

Q1. With this dataset (6 customers, 10 orders, one order from a guest with NULL customer_id, one customer with no orders), how many rows does SELECT count(*) FROM customers JOIN orders ON orders.customer_id = customers.id return?
Q2. You need every product with the number of times it has been sold, showing 0 for products never ordered. Which query shape is right?
Q3. A report lists one row per order, plus a yes/no column: does this order contain a monitor? Which pattern keeps exactly one row per order?
Practice only: not graded, not saved, not evidence.

09. Apply it

Push the practice project forward on the store schema:

  1. List every customer with their number of orders, showing 0 for Dmitri (LEFT JOIN, then count(o.id)).
  2. Rewrite the never-sold-products query from NOT EXISTS as a LEFT JOIN anti-join, and check both return USB-C dock.
  3. 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:

  1. With unique IDs on both sides, how do you predict the row count of an inner, left or full join?
  2. Why did count(*) after joining customers-orders-order_items overstate the number of orders, and what are the two fixes?
  3. Why does NOT IN (SELECT customer_id FROM orders) return no rows on this data, and which two forms answer the question correctly?
  4. When does rewriting EXISTS as a join need DISTINCT, and why?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check