Beginner

547. JOIN with DISTINCT

Understand how DISTINCT can remove duplicate result combinations after a JOIN.

📘 Lesson 547 of 728 ⏱ 11 min 🎯 Intermediate

DISTINCT removes duplicate rows from the final result based on all selected columns. It can be useful when the business requirement is to return unique combinations.

JOINs can produce repeated values when multiple related records exist, and sometimes only unique combinations are required.

Return each customer and product category only once even if the customer purchased that category multiple times.

SQL
SELECT DISTINCT
    c.CustomerName,
    p.Category
FROM Customers c
INNER JOIN Orders o
    ON c.CustomerID = o.CustomerID
INNER JOIN Products p
    ON o.ProductID = p.ProductID;

Used in customer segmentation, category analysis, lookup lists, and reporting.

  • DISTINCT removes duplicate result rows.
  • It applies to the complete selected column combination.
  • It should not automatically be used to hide JOIN problems.
  • JOIN relationships should be understood first.
  • DISTINCT can add processing cost on large datasets.
Why use DISTINCT with JOIN?

DISTINCT can return only unique combinations when the JOIN produces repeated result rows.

Should DISTINCT be used to fix every duplicate JOIN?

No. First determine whether duplicates are expected from the relationship or caused by an incorrect JOIN.

Have you finished this lesson?

Introduction to SQL – All Lessons