Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

SQL Joins Explained: Keep the Rows You Need, Avoid Duplicates

· 7 min read · Home Tech

In this article
  1. Why Joins Can Produce Duplicates
  2. The Four Core Join Types
  3. How to Choose the Right Join
  4. Common Pitfalls and How to Avoid Them
  5. Real-World Example: Customers and Orders
  6. Performance and Indexing Considerations
  7. Alternatives to Joins
  8. Frequently Asked Questions

SQL joins combine rows from two or more tables based on a related column, and the key to keeping exactly the rows you need without duplicates is choosing the right join type and understanding how the ON condition filters matches. This article explains each join type, shows how to prevent unintended row multiplication, and gives practical tips for writing accurate join queries.

Why Joins Can Produce Duplicates

When you join two tables, the database pairs every row from the left table with every row from the right table that satisfies the ON condition. If the column you join on is not unique in one of the tables, that row will appear multiple times in the result. For example, if you join a customers table (one row per customer) to an orders table (multiple rows per customer) on customer_id, each customer row will be repeated for every order they have. This is not a bug—it is how relational databases work—but it can surprise beginners who expect one row per customer.

The Four Core Join Types

SQL has four main join types, each with a distinct effect on the rows returned:

  • INNER JOIN: Returns only rows where the ON condition matches in both tables. Rows in either table without a match are omitted.
  • LEFT JOIN (or LEFT OUTER JOIN): Returns all rows from the left table, plus matched rows from the right table. If there is no match, the right-side columns are filled with NULL.
  • RIGHT JOIN (or RIGHT OUTER JOIN): The mirror of LEFT JOIN—all rows from the right table, plus matches from the left. Not supported by all databases (e.g., SQLite), but can be simulated by swapping the tables.
  • FULL OUTER JOIN: Returns all rows from both tables, filling NULLs where there is no match. Supported by PostgreSQL, SQL Server, and Oracle, but not by MySQL or SQLite (though they can emulate it with UNION).

There is also CROSS JOIN, which pairs every row of the left table with every row of the right table, producing a Cartesian product. It is rarely used intentionally, but it can be a source of massive row counts if you forget an ON clause.

How to Choose the Right Join

Your choice of join depends on which rows you want to preserve:

  • Use INNER JOIN when you only want rows that have a match in both tables—for example, customers who have placed at least one order.
  • Use LEFT JOIN when you want all rows from the left table regardless of whether a match exists—for example, all products, even those never ordered.
  • Use RIGHT JOIN when you want all rows from the right table—though many developers prefer to rewrite this as a LEFT JOIN by swapping the table order for readability.
  • Use FULL OUTER JOIN when you need all rows from both tables, such as merging two lists of users from different sources.

A common rule of thumb: start with the table that represents the “main” entity you want to list, then use LEFT JOIN if you want to include rows without matches, or INNER JOIN if you want to exclude them.

Common Pitfalls and How to Avoid Them

Beyond choosing the wrong join type, several mistakes can lead to unexpected duplicates:

  • Joining on non-unique columns: If the join column has duplicates in either table, the result will have more rows than expected. Always check that the join key is unique in at least one table (ideally a primary key or a unique constraint).
  • Forgetting the ON condition: Omitting ON in a JOIN (or using a comma-separated FROM) creates a CROSS JOIN, returning every combination of rows. This can explode the row count.
  • Multiple joins that multiply rows: Joining table A to B (one-to-many) and then to C (also one-to-many) can produce rows that appear multiple times due to the combined effect. For example, joining customers to orders and then to order_items can duplicate order rows if you don’t join on the correct keys.
  • Using DISTINCT as a band-aid: Adding DISTINCT removes exact duplicate rows, but it can hide the underlying problem and may remove rows that are legitimately different (e.g., two orders on the same date). It also adds performance overhead.

To avoid these, always inspect the data with a quick SELECT * before applying aggregation, and use COUNT(*) to compare row counts before and after the join.

Real-World Example: Customers and Orders

Suppose you have two tables:

customers (customer_id, name)
orders (order_id, customer_id, order_date)

If you run:

SELECT * FROM customers
LEFT JOIN orders ON customers.customer_id = orders.customer_id;

you will get one row per order for each customer, with customers who have no orders appearing once with NULL order columns. If you only want customers who have placed at least one order, use INNER JOIN. If you want a count of orders per customer without listing every order, you would use:

SELECT customers.customer_id, COUNT(orders.order_id)
FROM customers
LEFT JOIN orders ON customers.customer_id = orders.customer_id
GROUP BY customers.customer_id;

Here, the LEFT JOIN ensures customers with zero orders still appear with a count of 0, while INNER JOIN would omit them entirely.

Performance and Indexing Considerations

Joins can be expensive on large tables. To keep queries fast, ensure that the columns used in the ON condition are indexed. A primary key is automatically indexed, but foreign keys often are not. Creating an index on the foreign key column in the child table (e.g., orders.customer_id) can dramatically speed up joins. Also, avoid selecting unnecessary columns—use SELECT with explicit column lists instead of SELECT * to reduce the amount of data transferred.

When joining multiple tables, the database’s query optimizer decides the order of operations, but you can help by filtering rows early with WHERE clauses and by using the most selective join conditions first.

Alternatives to Joins

Sometimes a join is not the best tool. Consider these alternatives:

  • Subqueries: Use a correlated subquery to fetch a single value from another table, such as the latest order date per customer. This can be clearer than a join with aggregation.
  • EXISTS / NOT EXISTS: When you only need to check for the existence of a match, EXISTS is often more efficient and avoids duplicates entirely.
  • UNION: To combine rows from two tables with the same structure, use UNION (which removes duplicates) or UNION ALL (which keeps them).
  • Window functions: For tasks like ranking or running totals, window functions (e.g., ROW_NUMBER) can replace self-joins and are usually faster.

For example, to find customers who have placed at least one order, you could write:

SELECT * FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);

This is often more efficient than a JOIN followed by DISTINCT.

Frequently Asked Questions

Why does my LEFT JOIN return more rows than the left table?

Because the right table has multiple matching rows for a single left row. For example, if one customer has three orders, the LEFT JOIN will produce three rows for that customer. To get one row per left record, you need to aggregate the right table or use a subquery to limit matches.

How do I remove duplicates from a join result?

First, understand why duplicates exist. If they are caused by a one-to-many relationship, you may need to aggregate (e.g., using GROUP BY) or use DISTINCT only if the entire row is duplicated. If duplicates come from non-unique join keys, fix the join condition or clean the data.

What is the difference between INNER JOIN and LEFT JOIN?

INNER JOIN returns only rows with matches in both tables. LEFT JOIN returns all rows from the left table, and for rows without a match in the right table, the right-side columns are NULL. Use INNER JOIN when you want to exclude unmatched rows, and LEFT JOIN when you want to keep them.

Can I join more than two tables?

Yes, you can chain multiple joins. For example, FROM customers c JOIN orders o ON c.id = o.customer_id JOIN order_items i ON o.id = i.order_id. Each join adds its own condition, and the result set is the combination of all conditions. Be mindful that each join can multiply rows if the relationships are one-to-many.

What does ON vs USING mean in a join?

ON lets you specify any condition, such as ON a.id = b.customer_id. USING is a shorthand for equality on columns with the same name, e.g., JOIN orders USING (customer_id). USING automatically removes the duplicate column from the result, while ON keeps both columns.

Why is my join so slow?

Common causes include missing indexes on the join columns, large result sets, or a CROSS JOIN due to a missing ON clause. Check the execution plan, add indexes, and ensure you are not selecting more columns than needed.