Primary Keys, Foreign Keys, and the Joins That Confuse Everyone
A practical guide to understanding how SQL tables connect through primary and foreign keys, and how INNER, LEFT, RIGHT, and FULL OUTER joins actually work.
Joins are one of those SQL topics that feel obvious right up until you get a result set with the wrong number of rows. Most of the confusion comes from skipping the step before it: understanding how two tables are connected in the first place. So that's where we'll start, with keys, and then move on to the four joins you'll use in practice.
I'm using one small example database for the whole post. That way you can compare the join results directly instead of mentally switching datasets every section.
The example data
Two tables: customers, and the orders they place.
customers
id
name
1
Alice
2
Budi
3
Citra
4
Dewi
orders
id
customer_id
product
101
1
Laptop
102
1
Mouse
103
2
Keyboard
104
NULL
Monitor
A few things are deliberately a bit messy here, because real data is messy. Citra and Dewi never bought anything. Alice bought two things. And order 104 has no customer at all, say a guest checkout. These edge cases are what make the different joins behave differently, so keep them in mind.
SQL to create these tables (open it if you want to follow along)
1CREATETABLE customers (2 id INTPRIMARYKEY,3 name VARCHAR(50)NOTNULL4);56CREATETABLE orders (7 id INTPRIMARYKEY,8 customer_id INT,9 product VARCHAR(50)NOTNULL,10FOREIGNKEY(customer_id)REFERENCES customers(id)11);1213INSERTINTO customers (id, name)VALUES14(1,'Alice'),(2,'Budi'),(3,'Citra'),(4,'Dewi');1516INSERTINTO orders (id, customer_id, product)VALUES17(101,1,'Laptop'),18(102,1,'Mouse'),19(103,2,'Keyboard'),20(104,NULL,'Monitor');
Any online playground works, such as DB Fiddle or SQLite Online. This runs as-is on SQLite, PostgreSQL, and MySQL.
Primary key
A primary key is the column (or columns) that uniquely identifies a row. In customers that's id. If you know the id, you know exactly which row you mean, even if two customers share the same name.
It comes with two rules the database enforces for you: the value must be unique, and it can't be NULL. You also get exactly one primary key per table, although it can span several columns (a composite key).
1INSERTINTO customers (id, name)VALUES(1,'Eko');2-- fails: id 1 already belongs to Alice
One practical note: pick keys that never need to change. People change names, emails, even phone numbers. A plain auto-incrementing integer or a UUID is boring, and boring is what you want here.
Foreign key
A foreign key is a column that points at the primary key of another table. Here, orders.customer_id refers to customers.id, which is how the database knows that Laptop and Mouse belong to Alice.
Entity Relationship Diagram
o
ORDERS:
places
CUSTOMERS{
intid
PK
stringname
places
1───0..*
ORDERS
intid
PK
intcustomer_id
FK
stringproduct
The line in the middle reads as "one customer, zero or many orders."
The real value of a foreign key is that the database won't let you break the link:
1INSERTINTO orders (id, customer_id, product)VALUES(105,99,'Webcam');2-- fails: there is no customer 99
Without the constraint, that row would go in quietly, and months later you'd be debugging a report that has orders belonging to nobody.
How they differ
Primary key
Foreign key
Points to
Identifies its own row
A row in another table
Duplicates
Never
Fine (Alice appears twice)
NULL
Never
Allowed, unless you forbid it
Per table
One
As many as you need
A simple way to remember it: the primary key says who this row is, and the foreign key says who it belongs to.
Joins
A foreign key stores the relationship. A join is how you use it in a query. You tell SQL which two columns should match, and it stitches the rows together:
1ON orders.customer_id = customers.id
The part that matters is what happens to rows that have no match, and that's the only thing separating the four join types. Here's a rough picture, with customers on the left, orders on the right, and the overlap in the middle:
customers orders
┌──────────────────┐ ┌──────────────────┐
│ Citra │ │ │
│ Dewi │ │ Monitor │
│ ┌────────┼──────┼───────┐ │
│ │ Alice (Laptop, Mouse) │ │
│ │ Budi (Keyboard) │ │
│ └────────┼──────┼───────┘ │
└──────────────────┘ └──────────────────┘
only in customers matched only in orders
INNER JOIN
Only rows that match on both sides. Anything without a partner is thrown away.
1SELECT c.name, o.product
2FROM customers c
3INNERJOIN orders o ON o.customer_id = c.id;
name
product
Alice
Laptop
Alice
Mouse
Budi
Keyboard
Citra and Dewi are gone because they have no orders, and the Monitor is gone because it has no customer. This is the right choice when you only care about complete pairs, like "show me every order along with who placed it."
LEFT JOIN
Every row from the left table, plus whatever matches from the right. Where there's no match, the right-hand columns come back as NULL.
1SELECT c.name, o.product
2FROM customers c
3LEFTJOIN orders o ON o.customer_id = c.id;
name
product
Alice
Laptop
Alice
Mouse
Budi
Keyboard
Citra
NULL
Dewi
NULL
Now Citra and Dewi show up, with empty order columns. The Monitor still doesn't, because it lives in the right table and has no match.
This is the join I reach for most often. Whenever the question is "list all of X, and include Y if it exists," that's a left join.
It also gives you a handy way to find things that are missing. Filter for the NULLs and you get every customer who has never ordered:
1SELECT c.name
2FROM customers c
3LEFTJOIN orders o ON o.customer_id = c.id
4WHERE o.id ISNULL;5-- Citra, Dewi
RIGHT JOIN
The mirror image: every row from the right table, matches from the left.
1SELECT c.name, o.product
2FROM customers c
3RIGHTJOIN orders o ON o.customer_id = c.id;
name
product
Alice
Laptop
Alice
Mouse
Budi
Keyboard
NULL
Monitor
Every order is present now, including the guest one, and Citra and Dewi disappear.
In practice you'll rarely write this. Swapping the table order turns it into a left join, and most people find "main table first" easier to read. It's worth knowing mostly so you can read other people's queries.
FULL OUTER JOIN
Everything from both sides. Matches are paired up, and everything else is kept with NULLs on the missing side.
1SELECT c.name, o.product
2FROM customers c
3FULLOUTERJOIN orders o ON o.customer_id = c.id;
name
product
Alice
Laptop
Alice
Mouse
Budi
Keyboard
Citra
NULL
Dewi
NULL
NULL
Monitor
This is useful for reconciliation, such as comparing two lists and seeing what's missing from either. MySQL doesn't support it, so there you combine a left and a right join with UNION:
1SELECT c.name, o.product FROM customers c LEFTJOIN orders o ON o.customer_id = c.id
2UNION3SELECT c.name, o.product FROM customers c RIGHTJOIN orders o ON o.customer_id = c.id;
A note on the word "outer"
Left, right, and full joins are all outer joins, meaning they keep unmatched rows. The word OUTER is optional: LEFT JOIN and LEFT OUTER JOIN do the same thing.
Decision & Hierarchy Flowchart
JOIN
INNER
matches only
OUTER
keeps unmatched rows
LEFT
unmatched from left
RIGHT
unmatched from right
FULL
unmatched from both
Side by side
Join
Unmatched customers
Unmatched orders
Rows returned
INNER
dropped
dropped
3
LEFT
kept
dropped
5
RIGHT
dropped
kept
4
FULL OUTER
kept
kept
6
If you're unsure which one you need, this is how I'd decide:
Decision & Hierarchy Flowchart
What should happen to
rows with no match?
Drop them
INNER JOIN
Keep them from my main table
LEFT JOIN
Keep them from the other table
RIGHT JOIN, or swap tables and use LEFT
Keep them from both
FULL OUTER JOIN
Mistakes worth knowing about
Putting a filter on the right table in WHERE. This one catches almost everyone at least once. Say you write LEFT JOIN orders o ON ... WHERE o.product = 'Mouse'. The NULL rows can never equal 'Mouse', so they get filtered out and your left join quietly behaves like an inner join. If the condition belongs to the join, put it in ON:
1LEFTJOIN orders o ON o.customer_id = c.id AND o.product ='Mouse'
Forgetting that row counts change. Alice has two orders, so she appears twice in the result. Joining across a one-to-many relationship multiplies rows, which matters a lot when you then SUM or COUNT something. If your totals look too high, this is the first place to check.
Leaving out the ON clause. Depending on the database you either get an error or a cross join, where every row is paired with every other row. With two small tables that's harmless. With two big ones it can take your query (and sometimes your database) down.
Not indexing foreign keys. Primary keys get an index automatically. Foreign key columns often don't, PostgreSQL being one example. If you join on orders.customer_id regularly, add an index to it.
Check your understanding
1. Can a table have two primary keys?
Answer
No, only one. But that one key can be made of multiple columns, for example PRIMARY KEY (order_id, product_id) in an order-items table.
2. Can a foreign key column hold duplicates or NULL?
Answer
Yes to both, unless you add UNIQUE or NOT NULL. Alice's id appears twice in orders.customer_id, and order 104 has NULL there.
3. You want every product, with the customer's name when there is one. Which join?
Answer
Make orders the main table and left join to customers:
1SELECT o.product, c.name
2FROM orders o
3LEFTJOIN customers c ON c.id = o.customer_id;
The Monitor row comes back with a NULL name.
4. Why does customers LEFT JOIN orders return 5 rows when there are only 4 customers?
Answer
Alice has two orders, so she's returned twice. A join gives one row per matching pair, and unmatched left rows (Citra, Dewi) add one row each. That's 2 + 1 + 1 + 1 = 5.
5. How would you find orders with no customer?
Answer
1SELECT o.*2FROM orders o
3LEFTJOIN customers c ON c.id = o.customer_id
4WHERE c.id ISNULL;
Try it yourself
Add a payments table with id, order_id (a foreign key to orders), and amount. Then write one query that lists every customer, their orders, and the payment for each order, while still keeping customers who haven't ordered anything. You'll need two left joins in a row, and thinking through why the second one has to be a left join too is a good test of whether this all clicked.