DATABASE ENGINEERING · SQL QUERY DEBUGGING LAB
Your JOIN Isn’t Always Wrong. Your Assumption About the Data Might Be.
Learn why SQL joins multiply rows, how to identify the relationship causing the problem, and how to correct the query without hiding mistakes behind DISTINCT.
You write a SQL query to combine customers with their orders.
The customer table contains 100 records, but the result unexpectedly contains 350 rows.
Your first reaction might be that the JOIN is broken.
However, SQL may be doing exactly what you asked.
A JOIN returns combinations of rows that satisfy its matching condition.
If one customer matches several orders, that customer can appear several times in the result.
This behavior is not necessarily a database error.
The real problem often comes from misunderstanding the relationship between the tables or expecting one row per entity when the query produces one row per relationship.
To fix unexpected duplicate rows, first determine why multiple matches exist. Then change the query to express the result you actually need.
What Does a SQL JOIN Actually Return?
A SQL JOIN combines rows from two tables according to a specified condition.
Consider two tables: customers and orders.
The customers table contains one row per customer.
The orders table may contain multiple rows for the same customer because a customer can place several orders.
When the tables are joined using customer_id, SQL returns a row for each matching customer-order pair.
For example, if one customer has three orders, that customer appears three times in the joined result.
The customer information is repeated because each output row represents a different order.
This is expected behavior for a one-to-many relationship.
DATABASE RELATIONSHIP / ONE CUSTOMER, MULTIPLE ORDERS
customer_id: 101
name: Alice
order_id: 501 → 101
order_id: 502 → 101
order_id: 503 → 101
JOIN result: Three rows for Alice because three matching orders exist.
A Simple Example of Duplicate-Looking Rows
Suppose the database contains these records.
Customers Table
| customer_id | name |
|---|---|
| 101 | Alice |
| 102 | Bob |
Orders Table
| order_id | customer_id |
|---|---|
| 501 | 101 |
| 502 | 101 |
| 503 | 102 |
Now run this query:
SELECT
c.customer_id,
c.name,
o.order_id
FROM customers AS c
JOIN orders AS o
ON c.customer_id = o.customer_id;The result contains three rows.
Alice appears twice because she has two orders.
Bob appears once because he has one order.
Nothing is wrong with the JOIN.
The result represents individual orders rather than unique customers.
Reason 1: One-to-Many Relationships
The most common cause of repeated rows is a one-to-many relationship.
Examples include customers and orders, authors and articles, departments and employees, or products and reviews.
In each case, one record in the parent table may match several records in the related table.
When you join these tables, the parent record is repeated for every matching child record.
If you need one row per order, this is correct.
If you need one row per customer, the query must be designed differently.
The important question is not whether the JOIN produces repeated values.
It is whether the result has the correct level of detail.
Reason 2: Many-to-Many Relationships
Many-to-many relationships can create even more rows.
Consider students and courses.
One student can enroll in several courses.
One course can contain several students.
A junction table, such as enrollments, records these relationships.
Joining students with enrollments produces one row for each enrollment.
Joining additional one-to-many tables may multiply the result further.
For example, joining a customer to both orders and support tickets can produce combinations of orders and tickets.
If a customer has three orders and four tickets, the joined result may contain 12 rows for that customer.
This happens because each matching order can be combined with each matching ticket.
Understanding this multiplication is essential when building reporting queries.
Reason 3: Missing or Incomplete JOIN Conditions
Sometimes the JOIN condition does not identify the intended relationship correctly.
For example, suppose an application stores order numbers separately for each store.
The correct order identity may depend on both store_id and order_number.
Joining only on order_number can match records belonging to different stores.
Consider this incomplete condition:
SELECT *
FROM orders AS o
JOIN shipments AS s
ON o.order_number = s.order_number;If the same order number exists in multiple stores, this query may create incorrect matches.
A more appropriate condition might be:
SELECT *
FROM orders AS o
JOIN shipments AS s
ON o.store_id = s.store_id
AND o.order_number = s.order_number;The correct columns depend on the database schema.
The underlying lesson is to join using the complete relationship key.
Reason 4: Duplicate Data in the Source Tables
Repeated results can also originate from duplicate records already stored in the database.
Suppose an email address appears several times in a customer table.
Joining another table using email address may create multiple matches.
This is especially risky when the joined column is not guaranteed to be unique.
Before changing the query, inspect the source data.
For example:
SELECT
email,
COUNT(*) AS record_count
FROM customers
GROUP BY email
HAVING COUNT(*) > 1;This identifies email values appearing more than once.
However, repeated email addresses are not necessarily invalid in every database.
Whether they represent a data-quality problem depends on the intended business rules.
Step 1: Identify the Expected Result
Before debugging, define what one output row should represent.
Should the result contain one row per customer?
One row per order?
One row per product?
Or one row per customer-product combination?
Database engineers often call this the result’s grain.
Once the grain is clear, it becomes easier to recognize which joins are expected to multiply rows.
For example, a sales report grouped by customer should not directly display individual order lines without aggregation.
A report showing order details, however, may legitimately contain several rows for the same customer.
QUERY DEBUGGING PRINCIPLE
Define What One Row Means Before Writing the JOIN.
Unexpected duplicates are often a mismatch between the intended result grain and the actual relationship cardinality.
Step 2: Count Matches Before Joining
A useful debugging technique is to count related records for each parent key.
For example:
SELECT
customer_id,
COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
ORDER BY order_count DESC;This shows how many orders belong to each customer.
If one customer has 15 orders, a normal customer-to-orders JOIN can return 15 rows for that customer.
You can also check how many matches appear after a join:
SELECT
c.customer_id,
COUNT(*) AS joined_rows
FROM customers AS c
JOIN orders AS o
ON c.customer_id = o.customer_id
GROUP BY c.customer_id
ORDER BY joined_rows DESC;Comparing these counts helps reveal where row multiplication occurs.
Step 3: Add JOINs One at a Time
Complex queries often contain several joins.
Instead of examining the complete query immediately, build it incrementally.
Start with the main table.
Count its rows.
Add the first JOIN and count again.
Continue adding tables until the unexpected increase appears.
This approach helps identify the relationship responsible for the multiplication.
It is especially useful when several one-to-many relationships are involved.
Once the problematic join is identified, inspect its matching columns and expected cardinality.
Fix 1: Use EXISTS When You Only Need to Check for a Match
Sometimes you do not need data from the joined table.
You only need to know whether a related record exists.
For example, suppose you want customers who have placed at least one order.
A JOIN can return several rows for customers with multiple orders.
Instead, use EXISTS:
SELECT
c.customer_id,
c.name
FROM customers AS c
WHERE EXISTS (
SELECT 1
FROM orders AS o
WHERE o.customer_id = c.customer_id
);This returns each qualifying customer row once, assuming the customers table itself contains one row per customer.
EXISTS is often a clearer expression of a yes-or-no relationship check.
Fix 2: Aggregate the Child Table Before Joining
Suppose you want one row per customer showing their total order count.
Joining every order directly creates multiple customer rows.
Instead, summarize the orders first.
SELECT
c.customer_id,
c.name,
COALESCE(o.order_count, 0) AS order_count
FROM customers AS c
LEFT JOIN (
SELECT
customer_id,
COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
) AS o
ON c.customer_id = o.customer_id;The subquery produces one row per customer ID.
The outer query then joins customers to those summarized results.
This avoids multiplying customer rows by the number of individual orders.
It also preserves customers who have no orders.
Fix 3: Use ROW_NUMBER() When You Need One Specific Related Row
Sometimes you need exactly one related record, such as the latest order for each customer.
In that situation, simply removing duplicates is not enough.
You must define which order should be selected.
A window function can help:
WITH ranked_orders AS (
SELECT
order_id,
customer_id,
order_date,
ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY order_date DESC, order_id DESC
) AS rn
FROM orders
)
SELECT
c.customer_id,
c.name,
r.order_id,
r.order_date
FROM customers AS c
LEFT JOIN ranked_orders AS r
ON c.customer_id = r.customer_id
AND r.rn = 1;The ROW_NUMBER() function assigns a ranking within each customer group.
The query then selects the first ranked order.
The additional order_id sorting condition provides a deterministic tie-breaker when order dates match, assuming order IDs are unique.
This approach is useful when the business requirement is to select one specific related record.
Why DISTINCT Is Often the Wrong First Fix
The DISTINCT keyword removes duplicate result rows based on the selected columns.
It can be useful when unique combinations are genuinely required.
However, it does not repair an incorrect JOIN condition.
It also does not necessarily produce one row per business entity.
For example:
SELECT DISTINCT
c.customer_id,
c.name
FROM customers AS c
JOIN orders AS o
ON c.customer_id = o.customer_id;This may produce one row per customer because the selected customer columns are identical across their orders.
But if you include o.order_id, the rows remain distinct.
More importantly, DISTINCT can conceal a misunderstanding of the data relationship.
Before using it, determine whether the query should instead use EXISTS, aggregation, or a corrected JOIN condition.
| Problem | Better Approach | Why It Works |
|---|---|---|
| Need customers with at least one order | EXISTS | Checks for a match without returning every order |
| Need order totals per customer | GROUP BY before JOIN | Produces one summary row per customer |
| Need the latest order | ROW_NUMBER() | Selects a defined related record |
| Wrong records are matching | Correct the ON condition | Uses the intended relationship key |
| Source records violate uniqueness rules | Fix data and constraints | Addresses the underlying data-quality issue |
How GROUP BY Differs from DISTINCT
DISTINCT removes duplicate combinations from selected output columns.
GROUP BY organizes rows into groups so aggregate calculations can be performed.
For example, grouping orders by customer allows you to calculate order counts or totals.
Although both can reduce the number of result rows, they serve different purposes.
If your goal is to summarize several orders into one customer-level result, GROUP BY is often the more meaningful solution.
If your goal is to return unique combinations of selected values, DISTINCT may be appropriate.
The correct choice depends on the required result.
Why LEFT JOIN Can Also Produce Repeated Rows
A common misunderstanding is that LEFT JOIN guarantees one output row for every row in the left table.
It does not.
A LEFT JOIN preserves unmatched rows from the left table, but it still returns multiple rows when several right-table records match.
If one customer has five orders, a left join can return five rows for that customer.
If another customer has no orders, the left join returns one row with null values for the right-table columns.
Therefore, switching from INNER JOIN to LEFT JOIN does not solve one-to-many row multiplication.
It changes how unmatched rows are handled.
How Database Constraints Help Prevent Unexpected Matches
Good database design makes relationships easier to understand and query correctly.
Primary keys identify rows uniquely.
Unique constraints enforce uniqueness rules for selected columns or column combinations.
Foreign keys help define valid relationships between tables.
These constraints do not eliminate legitimate one-to-many relationships.
However, they help prevent unintended duplicate records and clarify which columns should be used in joins.
For example, if a table is intended to contain only one profile per user, a unique constraint on user_id can enforce that requirement.
When uniqueness is guaranteed by the schema, developers can reason about join cardinality more confidently.
A Practical SQL JOIN Debugging Checklist
QUERY DIAGNOSTICS / SIX QUESTIONS
Define the result grain before investigating duplicates.

