Learn SQL  /  Filtering & Sorting  /  DISTINCT

DISTINCT

DISTINCT removes duplicate rows from a result set, keeping only unique combinations of the selected columns.

DISTINCT on One Column

R Code
SELECT DISTINCT class
FROM students;
Output
class
A
B

DISTINCT Across Multiple Columns

DISTINCT applies to the whole row of selected columns together, not to each column separately.

R Code
SELECT DISTINCT class, age
FROM students;
Output
class | age
A     | 23
A     | 25
B     | 21
B     | 22
⚠ Common Mistake
SELECT DISTINCT class, age does not mean 'unique classes and unique ages separately' - it means 'unique class+age COMBINATIONS.' If two students share the same class and age, only one row of that pair appears.

Counting Unique Values

R Code
SELECT COUNT(DISTINCT class) AS num_classes
FROM students;
Output
num_classes
2

Advanced: DISTINCT vs GROUP BY

🚀 Advanced Example
DISTINCT class and GROUP BY class return the same rows here, but GROUP BY additionally lets you compute an aggregate per group in the same query - something DISTINCT alone cannot do.
R Code
-- DISTINCT: just the unique classes
SELECT DISTINCT class FROM students;

-- GROUP BY: unique classes PLUS a per-class count
SELECT class, COUNT(*) AS n
FROM students
GROUP BY class;
Output
class
A
B

class | n
A     | 2
B     | 2

Key Points

  • DISTINCT removes duplicate rows based on the FULL combination of selected columns.
  • COUNT(DISTINCT column) counts how many unique values a column has.
  • Use GROUP BY instead of DISTINCT whenever you also need a per-group aggregate.