SELECT DISTINCT

Updated · 9 min read
easyPostgreSQL 18sqlselectdistinctduplicates

SELECT DISTINCT removes duplicate rows from a result. Ask for the cities where students live and you get one row per student, so San Francisco appears twice. Add DISTINCT and each city appears once. The key idea is what counts as a duplicate: two result rows that are equal in every column you selected.

In One Minute

  • SELECT DISTINCT returns each different row of the result once.
  • A duplicate means equal in all the selected columns, not just one of them.
  • For removing duplicates, NULL values count as the same, so a missing value appears once.
  • count(*) counts rows, count(column) counts non-NULL values, and count(DISTINCT column) counts different non-NULL values.
  • DISTINCT doesn't sort: add ORDER BY if the order matters.
  • DISTINCT changes the result, never the table.

The Basics

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

DISTINCT goes right after SELECT and applies to the whole row of the result. It doesn't sort anything: the database may return the different rows in any order, so add an ORDER BY whenever the order matters, as every example here does. Here is the problem it solves. Each student has a city, and two of them live in San Francisco:

SQL▶ Try it
SELECT city, state
FROM students
ORDER BY city;
Output
     city      | state
---------------+-------
 Dallas        | TX
 San Francisco | CA
 San Francisco | CA
(3 rows)

With DISTINCT, each different city-and-state pair appears once:

SQL▶ Try it
SELECT DISTINCT city, state
FROM students
ORDER BY city;
Output
     city      | state
---------------+-------
 Dallas        | TX
 San Francisco | CA
(2 rows)
Duplicate rows are removed; each different row stays once

DISTINCT on Several Columns

With several columns, a row is a duplicate only if all of them match. The Fee Tracker teaches four technologies:

SQL▶ Try it
SELECT DISTINCT technology
FROM courses
ORDER BY technology;
Output
 technology
------------
 Git
 Java
 JavaScript
 SQL
(4 rows)

Add level and Java appears twice, because Java has both Beginner and Intermediate courses. The pairs (Java, Beginner) and (Java, Intermediate) are different rows:

SQL▶ Try it
SELECT DISTINCT technology, level
FROM courses
ORDER BY technology, level;
Output
 technology |    level
------------+--------------
 Git        | Beginner
 Java       | Beginner
 Java       | Intermediate
 JavaScript | Beginner
 SQL        | Beginner
(5 rows)
A duplicate must match in every selected column

DISTINCT and NULL

For removing duplicates, PostgreSQL treats NULL values as not distinct from one another, so they appear once. Payment 5 has no method recorded:

SQL▶ Try it
SELECT DISTINCT method
FROM payments
ORDER BY method;
Output
 method
--------
 card
 check
 NULL
(3 rows)
Equal values go in one bucket, and all NULL values share one; DISTINCT keeps one per bucket

Three different values: card, check, and one NULL for the missing method. That's different from comparisons, where NULL = NULL is unknown, as you saw in Basic Data Types; for removing duplicates, SQL groups the missing values together.

With several columns, a NULL doesn't make rows duplicates on its own. Every selected column still has to match. Advitha and Navika both have no email, but they live in different states, so both rows stay:

SQL▶ Try it
SELECT DISTINCT state, email
FROM students
ORDER BY state, email;
Output
 state |             email
-------+--------------------------------
 CA    | srihitha.anamaneni@example.com
 CA    | NULL
 TX    | NULL
(3 rows)

(CA, NULL) and (TX, NULL) share the NULL, but their states differ, so they're different rows.

Counting Distinct Values

count(DISTINCT column) counts how many different values a column has. Seven payments were made, but how many students made them?

SQL▶ Try it
SELECT count(student_id) AS payments, count(DISTINCT student_id) AS students_who_paid
FROM payments;
Output
 payments | students_who_paid
----------+-------------------
        7 |                 2
(1 row)

count(student_id) counts every payment row; count(DISTINCT student_id) counts each student once: Srihitha and Navika. (Advitha has made no payments.)

count comes in three forms, and NULL is what tells them apart. Here they are side by side on method, which is missing for payment 5:

SQL▶ Try it
SELECT count(*) AS payment_rows, count(method) AS with_method, count(DISTINCT method) AS different_methods
FROM payments;
Output
 payment_rows | with_method | different_methods
