BeginnerSQL · 19 min · 9 challenges

Joins: Beginner

Prime Day at Amazon: an analyst ranks shoppers by what they spent. Orders store only a customer number, so one query matches each order to its shopper. A draft that also matched every order against each promo code the shopper held reports one shopper spending double her real total. How rows get paired decides who tops the list.

The Row Pairing Model

Daily Life
Interviews

A store keeps its data in separate tables. customers holds one row per shopper, and orders holds one row per purchase. An order row stores the shopper's customer_id and leaves the name where it already lives, in customers.

Splitting data this way keeps each fact in one place. If Alice changes her name, one row in customers changes and every one of her orders stays correct. The price is that a question like 'which shopper spent the most?' needs columns from both tables in the same row. A join is how a query gets them there.

customers
customer_idname
1Alice
2Bob
orders
order_idcustomer_idtotal
101150
102130
103275

Ask who placed order 103 and you do a lookup by hand. You read customer_id 2 on the order row, scan customers for the row whose customer_id is also 2, and find Bob. A join is that same lookup, run for every row at once.

Every pair of rows gets one test

The database takes one row from the first table and one row from the second, and asks a true-or-false question about the pair. For these tables the question is: does the customer's customer_id equal the order's customer_id? A pair that answers true is kept. Every other pair is thrown away. Keep this model in mind for the rest of the lesson.

With 2 customers and 3 orders there are 6 possible pairs. This table lists all of them.
customers roworders rowtestresult
1, Alice101, customer 11 = 1true, kept
1, Alice102, customer 11 = 1true, kept
1, Alice103, customer 21 = 2false, dropped
2, Bob101, customer 12 = 1false, dropped
2, Bob102, customer 12 = 1false, dropped
2, Bob103, customer 22 = 2true, kept

3 pairs pass, so the result has 3 rows. Each result row is one customer row and one order row placed side by side, which is how a single row can show both name and total.

The query below asks for that pairing. The line that starts with ON holds the test, and the last section of this lesson takes the rest of the syntax apart. Play it and watch each comparison come out true or false.

SELECT
customers.customer_id,
customers.name,
orders.order_id,
orders.total
FROM customers
INNER JOIN orders
ON customers.customer_id = orders.customer_id
customers2 rows
customer_id
name
1
Alice
2
Bob
orders3 rows
order_id
customer_id
total
101
1
50
102
1
30
103
2
75
Preparing the animation
TIP
To practice, draw 2 tiny tables on paper, list every pair, and mark each test true or false before you run the query. 5 minutes of tracing by hand makes the row counts in later sections predictable.

What the model lets you predict

Alice appears twice in the result and Bob once. Her row passed the test with 2 different order rows, and each passing pair became its own result row.
3 predictions from the pairing model
  • ▸A result row is always a pair: one row from each table, side by side.
  • ▸A row shows up once for every partner it passes the test with, so one row can appear many times.
  • ▸A row that passes the test with no partner appears nowhere in the result.
These 3 statements answer most questions about a join before you run it. When a result has more rows than expected, some row found several partners. When a row you expected is missing, it found none.

On large tables a database skips the pair-by-pair work and uses faster matching methods. They return exactly the rows the every-pair model predicts, so the model stays a safe way to reason.

Multiple Choice

A new row arrives in orders: order 999 with customer_id 7 and total 40. The customers table still holds only Alice (1) and Bob (2). How many rows does the join return now?

Hold on to the picture of pairs and a test. The next 4 sections are all about that test: which columns it should compare, what those columns promise, how many pairs will pass, and how to write it.

Join keys and data types

Daily Life
Interviews
The columns compared in a join's test are called the join keys. The database will compare any 2 columns you name, as long as their types allow it. It has no idea whether the comparison means anything. Choosing keys that mean something is your job.

Same meaning comes first

A good pair of keys holds the same real-world identifier in both tables. Below, products lists what the store sells and order_items lists each line of each order. Both tables carry a product_id, and in both it means 'which product'.

products
product_idnameprice
1Kettle30
2Mug5
3Teapot25
order_items
item_idorder_idproduct_idquantity
110131
210125
310211
410333

order_items also has item_id, a second INTEGER column filled with small whole numbers. Nothing stops a query from comparing item_id to product_id. The 2 tabs below run the join both ways. Before you run them, predict which product name each tab gives item 1.

