SELECT DISTINCT

SQL FundamentalsDMLFree Lesson

Advertisement

SELECT DISTINCT

The SELECT DISTINCT statement returns only different (unique) values.

💡 DISTINCT removes duplicate rows from your results, giving you only unique values.

Basic Syntax

SELECT DISTINCT column1, column2
FROM table_name;

Simple Example

Without DISTINCT:

SELECT city FROM customers;
city
New York
Los Angeles
Chicago
New York

With DISTINCT:

SELECT DISTINCT city FROM customers;
city
New York
Los Angeles
Chicago

DISTINCT on Multiple Columns

SELECT DISTINCT city, state FROM customers;

Returns unique combinations of city AND state.

DISTINCT with COUNT

-- How many different cities?
SELECT COUNT(DISTINCT city) FROM customers;
COUNT(DISTINCT city)
8

DISTINCT vs GROUP BY

-- These produce the same result:
SELECT DISTINCT city FROM customers;
SELECT city FROM customers GROUP BY city;

-- But GROUP BY is more powerful:
SELECT city, COUNT(*) FROM customers GROUP BY city;

✏️ Exercise: Find all unique product categories from a 'products' table

See Solution


SELECT DISTINCT category FROM products;

✅ Key Takeaways

  1. DISTINCT removes duplicate rows from results
  2. Works on single columns or combinations of columns
  3. Can be used with COUNT to count unique values
  4. Treats NULL as a unique value
  5. GROUP BY is similar but more powerful for aggregation

Advertisement

Need Expert SQL Help?

Get personalized SQL training or database consulting.

Advertisement