--------------+-------------+-------------------
            7 |           6 |                 2
(1 row)
FormCountsHere
count(*)Every row7 payments
count(method)Rows where method isn't NULL6: payment 5 is left out
count(DISTINCT method)Different non-NULL values2: card and check

You'll meet count() and the other summary functions properly in Aggregate Functions.

count(*) counts rows; count(column) skips NULL; count(DISTINCT) counts different values

DISTINCT ON: One Row per Group

PostgreSQL has an extra form, DISTINCT ON, that keeps the first row for each value of a column, according to the ORDER BY. It's PostgreSQL only, and optional for now; later lessons show the standard way with window functions. Here it finds each student's most recent payment:

SQL▶ Try it
SELECT DISTINCT ON (student_id) student_id, payment_id, paid_on
FROM payments
ORDER BY student_id, paid_on DESC;
Output
 student_id | payment_id |  paid_on
------------+------------+------------
        101 |          5 | 2026-01-05
        103 |          7 | 2025-12-19
(2 rows)

The ORDER BY decides which row is "first" for each student: sorting by paid_on DESC puts the latest payment first, so that's the one kept.

The DISTINCT ON expressions must match the leftmost ORDER BY expressions. Here student_id comes first in both; the columns after it decide which row is kept within each group. Put another column first and PostgreSQL refuses:

SQL▶ Try it
SELECT DISTINCT ON (student_id) student_id, payment_id, paid_on
FROM payments
ORDER BY paid_on DESC, student_id;
Output
ERROR:  SELECT DISTINCT ON expressions must match initial ORDER BY expressions
Group by student, sort newest first, keep the first row of each group

Common Mistakes

Expecting DISTINCT to apply to one column. SELECT DISTINCT technology, title returns all six courses, because every title is different. DISTINCT looks at the whole row.

Using DISTINCT to hide a mistake. If a query returns unexpected duplicates, find out why before adding DISTINCT. Later, when you join tables, duplicates often mean the join is wrong.

Counting rows instead of values. count(student_id) counts payment rows (7). To count students, write count(DISTINCT student_id) (2).

Adding DISTINCT to every query "just in case". Removing duplicates makes PostgreSQL sort or hash the result rows, which is extra work on large results. Use DISTINCT when you actually need unique rows.

Practice

Challenge: Which payment methods have been recorded? List each method once, sorted alphabetically. Then count how many different courses have at least one payment, with count(DISTINCT ...).

Bonus: How many different technologies have courses, and how many different technology-and-level combinations exist? count(DISTINCT ...) takes one column, so for the combinations, count the rows of a SELECT DISTINCT written inside parentheses (a subquery, which gets its own lesson later).

Show solution
SQL▶ Try it
SELECT DISTINCT method
FROM payments
ORDER BY method;
 
SELECT count(DISTINCT course_id) AS courses_paid_for
FROM payments;
 
SELECT count(DISTINCT technology) AS technologies
FROM courses;
 
SELECT count(*) AS technology_level_combinations
FROM (
  SELECT DISTINCT technology, level
  FROM courses
) AS combinations;
Output
 method
--------
 card
 check
 NULL
(3 rows)
 
 courses_paid_for
------------------
                5
(1 row)
 
 technologies
--------------
            4
(1 row)
 
 technology_level_combinations
-------------------------------
                             5
(1 row)

Two methods are recorded (card and check), and payment 5 has none, so NULL appears once. Payments were made for five different courses: every course except Git Basics. There are 4 technologies but 5 technology-and-level combinations, because Java has two levels.

Quick check: SELECT DISTINCT

3 questions
1When are two result rows duplicates for DISTINCT?
2SELECT DISTINCT technology, level FROM courses; returns Java twice. Why?
3Seven payments were made by two students. What does count(DISTINCT student_id) return?

Key Takeaways

You want toWrite
Each different value onceSELECT DISTINCT city FROM students;
Each different pair onceSELECT DISTINCT technology, level FROM courses;
Count different valuesSELECT count(DISTINCT student_id) FROM payments;
First row per student (PostgreSQL only)SELECT DISTINCT ON (student_id) ... ORDER BY student_id, ...;

Was this tutorial helpful?

Lesson 11 of 115