Compares product_id with product_id: the same identifier on both sides.
SELECT
order_items.item_id,
order_items.quantity,
products.name
FROM order_items
INNER JOIN products
ON order_items.product_id = products.product_id
Result
item_idquantityname
11Teapot
25Mug
31Kettle
43Teapot
4 rows
The right key returns 4 rows and says item 1 is a Teapot, which agrees with the data. The wrong key returns 3 rows and says item 1 is a Kettle. It raised no error, it gave item 2 the correct name by coincidence, and it silently lost item 4. A join on the wrong key produces rows that look reasonable and are false.
3 questions to ask about a pair of keys
  • ▸Meaning: do both columns identify the same kind of thing, such as a product or a customer?
  • ▸Type: are both columns stored as the same data type?
  • ▸Format: is one value written the same way in both tables, character for character?

A shared column name is a strong hint and nothing more. 2 tables can each have a column called id or name that means entirely different things. The same identifier can also be called product_id in one table and sku_id in another. Read a few rows of each column before trusting its name.

Types decide what equal means

Suppose a returns table was loaded from a spreadsheet export, and its product_code column arrived as VARCHAR. Its values are text that happens to contain digits: '3', '2', '3'. The query below compares that text with the INTEGER product_id.

SELECT
returns.return_id,
products.name
FROM returns
INNER JOIN products
ON returns.product_code = products.product_id
The fix is one you already know: convert one side with CAST so both sides have the same type. Here the text column is cast to INTEGER before the comparison.
SELECT
returns.return_id,
products.name
FROM returns
INNER JOIN products
ON CAST(returns.product_code AS INTEGER) = products.product_id
Result
return_idname
901Teapot
902Mug
903Teapot
3 rows

3 returns come back with product names. CAST only works when every value can be read as a number. One 'N/A' in product_code stops the whole query, so read through a text key's values before you cast it.

Type also changes which values count as equal. Text is equal only when every character is the same, including capital letters, spaces and leading zeros. Numbers are equal when their values are the same.
Left valueRight valueCompared asEqual?
'TEA-3''TEA-3'VARCHARtrue
'TEA-3''tea-3'VARCHARfalse
'TEA-3''TEA-3 'VARCHARfalse
'0042''42'VARCHARfalse
CAST('0042' AS INTEGER)CAST('42' AS INTEGER)INTEGERtrue

Row 3 fails because the right value ends in a space you can barely see. Rows 4 and 5 start from the same 2 values and give opposite answers. As text, '0042' and '42' differ by 2 characters. As numbers, both are 42. When a join returns fewer rows than you expected, mismatched formatting in a text key is a common cause.

Multiple Choice

An employees table has employee_id (INTEGER), name (VARCHAR) and department_id (INTEGER). A departments table has department_id (INTEGER), name (VARCHAR) and floor (INTEGER). Which test pairs each employee with their own department?

Meaning, type, format: check them in that order. Here a type mismatch failed loudly with an error, though a database that converts one side silently would hide it. A mismatch in meaning or format fails quietly with wrong or missing rows, which is why those 2 deserve the closer look.

Primary and foreign keys

Daily Life
Interviews
The previous section chose keys by reading rows and checking types. Most tables make the choice for you, because they are designed around 2 kinds of key column. Learn to spot them and a schema tells you how its tables join.

Primary key: one value, one row

A primary key is a column whose value identifies exactly one row of its table. That takes 2 promises: no value repeats, and no value is NULL. In customers, the primary key is customer_id. There is one row with customer_id 1, and it is Alice's. 2 shoppers can share the name Alice, which is why name could never do this job.

Foreign key: a pointer to another table

A foreign key is a column that stores primary key values from another table. orders.customer_id is a foreign key: each value in it points at one row of customers. A foreign key is free to repeat. Orders 101 and 102 both hold customer_id 1, because Alice ordered twice.

customers
customer_idPKINTEGER
nameVARCHAR
orders
order_idPKINTEGER
customer_idFKINTEGER
totalINTEGER

The line in the diagram runs from the foreign key to the primary key it points at, and that line is the join. The test compares the column at one end with the column at the other: orders.customer_id = customers.customer_id. A foreign key and its primary key already agree on meaning and type, so 2 of the 3 questions from the last section answer themselves. The N:1 label says many orders can point at one customer, which the next section turns into row counts.

✓Primary key
  • Identifies a row of its own table
  • Every value appears once
  • Never NULL
  • One per table
✗Foreign key
  • Points at a row of another table
  • Values may repeat
  • Each value should exist as a primary key value in the other table
  • A table can hold several

A foreign key value that exists nowhere in the other table's primary key is called an orphan. An order carrying customer_id 9 would be one, because no customer has that value. Orphans usually mean a row was deleted or loaded late, and the last section shows what a join does with them.

Finding keys when nobody drew the diagram

