Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

SQL SELECT DISTINCT: Remove Duplicates From Query Results

Get unique values or combinations with SELECT DISTINCT, understand how it handles NULL, and check for joins that produce unexpected duplicates.

Table of Contents

SELECT DISTINCT returns one result row for each unique combination of selected values. It removes duplicates from the query result. The underlying table and its records stay intact.

Learn about the SELECT DISTINCT command in SQL Picture 1

Get unique values from one column or a combination

SELECT DISTINCT city
FROM customers
WHERE city IS NOT NULL
ORDER BY city;

This lists each reported city once. WHERE excludes missing values before duplicates are removed, and ORDER BY makes the result order explicit.

SELECT DISTINCT city, state
FROM customers
ORDER BY state, city;

Now the database compares the pair. Two customers in the same city and state yield one row, while Portland, Maine and Portland, Oregon remain separate. Adding a unique customer ID to the output would keep those customer rows distinct even if the other columns matched.

Learn about the SELECT DISTINCT command in SQL Picture 2

SELECT DISTINCT can return a list of unique values from a table.

How DISTINCT handles NULL and counting

In a one-column result, repeated NULL values collapse to one NULL unless you filter them out. COUNT(DISTINCT city) counts distinct non-null cities, while COUNT(*) counts result rows. If a report needs a count for each city, use GROUP BY city with an aggregate.

Check why duplicates appeared

If a join unexpectedly returns several rows per customer, check whether it matched multiple orders or joined on an incomplete key. DISTINCT can hide an incorrect join without repairing it. Decide what one result row should represent, then check sample rows and counts. For more practice, use the SQL retrieval lesson and the SQL lab on joins and totals.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.