SQL Inner Joins: Combining Rows From Related Tables
How INNER JOIN combines rows from two or more tables: the ON condition, table aliases, qualified and ambiguous column names, joining three or four tables, USING and NATURAL JOIN, the old comma syntax, joins on non-key columns, and why rows without a match disappear.
kvi5hnuCode Sprout team member12 min readOn this page
Part 2 queried one table at a time. Real databases spread information across many tables, linked by keys (article 1): an order records a customer_id, not the customer's name, and an order line records a product_id, not the product's details. To answer "who placed order 102?" or "which products did Asha buy?", a query has to join the tables, combining rows from several tables into one result.
This part uses a small shop database. Every runnable example creates it first:
| Table | Rows | Notes |
|---|---|---|
products | the 7 products from Part 2 | the Basecamp lantern has never been ordered |
customers | 6 customers, with customer_id, name, city and referred_by | Eli and Farah have no orders, and Farah's city is NULL |
orders | 6 orders, with order_id, customer_id, placed_on and status | order 106 is a guest checkout, so its customer_id is NULL |
order_items | 9 order lines, with order_id, product_id, qty and unit_price | primary key (order_id, product_id) |
Your first join
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Each order with the name of the customer who placed it
SELECT o.order_id, o.placed_on, c.name AS customer
FROM orders AS o
INNER JOIN customers AS c ON c.customer_id = o.customer_id
ORDER BY o.order_id;
order_id | placed_on | customer
----------+------------+------------
101 | 2026-03-02 | Asha Rao
102 | 2026-03-05 | Ben Okafor
103 | 2026-03-09 | Asha Rao
104 | 2026-03-15 | Chen Wei
105 | 2026-03-20 | Dana Cruz
(5 rows)
The query reads like this:
FROM orders AS o INNER JOIN customers AS cnames the two tables and gives them short aliases,oandc.ON c.customer_id = o.customer_idis the join condition. It says which rows belong together: an order and the customer whose key it records.- The select list can now use columns from both tables.
Logically, a join considers every combination of an order and a customer, and keeps the combinations where the ON condition is true. (The database doesn't actually build every combination. It uses indexes and smarter algorithms, but the result is the same.) Each kept combination becomes one result row.

Notice what's missing:
- Order 106 has a NULL
customer_id.NULL = anythingis unknown (article 8), so it matches no customer and isn't in the result. - Eli and Farah have no orders, so no order row pairs with them.
That's the defining property of an inner join: only rows that have a match on the other side are kept. If you need the unmatched rows too, such as all customers including those without orders, you need an outer join (article 13). Choosing between the two is one of the most important decisions in writing a query, and getting it wrong silently drops rows from reports.
INNER is optional: JOIN on its own means an inner join. Many people write JOIN and reserve the full word for emphasis. This course writes JOIN from here on.
Table aliases and qualified columns
A qualified column name includes its table, or the table's alias: o.customer_id, c.name. You must qualify a column whose name exists in more than one of the joined tables, and it's good practice to qualify every column in a join, so that readers don't have to know every table's columns.
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- A column that exists in both tables must be qualified
SELECT order_id, customer_id, name
FROM orders
JOIN customers ON customers.customer_id = orders.customer_id;
-- The older "comma" syntax: the join condition goes in WHERE
SELECT o.order_id, c.name
FROM orders o, customers c
WHERE c.customer_id = o.customer_id
AND o.status = 'shipped'
ORDER BY o.order_id;
-- Forget the condition and every order pairs with every customer
SELECT COUNT(*) AS pairs FROM orders, customers;
psql:/workspace/solution.sql:65: ERROR: column reference "customer_id" is ambiguous
LINE 1: SELECT order_id, customer_id, name
^
order_id | name
----------+------------
101 | Asha Rao
102 | Ben Okafor
(2 rows)
pairs
-------
36
(1 row)
- Ambiguous column. Both tables have a
customer_id, so the unqualified name in the select list is an error. The database doesn't assume they're the same, even though the join makes them equal. - Aliases.
FROM orders AS oandFROM orders oboth work in PostgreSQL, MySQL, SQL Server and SQLite. Oracle doesn't allowASbefore a table alias, only before a column alias, soFROM orders ois the portable form. Once a table has an alias, refer to it by the alias. In PostgreSQL, using the full table name for an aliased table is an error.
The comma syntax
The second query uses the older syntax: list the tables separated by commas, and put the join condition in WHERE. It gives exactly the same result as JOIN ... ON, and you'll see it in a lot of existing code. Prefer JOIN ... ON because:
- the join conditions stay next to the tables they join, separate from the filters;
- forgetting a condition is much easier to spot;
- outer joins can only be written in the
JOINsyntax (apart from the old, proprietary(+)notation in Oracle).
The last query shows what happens when the condition is forgotten: every order is paired with every customer, 6 × 6 = 36 rows. This is called a Cartesian product or cross join (article 14). With real tables, 100,000 orders times 50,000 customers gives five billion rows, so a missing join condition is a classic way to make a query run for hours.
Joining three or more tables
A query can join as many tables as it needs. Each additional JOIN adds one more table, with its own ON condition connecting it to tables already in the query:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Three tables: each order line with its customer and product
SELECT o.order_id,
c.name AS customer,
p.name AS product,
oi.qty,
oi.unit_price,
oi.qty * oi.unit_price AS line_total
FROM orders AS o
JOIN customers AS c ON c.customer_id = o.customer_id
JOIN order_items AS oi ON oi.order_id = o.order_id
JOIN products AS p ON p.product_id = oi.product_id
WHERE o.status <> 'cancelled'
ORDER BY o.order_id, p.name;
order_id | customer | product | qty | unit_price | line_total
----------+------------+-------------------+-----+------------+------------
101 | Asha Rao | Merino socks | 3 | 16.00 | 48.00
101 | Asha Rao | Ridge 2 tent | 1 | 249.99 | 249.99
102 | Ben Okafor | Glow head torch | 2 | 34.50 | 69.00
103 | Asha Rao | Glow head torch | 1 | 34.50 | 34.50
103 | Asha Rao | Merino socks | 2 | 15.00 | 30.00
103 | Asha Rao | Trail 30 backpack | 1 | 89.95 | 89.95
104 | Chen Wei | Summit 4 tent | 1 | 489.00 | 489.00
(7 rows)
The query follows the foreign keys: order lines point to orders and products, and orders point to customers. It's normal to have one more JOIN for each table, and each ON condition usually follows one foreign key.
Things to notice:
- The result has one row per order line, because the most detailed table,
order_items, determines the "grain" of the result. Order 103 has three lines, so it appears three times. Keeping track of a query's grain is how you avoid accidental duplication (article 17). WHEREfilters after joining, so it can refer to any joined table. Here it removes the cancelled order 105.- Inner joins drop rows at every step. The guest order 106 disappeared at the join to
customers, so its line for socks is missing too. The lantern doesn't appear because no line references it. - The order of
JOINclauses doesn't affect the result of inner joins. The optimizer picks its own order for joining the tables, based on their sizes and indexes. Write them in the order that reads most naturally.
USING and NATURAL JOIN
When the joined columns have the same name in both tables, standard SQL offers a shorter form, USING:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- USING: join on columns with the same name; the column appears once
SELECT order_id, customer_id, name, placed_on
FROM orders
JOIN customers USING (customer_id)
WHERE placed_on < DATE '2026-03-10'
ORDER BY order_id;
-- A join on columns that aren't keys: lines sold below the current list price
SELECT oi.order_id, p.name, oi.unit_price, p.price AS list_price
FROM order_items AS oi
JOIN products AS p
ON p.product_id = oi.product_id
AND oi.unit_price < p.price
ORDER BY oi.order_id;
order_id | customer_id | name | placed_on
----------+-------------+------------+------------
101 | 1 | Asha Rao | 2026-03-02
102 | 2 | Ben Okafor | 2026-03-05
103 | 1 | Asha Rao | 2026-03-09
(3 rows)
order_id | name | unit_price | list_price
----------+--------------+------------+------------
103 | Merino socks | 15.00 | 16.00
(1 row)
JOIN customers USING (customer_id) means ON orders.customer_id = customers.customer_id, and the joined column appears once in the result, so the unqualified customer_id in the select list isn't ambiguous anymore. PostgreSQL, MySQL, Oracle and SQLite support USING. SQL Server doesn't.
NATURAL JOIN goes one step further: it joins on every column name the two tables have in common, without naming them. Avoid it. The join condition is invisible, and it changes silently when someone adds a column. If orders and customers both gained a created_at or notes column, a NATURAL JOIN would start requiring those to be equal too, and most rows would vanish.
Join conditions beyond keys
Most joins compare a foreign key with a primary key, but an ON condition can be any condition:
- Compound conditions. In the second query above, the
ONclause includesoi.unit_price < p.price, so it finds order lines sold below the product's current list price. Only the socks in order 103 qualify, at 15.00 instead of 16.00. Composite keys always need compound conditions, as inON a.order_id = b.order_id AND a.product_id = b.product_id. - Ad hoc relationships. You can join on columns that aren't declared as keys at all, such as customers and stores in the same city. Joins don't depend on foreign keys existing. Constraints protect the data, while joins just compare values.
- Non-equi joins use
<,BETWEENor other operators, for example to match each order to a price band or a date range. Article 14 covers them.
ON or WHERE?
For an inner join, a filter condition gives the same result whether you write it in ON or in WHERE. JOIN products p ON p.product_id = oi.product_id AND p.category = 'tents' and the same join with WHERE p.category = 'tents' return the same rows. By convention, put the conditions that relate the tables in ON, and the conditions that filter rows in WHERE.
For outer joins, the two places give different results, and mixing them up is a common bug. Article 13 explains why.
How databases execute joins
You don't need to know how a join is executed to write a correct one, but it helps to understand performance. Optimizers choose among three main algorithms:
- Nested loop: for each row of one table, look up matching rows in the other, ideally through an index. It's best when one side is small, or when there's an index on the join column.
- Hash join: build an in-memory hash table from the smaller input, then scan the other input and probe the hash table. It's best for large, unsorted inputs joined with
=. - Merge join: sort both inputs on the join key, then walk through them together. It's best when both inputs are already sorted, for example by an index.
For joins to be fast, index the foreign key columns (such as orders.customer_id and order_items.product_id). Primary keys are indexed automatically, but in most products foreign keys aren't (MySQL's InnoDB is an exception: it creates one automatically). Articles 55 and 67 look at indexes and query plans.
What's current
- The explicit
JOIN ... ONsyntax has been standard since SQL-92 and is supported everywhere. The comma syntax remains valid, but style guides and linters generally prefer explicit joins. - SQL Server still doesn't support
USINGorNATURAL JOIN. Oracle still rejectsASbefore table aliases, even in 26ai. - PostgreSQL 18 can remove some unnecessary self-joins during planning, and each recent release has improved how the planner handles joins. These changes affect speed, never results.
Common questions
Is JOIN the same as INNER JOIN?
Yes. INNER is the default kind of join.
Does the order of tables in an inner join matter?
Not for the result. a JOIN b and b JOIN a give the same rows (possibly with columns in a different order), and the optimizer picks the order in which it actually joins them. With outer joins, the order does matter.
Why did my join return fewer rows than the table has? An inner join drops rows that have no match, including rows whose join column is NULL. Check for rows without a partner, and use an outer join if they should be kept.
Why did my join return more rows than the table has? A row matched several rows on the other side. That's correct for one-to-many relationships, such as an order with three lines. It's a bug when the join condition is incomplete, for example when a composite key is only partly compared. Article 17 covers this.
Do I need a foreign key constraint to join two tables? No. A join compares values, and works on any columns with comparable types. A foreign key guarantees the values match, and helps some optimizers, but it isn't required.
Can I join a table to itself?
Yes, using two different aliases. It's called a self join, and it's used for relationships within one table, such as the referred_by column of customers. Article 14 covers it.
Should I use USING or ON?
USING is shorter and removes duplicate columns, but it only works when the column names are identical, and not in SQL Server. ON works in every case and product, so it's the safer habit.
Summary
JOIN ... ON conditioncombines rows from two tables. An inner join keeps only combinations where the condition is true.- Rows without a match, including rows whose join column is NULL, are left out of an inner join.
- Give tables short aliases and qualify columns. A column name that exists in several joined tables must be qualified. Oracle rejects
ASbefore table aliases. - The comma syntax with conditions in
WHEREis equivalent but easier to get wrong. Forgetting a condition produces a Cartesian product. - Join several tables by adding one
JOINper table, usually following foreign keys. The most detailed table determines how many rows you get. USING (col)joins on same-named columns, which then appear once. AvoidNATURAL JOIN.- For inner joins, filters in
ONand inWHEREare equivalent. For outer joins, they aren't. - Index foreign key columns so that joins are fast.
Practice questions
Write a query that lists every order line for customers in Pune, showing the customer's name, the order date and the product name.
Answer
SELECT c.name AS customer, o.placed_on, p.name AS product
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id
WHERE c.city = 'Pune'
ORDER BY o.placed_on, p.name;
This returns six rows: Asha's five lines from orders 101 and 103, and Chen's Summit 4 tent from order 104.
orders has 6 rows and customers has 6 rows. SELECT * FROM orders JOIN customers ON orders.customer_id = customers.customer_id returns 5 rows. Which row is missing, and why aren't there 6?
Answer
Order 106 is missing. Its customer_id is NULL, so the join condition is unknown for every customer, and an inner join only keeps rows where the condition is true. The two customers without orders, Eli and Farah, don't add rows either, because they have no matching order. The result has one row per order that has a customer: 101 to 105.
Why is this query an error in PostgreSQL, and how do you fix it?
SELECT order_id, product_id, name
FROM order_items
JOIN products ON products.product_id = order_items.product_id;
Answer
product_id exists in both order_items and products, so the unqualified name in the select list is ambiguous, even though the join makes the two values equal. Qualify it, as in SELECT oi.order_id, oi.product_id, p.name FROM order_items oi JOIN products p ON p.product_id = oi.product_id, or join with USING (product_id), which merges the two columns into one.
A teammate writes FROM orders, order_items, products WHERE orders.order_id = order_items.order_id. What's wrong with the result?
Answer
products has no join condition, so every row from the orders-and-lines join is paired with every product: 9 lines × 7 products = 63 rows instead of 9. Add the missing condition, AND products.product_id = order_items.product_id, or better, rewrite with explicit joins so that each table's condition sits next to it in an ON clause.

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.