Course contentsShow
← Data Science
Lesson 873 of 2,14522. SQL FoundationsFree lesson

Understanding DISTINCT: Removing Duplicate Rows

Learn how DISTINCT eliminates duplicate rows from query results and when to use it for unique value analysis.

Understanding DISTINCT: Removing Duplicate Rows

What you'll learn: How to use the DISTINCT keyword to eliminate duplicate rows from your SQL query results and identify unique values in your data.

What is DISTINCT?

When querying databases, you'll often encounter duplicate rows—especially when selecting specific columns. The DISTINCT keyword tells SQL to return only unique rows, filtering out any exact duplicates from your result set.

Think of it like creating a guest list from multiple RSVPs: if someone responds twice with identical information, you only write their name once on the final list.

How DISTINCT Works

Place DISTINCT immediately after SELECT and before your column names:

SELECT DISTINCT column_name
FROM table_name;

SQL examines all returned rows and keeps only one copy of each unique combination of values. If you select multiple columns with DISTINCT, it looks at the entire row—all selected columns together must match for rows to be considered duplicates.

Single Column Example

SELECT DISTINCT country
FROM customers;

This returns each unique country value once, even if 50 customers live in the same country.

Multiple Columns Example

SELECT DISTINCT city, state
FROM customers;

This returns unique combinations of city and state. "Portland, Oregon" and "Portland, Maine" would both appear because the combination differs.

When to Use DISTINCT

  • Finding unique categories: What products do we sell? What departments exist?
  • Counting unique entities: How many different customers placed orders?
  • Data exploration: Understanding the range of values in a column
  • Removing redundancy: Cleaning up result sets with unwanted duplicates

Key Takeaway: DISTINCT removes duplicate rows from query results by keeping only unique values or combinations, making it essential for analyzing unique categories and cleaning redundant data.