Many tables arrive with no diagram. Names help: a column called order_id in a table called orders is probably its primary key, and an _id column named after a different table is probably a foreign key. You can test the guess with 2 counts you already know. If COUNT(*) and COUNT(DISTINCT column) return the same number, no value repeats.

Tests whether order_id could be the primary key of orders.
SELECT
COUNT(*) AS row_count,
COUNT(DISTINCT order_id) AS distinct_values
FROM orders
Result
row_countdistinct_values
44
1 row

order_id gives 4 rows and 4 distinct values, so it can identify a row. customer_id gives 4 rows and 3 distinct values. A value repeats, so it cannot be the primary key of orders, and it behaves the way a foreign key does. To test the second promise, compare COUNT(*) with COUNT(column): equal numbers mean the column holds no NULL.

TIP
A count proves a column is unique in today's rows. A primary key is a promise about every future row too. Treat the count as evidence, then confirm with whoever owns the table.

One table, several relationships

A table has one primary key, and it can hold several foreign keys. order_items points at 2 tables at once: each line belongs to an order and names a product.

customers
customer_idPKINTEGER
nameVARCHAR
orders
order_idPKINTEGER
customer_idFKINTEGER
totalINTEGER
order_items
item_idPKINTEGER
order_idFKINTEGER
product_idFKINTEGER
quantityINTEGER
products
product_idPKINTEGER
nameVARCHAR
priceINTEGER

Each line is one relationship and one possible join. To put a product's price beside an order line, follow the line from order_items.product_id to products.product_id. No line connects customers to products, and they share no key, so no single test relates those 2 tables.

Multiple Choice

A payments table has 1,000 rows. COUNT(DISTINCT payment_id) returns 1,000. COUNT(order_id) returns 1,000 and COUNT(DISTINCT order_id) returns 940. What do these counts tell you?

Find each primary key and the foreign keys that point at it, and you have the list of sensible joins: one for each line in the diagram.

Cardinality

Daily Life
Interviews
Cardinality describes how many rows on one side of a relationship can match a single row on the other side. It is the difference between a join that returns the row count you planned for and one that returns 10x as many. You can work it out before running anything.

Count matches per key, multiply, then add

The pairing model gives the rule. Take one key value. If it appears on m rows of the left table and n rows of the right table, every one of those left rows passes the test with every one of those right rows. That value produces m times n result rows. Do this for each key value and add the products.

Try it on 3 customers and 4 orders. Alice has orders 101 and 102, Bob has 103 and Carol has 104.
customer_idRows in customersRows in ordersResult rows
1121 x 2 = 2
2111 x 1 = 1
3111 x 1 = 1
Total344
SELECT
customers.name,
orders.order_id
FROM customers
INNER JOIN orders
ON customers.customer_id = orders.customer_id
customers3 rows
customer_id
name
1
Alice
2
Bob
3
Carol
orders4 rows
order_id
customer_id
101
1
102
1
103
2
104
3
Preparing the animation

The result has 4 rows, the same count as orders. That is the signature of a one-to-many relationship joined on its keys. The primary key side contributes a 1 to every multiplication, so the result gets one row for each foreign key row that finds its partner.

The 3 shapes

ShapeEach key value appearsExampleResult rows per key value
One-to-oneonce on each sidea customer and their loyalty card1 x 1 = 1
One-to-manyonce on one side, many times on the othera customer and their orders1 x n = n
Many-to-manymany times on both sidesone customer's orders and couponsm x n
The first 2 shapes are safe: the result never has more rows than the larger table. Many-to-many is the shape that surprises people, because both numbers in the multiplication can be bigger than 1.

When both sides repeat

The store hands out coupons, and coupons has one row per coupon with its owner's customer_id. Alice holds 2 coupons, Bob holds one and Carol holds 2. Joining orders to coupons on customer_id compares one foreign key with another, so the value 1 repeats on both sides. Predict the row count before running it: Alice 2 x 2, Bob 1 x 1, Carol 1 x 2.

SELECT
orders.order_id,
orders.customer_id,
coupons.code
FROM orders
INNER JOIN coupons
ON orders.customer_id = coupons.customer_id
Result
order_idcustomer_idcode
1011SAVE5
1011SHIP0
1021SAVE5
1021SHIP0
1032SAVE5
1043SHIP0
1043TEA10
7 rows
7 rows come back from a table of 4 orders and a table of 5 coupons. Each of Alice's 2 orders sits beside each of her 2 coupons, which makes 4 rows about a shopper who ordered twice. No single row is false. The trouble starts when you add things up.
Adds total across the 4 rows of orders.
SELECT
SUM(total) AS revenue
FROM orders
Result
revenue
175
1 row
Revenue was 175 and the joined query reports 275. Orders 101, 102 and 104 each appear twice, so their totals are added twice. This is called fan-out. It is costly because the query runs cleanly and the inflated number looks plausible.

