Pathubs SQL Curriculum • Module 02

SQL DISTINCT Statement

Master result set deduplication: understand single-column unique extraction, multi-column tuple evaluation, NULL behavior, and why DISTINCT is never a substitute for sorting.

⏱️ Estimated Time:40 Minutes
🎯 Level:Beginner First
📊 Track:Data Analytics & SQL Mastery
✨ Mode:Visual Deduplication Lab
1

Introduction

In real-world relational databases, records frequently repeat values across rows. For instance, in an e-commerce platform with 500,000 orders, thousands of customers might reside in Mumbai, Delhi, or London. If you query the customer locations, a standard SELECT city FROM customers; query will return 500,000 rows where city names repeat over and over.

When building filter dropdowns, demographic reports, or categorical summaries, you don’t want 500,000 repeated entries — you need a clean, concise list containing each unique value exactly once. This is the exact problem that DISTINCT solves.

2

What Does DISTINCT Mean?

In SQL, the DISTINCT keyword acts as a deduplication filter on the query's output result set. It examines the returned rows and strips away all duplicate entries, keeping only the first occurrence of each unique value or combination of values.

Original Table Rows (city)Standard Query (SELECT city)Deduplicated Query (SELECT DISTINCT city)
Row 1: MumbaiMumbaiMumbai
Row 2: MumbaiMumbaiMumbai (Removed Duplicate)
Row 3: DelhiDelhiDelhi
Row 4: PunePunePune
Row 5: MumbaiMumbaiMumbai (Removed Duplicate)
Diagram 1: Single-Column Deduplication
Raw Output (SELECT city)
Mumbai
Mumbai
Delhi
Pune
Mumbai
➔ DISTINCT ➔
Unique Output (SELECT DISTINCT city)
Mumbai
Delhi
Pune
3

Basic DISTINCT Syntax

The syntax for DISTINCT is straightforward: place the keyword directly after SELECT:

SELECT DISTINCT column_name
FROM table_name;

Let us break down each part:

  • SELECT: The data extraction command.
  • DISTINCT: Instructs the engine to collapse identical output rows into a single unique row.
  • column_name: The column (or list of columns) to extract and evaluate.
  • FROM table_name: The database table being queried.
  • ;: Statement terminator.
4

DISTINCT With One Column

When you select a single column, DISTINCT checks each value individually:

SELECT DISTINCT city
FROM customers;

If the customers table contains 50,000 rows across 12 unique cities, this query returns exactly 12 rows.

5

DISTINCT With Multiple Columns (Tuple Uniqueness)

This is one of the most important concepts for SQL beginners: DISTINCT applies to all columns listed in the SELECT clause as a combined unit (tuple), not just the first column.

SELECT DISTINCT city, department
FROM employees;

In this query, SQL checks whether the combination of (city, department) has been seen before:

RowcitydepartmentCombined TupleResult Set Action
1MumbaiSales(Mumbai, Sales)Retained (1st time seen)
2MumbaiSales(Mumbai, Sales)Dropped (Duplicate tuple)
3MumbaiHR(Mumbai, HR)Retained (Different department!)
4DelhiSales(Delhi, Sales)Retained (Different city!)
💡
Key Takeaway: Mumbai + Sales and Mumbai + HR are considered distinct result rows because their department values differ, even though both share the same city.
Diagram 2: Multi-Column Tuple Evaluation
Raw (city, department)
Mumbai | Sales
Mumbai | Sales (Duplicate)
Mumbai | HR
Delhi | Sales
➔ DISTINCT ➔
Unique Combinations
Mumbai | Sales
Mumbai | HR
Delhi | Sales
6

DISTINCT vs Normal SELECT

Compare the execution outcomes directly:

FeatureSELECT city FROM customers;SELECT DISTINCT city FROM customers;
Output Row CountAlways equals total rows in tableEquals number of unique city values
Duplicate HandlingPreserves all repeating valuesEliminates all repeating values
Processing CostMinimal (direct streaming scan)Requires hashing/sorting buffer in memory
Primary Use CaseRetrieving raw transactional dataBuilding category lists, filters, audits
7

DISTINCT With NULL Values

In SQL, NULL represents missing or unknown data. In logical comparisons, NULL = NULL evaluates to UNKNOWN.

However, for the DISTINCT clause, all SQL engines (PostgreSQL, MySQL, SQLite, Oracle, SQL Server) treat multiple NULL values as identical duplicates of one another:

-- If 1,000 customers have NULL in referral_code
SELECT DISTINCT referral_code
FROM customers;

This query will return the unique referral codes plus exactly one single NULL row representing all missing values.

8

DISTINCT and Result Ordering (DISTINCT ≠ SORT)

A very widespread misconception among beginners is assuming that DISTINCT automatically sorts the results alphabetically or numerically.

⚠️
Official Database Standard: DISTINCT guarantees uniqueness, but it provides zero guarantee of row order. Modern database query optimizers often use hash-based aggregation to deduplicate data, which can return rows in arbitrary or unpredictable order.

If your application or report requires a specific order, you must explicitly add the ORDER BY clause:

-- Unordered unique list (Arbitrary engine order)
SELECT DISTINCT city
FROM customers;

