EVIKA.ACADEMY›SQL Tutorial
SQL Tutorial›SELECT DISTINCT

SQL SELECT DISTINCT

Chapter 4 of 40 · Estimated read time: 5 min

The SELECT DISTINCT statement returns only unique values in the result set — duplicate rows are removed. Use it when you want to see what distinct values exist in a column.

Syntax

SELECT DISTINCT column1, column2, ... FROM table_name;

Example 1 — Without vs With DISTINCT

-- Without DISTINCT
-- (shows all rows)
SELECT category
FROM products;
WITHOUT DISTINCT — 7 rows
category
Electronics
Electronics
Stationery
Stationery
Furniture
Furniture
Electronics
-- With DISTINCT
-- (unique values only)
SELECT DISTINCT category
FROM products;
WITH DISTINCT — 3 rows
category
Electronics
Stationery
Furniture

Example 2 — DISTINCT on Multiple Columns

When you use DISTINCT on multiple columns, it returns unique combinations of those columns:

SELECT DISTINCT customer_id, product_id
FROM orders;
OUTPUT ↓
customer_idproduct_id
C011
C025
C013
C036
C042
C027
C014
DISTINCT applies to the entire row, not just the first column. SELECT DISTINCT customer_id, product_id returns unique (customer_id, product_id) pairs — not unique customer_ids.

Example 3 — COUNT DISTINCT

Combine DISTINCT with COUNT to count unique values — one of the most common patterns in analytics:

-- How many unique categories do we have?
SELECT COUNT(DISTINCT category) AS category_count
FROM products;
-- Result: 3

-- How many unique customers placed an order?
SELECT COUNT(DISTINCT customer_id) AS active_customers
FROM orders;
-- Result: 4 (C05 never ordered)

-- How many unique products were ordered?
SELECT COUNT(DISTINCT product_id) AS products_ordered
FROM orders;
-- Result: 6

Example 4 — List All Cities Customers Are From

SELECT DISTINCT city
FROM customers
ORDER BY city;
OUTPUT ↓
city
Bengaluru
Delhi
Mumbai
Noida
✏️ Practice Exercises
1. Write a query to find all unique supplier_ids from the products table.
2. How many unique customers have placed orders? (Use COUNT DISTINCT)
3. Find all unique combinations of category and supplier_id in the products table.
Show Answers
-- 1.
SELECT DISTINCT supplier_id FROM products;

-- 2.
SELECT COUNT(DISTINCT customer_id) AS unique_customers FROM orders;

-- 3.
SELECT DISTINCT category, supplier_id FROM products ORDER BY category;