Calculator Notes: How Many Rows Will My JOIN Return?

A JOIN glues rows from two tables together. Beginners are often surprised by how many rows come back, either far more or fewer than expected. With a pencil and a little arithmetic you can predict the answer before you run the query, which is a great way to check your understanding.

First, two words

A row is one record in a table, such as one customer. A JOIN combines rows from two tables wherever a condition is true, usually "this column in table A equals that column in table B".

The simple rule for an INNER JOIN

For an INNER JOIN on orders.customer_id = customers.id, think of it one row at a time:

If every order belongs to exactly one customer, the answer is simply the number of orders. That is the usual case when you join from the "many" side (orders) to the "one" side (customers).

A tiny worked example

Here are two small tables, made up for practice.

customers.idname
1Ana
2Ben
3Chloe
orders.idcustomer_id
101
111
122

Counting row by row:

Total: 3 rows. Chloe has no orders, so she does not appear at all in an INNER JOIN.

SELECT customers.name, orders.id
FROM orders
JOIN customers ON customers.id = orders.customer_id;

The LEFT JOIN version

A LEFT JOIN keeps every row from the left table, even with no match. If you write FROM customers LEFT JOIN orders ..., the count is:

Ana: 2, Ben: 1, Chloe: 1 (with empty order columns). Total: 4 rows.

When the number explodes

The surprise comes when both sides have repeats. Suppose you join orders to a payments table on customer_id instead of on the order. Ana has 2 orders and, say, 3 payments. Every one of her orders matches every one of her payments: 2 × 3 = 6 rows just for Ana. This is sometimes called a "row explosion", and it usually means the join condition is not the one you meant.

SituationQuick formula
Many-to-one (orders to customers)Rows = number of orders that have a customer
One-to-many with LEFT JOINRows = sum over parents of max(children, 1)
Matching repeats on both sidesRows = product of the repeats, added up per value
No join condition at allRows = rows in A × rows in B

How to check your prediction

Run the query with SELECT COUNT(*) in place of the column list. If the count is not what you predicted, look at the join condition first. It is the most common place for a small typo to make a big difference.

A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.