-- Guaranteed alphabetical sorting (A to Z)
SELECT DISTINCT city
FROM customers
ORDER BY city ASC;
Live Interactive SQL DISTINCT Practice Lab
📦 Source Table with Live Deduplication Scan8 Scanned Records
idnamecitydepartmentDeduplication Status
1RahulMumbaiSales✓ Retained Unique
2PriyaDelhiHR✓ Retained Unique
3AmitMumbaiSales✗ Duplicate Dropped
4SnehaMumbaiHR✓ Retained Unique
5VikramDelhiHR✗ Duplicate Dropped
6AnanyaPuneEngineering✓ Retained Unique
7RohanMumbaiSales✗ Duplicate Dropped
8PoojaDelhiSales✓ Retained Unique
✍️ SQL Editor● Interactive Engine
DISTINCT ≠ SORT Toggle:
Test explicit ORDER BY sorting
📋 Output Result Set5 Unique Rows (3 Dropped)
citydepartment
MumbaiSales
DelhiHR
MumbaiHR
PuneEngineering
DelhiSales
9

DISTINCT With Expressions

DISTINCT is not limited to raw stored columns. It can operate on calculated expressions and string transformations:

-- Normalizing case variations to deduplicate clean cities
SELECT DISTINCT LOWER(city) AS clean_city
FROM customers;
10

When Should You Use DISTINCT?

✅ Ideal Use Cases:
  • Populating UI dropdown filter options (e.g., all active countries or product categories).
  • Auditing categorical values in data cleaning pipelines.
  • Finding unique combinations of roles, permissions, or branch locations.
❌ When DISTINCT is Unnecessary:
  • When querying unique primary keys (e.g., user_id).
  • When querying columns that already have a UNIQUE database constraint.
  • As a quick hack to hide duplicate rows caused by incorrect JOIN conditions.
11

Common DISTINCT Mistakes

1. Thinking DISTINCT modifies the original table

DISTINCT is strictly a query-time filter. It does not delete or alter any records stored on disk.

2. Thinking DISTINCT applies to only one column in a multi-column query

In SELECT DISTINCT a, b FROM table;, DISTINCT applies to the pair (a, b), never just column a alone.

3. Assuming DISTINCT automatically sorts output

DISTINCT guarantees uniqueness, not order. Always use ORDER BY if you need alphabetical or numerical sorting.

4. Selecting unnecessary primary keys alongside DISTINCT

SELECT DISTINCT id, department FROM employees; will return all rows because id is always unique per row.

🧠 Interactive Challenge: Predict The Result (1 of 3)
SELECT DISTINCT city FROM employees;
How many unique cities will be returned, and which ones?
12

Practical DISTINCT Exercises

Task GoalTarget TableRequired SQL SolutionConcept Tested
1. Find Unique CitiescustomersSELECT DISTINCT city FROM customers;Single-column deduplication
2. Find Unique DepartmentsemployeesSELECT DISTINCT department FROM employees;Categorical unique list
3. Find Unique Product CategoriesproductsSELECT DISTINCT category FROM products;Product catalog extraction
4. Unique City + Department CombinationsemployeesSELECT DISTINCT city, department FROM employees;Multi-column tuple evaluation
5. Sorted Unique Country ListsuppliersSELECT DISTINCT country FROM suppliers ORDER BY country ASC;DISTINCT paired with ORDER BY
13

DISTINCT Best Practices

  • Select Only What Needs Deduplication: Do not include unneeded columns (especially primary keys) in a DISTINCT query.
  • Pair With ORDER BY When Order Matters: Never rely on DISTINCT to sort rows alphabetically or numerically.
  • Inspect Root Causes Before Adding DISTINCT: If an unexpected duplicate row appears after joining tables, fix the JOIN condition rather than masking it with DISTINCT.
  • Be Mindful on Huge Tables: Deduplicating millions of records requires memory buffers for hashing. Indexing the selected columns can significantly accelerate DISTINCT queries.
14

What You Should Know Now

  • What DISTINCT Does: Eliminates duplicate result rows from output
  • Single-Column DISTINCT: Keeps unique values for one column
  • Multi-Column DISTINCT: Evaluates combined tuples across all columns
  • NULL Behavior: Treats multiple NULLs as identical duplicates
  • DISTINCT ≠ Sorting: Unordered by default; use ORDER BY if sorted
  • Read-Only Query: Never alters physical data stored in database

🎯 Knowledge Check Quiz: SQL DISTINCT

Test your understanding of tuple uniqueness, NULL handling, result predictions, and best practices.

1. What is the primary function of the SQL DISTINCT keyword?
2. Where is the DISTINCT keyword placed in a standard SQL query?
3. When you execute "SELECT DISTINCT city, department FROM employees;", how does SQL determine what counts as a duplicate?
4. How does SQL DISTINCT handle NULL values if multiple rows have NULL in the selected column?
5. Does the query "SELECT DISTINCT city FROM customers;" guarantee that the returned cities will be sorted alphabetically?
6. Predict the result: A table has 10 customer records: 4 from "London", 3 from "Paris", 3 from "Tokyo". What does "SELECT DISTINCT city FROM customers;" return?
7. Why does adding "id" (e.g. SELECT DISTINCT id, department FROM employees;) often surprise beginners by returning all rows?
8. Which of the following is considered a SQL anti-pattern regarding DISTINCT?