Check the keys before you join

You can see fan-out coming. Group each table by the join key and keep the keys that appear more than once. If neither table returns rows, the join is one-to-one. If only one does, it is one-to-many. If both do, it's many-to-many and the result will multiply.
SELECT
customer_id,
COUNT(*) AS coupon_count
FROM coupons
GROUP BY customer_id
HAVING COUNT(*) > 1
Result
customer_idcoupon_count
12
32
2 rows

coupons repeats customer_id 1 and 3. Run the same check on orders and it returns customer_id 1. Both tables repeat a key, so the multiplication was predictable from 2 short queries.

Multiple Choice

A teams table has 4 rows with city values A, A, B, C. A players table has 5 rows with city values A, B, B, B, D. How many rows does a join on city return?

Make the prediction a habit. Before running a join, write down the row count you expect. After running it, compare. A result larger than the foreign key side's table means some key repeated where you assumed it was unique.

INNER JOIN

Daily Life
Interviews
Every join in this lesson so far has been an INNER JOIN. It keeps a pair of rows when the test is true and keeps nothing else. This section reads the syntax piece by piece, then looks at what 'nothing else' costs you.

customers now has a new shopper, Dave, who has never ordered. Play the query and watch what happens to his row.

SELECT
customers.name,
orders.order_id,
orders.total
FROM customers
INNER JOIN orders
ON customers.customer_id = orders.customer_id
customers4 rows
customer_id
name
1
Alice
2
Bob
3
Carol
4
Dave
orders4 rows
order_id
customer_id
total
101
1
50
102
1
30
103
2
75
104
3
20
Preparing the animation
Reading the query
  • FROM customers names the first table, called the left table.
  • INNER JOIN orders names the second table, the right table, and says which kind of join to run.
  • ON customers.customer_id = orders.customer_id is the test applied to every pair of one left row and one right row.
  • SELECT picks columns from the kept pairs, and can take them from either table.

Each column is written as table.column. The prefix is required for customer_id, because both tables have a column with that name and the database refuses to guess which one you mean. name exists in only one table, so its prefix is optional. Writing it anyway tells the next reader where every column comes from.

The keyword JOIN on its own means INNER JOIN, and both spellings run the same query. This lesson writes the full form so the join type is always visible.

Unmatched rows vanish from both sides

Dave's row was tested against all 4 orders and every test was false, so he is missing from the result. The same thing happens on the other side. The tables below add order 105, which carries customer_id 9, and no customer has that value. This query also writes orders first, to show that swapping the 2 tables leaves the passing pairs unchanged.

SELECT
orders.order_id,
orders.total,
customers.name
FROM orders
INNER JOIN customers
ON orders.customer_id = customers.customer_id
Result
order_idtotalname
10150Alice
10230Alice
10375Bob
10420Carol
4 rows
4 rows again. Dave is absent because he has no order, and order 105 is absent because it has no customer. An INNER JOIN result contains only what exists in both tables. That makes it the right choice when a row is useless without its partner, and a risky one when every row must be accounted for.
✓Do
  • Compare the result's row count with each table's row count
  • Prefix every column with its table name
  • Join a foreign key to the primary key it points at
✗Don't
  • Assume every row of the first table appears in the result
  • Report a total without checking for unmatched rows
  • Pick keys by column name alone

The joined result is a table

Once the pairs are kept, the result behaves like any table. WHERE can filter its rows, and GROUP BY can fold them into one row per group. The query in the question below counts orders and adds up spending for each customer name. It runs on the original data: 4 customers, and orders 101 to 104.
Multiple Choice

customers holds Alice, Bob, Carol and Dave, and Dave has no orders. Alice's orders total 50 and 30. What does this query return?

SELECT
customers.name,
COUNT(*) AS order_count,
SUM(orders.total) AS total_spent
FROM customers
INNER JOIN orders
ON customers.customer_id = orders.customer_id
GROUP BY customers.name
Run it and compare the result with your prediction.
SELECT
customers.name,
COUNT(*) AS order_count,
SUM(orders.total) AS total_spent
FROM customers
INNER JOIN orders
ON customers.customer_id = orders.customer_id
GROUP BY customers.name
Result
nameorder_counttotal_spent
Alice280
Bob175
Carol120
3 rows
A report built on this query shows 3 customers and never mentions Dave. Listing customers with 0 orders takes a different kind of join, which a later lesson covers.

Build one yourself

