Joins: Beginner
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.
| customer_id | name |
|---|---|
| 1 | Alice |
| 2 | Bob |
| order_id | customer_id | total |
|---|---|---|
| 101 | 1 | 50 |
| 102 | 1 | 30 |
| 103 | 2 | 75 |
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.
| customers row | orders row | test | result |
|---|---|---|---|
| 1, Alice | 101, customer 1 | 1 = 1 | true, kept |
| 1, Alice | 102, customer 1 | 1 = 1 | true, kept |
| 1, Alice | 103, customer 2 | 1 = 2 | false, dropped |
| 2, Bob | 101, customer 1 | 2 = 1 | false, dropped |
| 2, Bob | 102, customer 1 | 2 = 1 | false, dropped |
| 2, Bob | 103, customer 2 | 2 = 2 | true, 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.
SELECTcustomers.customer_id,customers.name,orders.order_id,orders.totalFROM customersINNER JOIN ordersON customers.customer_id = orders.customer_id
What the model lets you predict
- ▸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.
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.
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?
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'.
| product_id | name | price |
|---|---|---|
| 1 | Kettle | 30 |
| 2 | Mug | 5 |
| 3 | Teapot | 25 |
| item_id | order_id | product_id | quantity |
|---|---|---|---|
| 1 | 101 | 3 | 1 |
| 2 | 101 | 2 | 5 |
| 3 | 102 | 1 | 1 |
| 4 | 103 | 3 | 3 |
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.
- ▸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.
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.
| Left value | Right value | Compared as | Equal? |
|---|---|---|---|
| 'TEA-3' | 'TEA-3' | VARCHAR | true |
| 'TEA-3' | 'tea-3' | VARCHAR | false |
| 'TEA-3' | 'TEA-3 ' | VARCHAR | false |
| '0042' | '42' | VARCHAR | false |
| CAST('0042' AS INTEGER) | CAST('42' AS INTEGER) | INTEGER | true |
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.
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?
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.
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.
- Identifies a row of its own table
- Every value appears once
- Never NULL
- One per table
- 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.
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.
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.
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.
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?
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.
| customer_id | Rows in customers | Rows in orders | Result rows |
|---|---|---|---|
| 1 | 1 | 2 | 1 x 2 = 2 |
| 2 | 1 | 1 | 1 x 1 = 1 |
| 3 | 1 | 1 | 1 x 1 = 1 |
| Total | 3 | 4 | 4 |
SELECTcustomers.name,orders.order_idFROM customersINNER JOIN ordersON customers.customer_id = orders.customer_id
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
| Shape | Each key value appears | Example | Result rows per key value |
|---|---|---|---|
| One-to-one | once on each side | a customer and their loyalty card | 1 x 1 = 1 |
| One-to-many | once on one side, many times on the other | a customer and their orders | 1 x n = n |
| Many-to-many | many times on both sides | one customer's orders and coupons | m x n |
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.
Check the keys before you join
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.
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?
customers now has a new shopper, Dave, who has never ordered. Play the query and watch what happens to his row.
SELECTcustomers.name,orders.order_id,orders.totalFROM customersINNER JOIN ordersON customers.customer_id = orders.customer_id
- 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.
- 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
- 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
customers holds Alice, Bob, Carol and Dave, and Dave has no orders. Alice's orders total 50 and 30. What does this query return?
Build one yourself
> 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.
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.
> 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.
customer_id values are equal.orders.customer_id meets customers.customer_id and a shopper's name stays out of the test.customers.customer_id is unique, so each order finds at most one shopper and no order is duplicated by that join.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.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
- 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
- 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
- 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
- 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.
- 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