2 short exercises put the syntax in your hands. The first gives you the lines of a query out of order. The second leaves blanks in a join for you to fill.
Complete the SQL

> Show each order's order_id beside the name of the customer who placed it. Drag the tiles into the slots to build the query. 2 tiles do not belong.

1
2
3
4

The wrong ON tile compared order_id with customer_id: both INTEGER, different meanings, the same trap as the item_id join in section 1. A join always has 3 parts in a fixed order: the join keywords with the second table, then ON, then a test with one column from each table that holds the same identifier.

Loading the challenge
Every INNER JOIN you write comes down to 4 decisions, made in this order: which 2 tables, which keys, how many rows to expect, and which rows you are willing to lose.
PUTTING IT ALL TOGETHER

> Picture the Prime Day dashboard at Amazon from the opening. An analyst wants revenue per shopper, so the query joins orders to customers and groups by name. A first draft also joins to coupons on the shopper's ID, and the revenue figure comes out well above the sum of the orders table.

Row pairing: each order row is tested against each customer row, and a pair is kept when the 2 customer_id values are equal.
Keys and types: the test compares identifiers with the same meaning and type, so orders.customer_id meets customers.customer_id and a shopper's name stays out of the test.
Primary and foreign keys: customers.customer_id is unique, so each order finds at most one shopper and no order is duplicated by that join.
Cardinality: orders and coupons both repeat customer_id, so that join multiplies rows and inflates SUM. Counting rows per key in each table exposes it before the dashboard ships.
INNER JOIN: shoppers with no orders vanish from the result, which suits a top-spenders list and would be wrong for a list of every customer.
KEY TAKEAWAYS
A join tests pairs of rows, one from each table, and keeps the pairs where the test is true.
Good join keys share meaning, type and format. A wrong key runs without error and returns false rows.
A primary key identifies one row of its table. A foreign key points at it, and that pointer is the join.
For each key value, result rows equal left matches times right matches. When both sides repeat a key, sums inflate.
INNER JOIN drops unmatched rows from both tables, so compare row counts before trusting a total.

Pair rows from 2 tables on a shared key, and know how many rows come back before you run the query.

Getting tables to talk to each other

Category
SQL
Difficulty
beginner
Duration
19 minutes
Challenges
9 hands-on challenges

Topics covered: The Row Pairing Model, Join keys and data types, Primary and foreign keys, Cardinality, INNER JOIN

Lesson Sections

  1. The Row Pairing Model (concepts: Inner Joins)

    Every pair of rows gets one test With 2 customers and 3 orders there are 6 possible pairs. This table lists all of them. What the model lets you predict Alice appears twice in the result and Bob once. Her row passed the test with 2 different order rows, and each passing pair became its own result row. These 3 statements answer most questions about a join before you run it. When a result has more rows than expected, some row found several partners. When a row you expected is missing, it found non

  2. Join keys and data types (concepts: Inner Joins, Type Casting)

    The columns compared in a join's test are called the join keys. The database will compare any 2 columns you name, as long as their types allow it. It has no idea whether the comparison means anything. Choosing keys that mean something is your job. Same meaning comes first The right key returns 4 rows and says item 1 is a Teapot, which agrees with the data. The wrong key returns 3 rows and says item 1 is a Kettle. It raised no error, it gave item 2 the correct name by coincidence, and it silently

  3. Primary and foreign keys

    The previous section chose keys by reading rows and checking types. Most tables make the choice for you, because they are designed around 2 kinds of key column. Learn to spot them and a schema tells you how its tables join. Primary key: one value, one row Foreign key: a pointer to another table Finding keys when nobody drew the diagram One table, several relationships Find each primary key and the foreign keys that point at it, and you have the list of sensible joins: one for each line in the di

  4. Cardinality (concepts: Join Cardinality)

    Cardinality describes how many rows on one side of a relationship can match a single row on the other side. It is the difference between a join that returns the row count you planned for and one that returns 10x as many. You can work it out before running anything. Count matches per key, multiply, then add Try it on 3 customers and 4 orders. Alice has orders 101 and 102, Bob has 103 and Carol has 104. The 3 shapes The first 2 shapes are safe: the result never has more rows than the larger table.

  5. INNER JOIN (concepts: Inner Joins)

    Every join in this lesson so far has been an INNER JOIN. It keeps a pair of rows when the test is true and keeps nothing else. This section reads the syntax piece by piece, then looks at what 'nothing else' costs you. The keyword JOIN on its own means INNER JOIN, and both spellings run the same query. This lesson writes the full form so the join type is always visible. Unmatched rows vanish from both sides 4 rows again. Dave is absent because he has no order, and order 105 is absent because it h