DISTINCT: Keep Only Unique Values
Unique Values Only
In the archive's great hall, every sound has an echo. The same status appears in thousands of orders. The same category appears across hundreds of products. The same city shows up in many user profiles.
When you need the full stream of data, repeated values are perfectly normal.
For example, if you're looking at orders, the status paid may appear many times:
SELECT id, status
FROM orders;
Here are the first six rows of the result:
| id | status |
|---|---|
| 1 | paid |
| 2 | paid |
| 3 | cancelled |
| 4 | paid |
| 5 | paid |
| 6 | paid |
Each row represents a separate order. Repeated statuses are not an error. Several orders simply have the same status.
Sometimes, though, you need a short list instead of the full stream of orders:
Which statuses appear in this table?
In that case, you don't need every occurrence of paid and pending. You want to see each value once.
Use DISTINCT for that:
SELECT DISTINCT status
FROM orders;
Result:
| status |
|---|
| cancelled |
| paid |
| pending |
| refunded |
DISTINCT removes duplicate rows from the query result.
It does not change the data in the table.
It does not delete rows from the database.
It only removes duplicates from the result set.
QUERY: An echo in the archive isn't always noise. Sometimes it shows how often something happens. But when you need a list of values instead of repeated entries, use the silencer:
DISTINCT.

DISTINCT silences the archive's echo: thousands of repeated values collapse into a short list of unique values.Where DISTINCT Goes
DISTINCT goes immediately after SELECT:
SELECT DISTINCT status
FROM orders;
That position matters.
Not like this:
SELECT status DISTINCT
FROM orders;
And not like this:
SELECT status
FROM orders
DISTINCT;
The correct form is:
SELECT DISTINCT columns
FROM table_name;
For example, to get a list of product categories:
SELECT DISTINCT category
FROM products;
To get a list of user cities:
SELECT DISTINCT city
FROM users;
To get a list of order statuses:
SELECT DISTINCT status
FROM orders;
All of these queries express the same idea:
Show me which values occur, without duplicates.
DISTINCT compares rows using the full combination of selected columns, so each combination appears in the result exactly once.events log? Return all values of event_type, with each value shown only once.DISTINCT on One Column
The simplest case is selecting the unique values from one column.
Take the rows from products with id values from 5 through 10:
| id | name | category |
|---|---|---|
| 5 | Mechanical Keyboard | Electronics |
| 6 | SQL for Pros | Books |
| 7 | Clean Code | Books |
| 8 | Practical Algorithms | Books |
| 9 | Oversized Hoodie | Clothing |
| 10 | Basic T-Shirt | Clothing |
If you write a regular query:
SELECT category
FROM products
WHERE id BETWEEN 5 AND 10;
the result shows the category for each row:
| category |
|---|
| Electronics |
| Books |
| Books |
| Books |
| Clothing |
| Clothing |
If you want the categories without duplicates:
SELECT DISTINCT category
FROM products
WHERE id BETWEEN 5 AND 10;
you get:
| category |
|---|
| Books |
| Clothing |
| Electronics |
DISTINCT does not pick the “first product in each category.”
It does not group products for calculations.
It simply answers this question:
Which different values appear in this column?
DISTINCT on Multiple Columns
The main idea in this lesson is:
uniqueness is determined by the entire selected result row.
If you select one column, DISTINCT removes duplicates based on that column.
SELECT DISTINCT country
FROM users;
But if you select two columns:
SELECT DISTINCT country, city
FROM users;
then DISTINCT looks for unique pairs:
country + city
Here are the first six rows of the users table. The table contains 40 rows in total:
| id | country | city |
|---|---|---|
| 1 | United States | Tampa |
| 2 | United States | Dallas |
| 3 | Mexico | Cancun |
| 4 | United States | Seattle |
| 5 | United States | Denver |
| 6 | United States | Seattle |
Now run the query on the whole table. We'll add sorting so the rows appear in a predictable order each time:
SELECT DISTINCT country
FROM users
ORDER BY country;
This gives us three countries:
| country |
|---|
| Canada |
| Mexico |
| United States |
But this query:
gives us eight pairs:
| country | city |
|---|---|
| Canada | Halifax |
| Mexico | Cancun |
| United States | Dallas |
| United States | Denver |
| United States | Miami |
| United States | Phoenix |
| United States | Seattle |
| United States | Tampa |
Why?
SQL is now checking whether the whole country and city pair is unique, rather than looking only at country:
country + city
These rows:
United States + Miami
United States + Denver
are different to SQL even though their country values match. Identical “United States + Seattle” pairs, however, collapse into one row.
So DISTINCT does not mean “make the first column unique.” It means:
Remove duplicate result rows as a whole.
user_id 5 and 10? Return the user_id and status pairs from orders, showing each pair only once.How DISTINCT Treats NULL
NULL means a value is missing, but for DISTINCT, multiple rows containing NULL in the same column are treated as duplicates.
Imagine that some users in the users table do not have a city specified. In the course database, every user has a city, so the NULL values below are only for this example:
| id | full_name | city |
|---|---|---|
| 1 | Anna Smith | Miami |
| 2 | Ben Johnson | |
| 3 | Vera Brown | Denver |
| 4 | Glen Davis | NULL |
| 5 | Dana Wilson | Miami |
The query:
SELECT DISTINCT city
FROM users;
would return roughly this set:
| city |
|---|
| Miami |
| Denver |
| NULL |
The two rows with NULL do not appear separately. The list of cities contains a single NULL row.
This does not contradict what you learned about NULL in the previous lesson.
In a WHERE condition, comparing something with NULL using = produces UNKNOWN. DISTINCT solves a different problem: it removes duplicates from the completed result set. During , several missing values in the same column collapse into one row.
If you don't want NULL to appear in the list, add a filter:
SELECT DISTINCT city
FROM users
WHERE city IS NOT NULL
ORDER BY city;
Now the result contains only cities with actual values.
DISTINCT Does Not Sort the Result
DISTINCT removes duplicates, but it does not control the order of the rows.
For example:
SELECT DISTINCT status
FROM orders;
might return:
| status |
|---|
| cancelled |
| paid |
| pending |
| refunded |
In another situation, the rows might appear in a different order.
That's normal. SQL does not guarantee any “natural” row order unless you explicitly request sorting.
If you need a predictable list, add ORDER BY, as we did near the beginning of the lesson.
The query now expresses two separate instructions:
SELECT DISTINCT status
— remove duplicates;
ORDER BY status
— sort the result by status.
Do not assume that DISTINCT also puts rows in order. It removes duplicates; sorting is a separate operation.
DISTINCT vs. GROUP BY
For a simple list of values, these two queries can produce the same result:
SELECT DISTINCT category
FROM products;
and:
SELECT category
FROM products
GROUP BY category;
Both return a list of categories without duplicates.
But they express different ideas.
DISTINCT answers this question:
Which values exist?
GROUP BY answers this question:
How should I divide the rows into groups so I can calculate something for each group?
For example, if you only need a list of categories, DISTINCT is enough:
SELECT DISTINCT category
FROM products;
If you need to find out how many products are in each category, use GROUP BY:
SELECT category, COUNT(*) AS products_count
FROM products
GROUP BY category;
Result:
| category | products_count |
|---|---|
| Home | 4 |
| Books | 3 |
| Toys | 4 |
| Clothing | 4 |
| Electronics | 5 |
Here, GROUP BY is doing more than removing duplicates. It collects rows into groups so the function COUNT(*) can count the rows in each group.
A practical rule is:
If you need a list of distinct values, use DISTINCT.
SELECT DISTINCT category
FROM products;
If you need to calculate something for each group, use GROUP BY.
SELECT category, COUNT(*)
FROM products
GROUP BY category;
The Cost of Silence
DISTINCT may be a small keyword, but the database still has work to do when you use it.
To remove duplicates, the must determine which result rows are identical. That requires comparing rows. Depending on the query, the database may:
- sort the result and remove adjacent duplicates;
- build a of unique values;
- use a suitable existing index if it helps.
On a small table, the difference is usually hard to notice.
For example, if products contains only 20 rows, this query:
SELECT DISTINCT category
FROM products;
will run quickly.
But if a table contains millions of rows and you select many columns, can become a noticeable part of the query cost.
A query like this can be especially expensive:
SELECT DISTINCT *
FROM orders;
Here, the database has to compare entire rows across all selected columns. More rows and more columns mean more work.
So don't add DISTINCT “just in case.”
Before using it, ask:
Exactly which duplicates am I trying to remove, and why did they appear?
If your answer is:
I need a list of statuses.
Then DISTINCT makes sense.
SELECT DISTINCT status
FROM orders;
If your answer is:
I got some strange duplicates after joining tables, so I added DISTINCT.
That's a warning sign. The problem may be in the join logic rather than the result itself.
DISTINCT After JOIN: When It Hides a Problem
One risky pattern is adding DISTINCT to “fix” duplicates after a JOIN.
We haven't covered joins in detail yet, but this idea is worth remembering now.
Suppose you have users and orders.
One user can place many orders.
If you join users to orders, the user's data appears once for each matching order.
For example:
| user_id | full_name | order_id |
|---|---|---|
| 1 | Anna Smith | 101 |
| 1 | Anna Smith | 102 |
| 1 | Anna Smith | 103 |
| 2 | Ben Johnson | 104 |
If you only need the users, you might see Anna Smith three times.
Someone might handle this by writing:
SELECT DISTINCT users.id, users.full_name
FROM users
JOIN orders ON orders.user_id = users.id;
The result now looks “clean”:
| id | full_name |
|---|---|
| 1 | Anna Smith |
| 2 | Ben Johnson |
But DISTINCT has not explained why Anna Smith appeared three times. It has only collapsed identical rows after the join.
That can be completely valid if you deliberately want a list of users who have at least one order.
But if you added DISTINCT only because “there are duplicates without it for some reason,” that's a code smell.
Instead, understand what the data is doing:
- what kind of relationship exists between the tables: one-to-one or one-to-many;
- why one row on the left matches several rows on the right;
- whether you actually need a list of unique users;
- whether you need to count orders;
- whether you need one specific order;
- whether the join condition needs to change.
DISTINCT after a JOIN can be a valid tool, but it should not be a patch for a problem you don't understand.
QUERY: If the echo started after you opened the neighboring hall, don't rush to silence the whole archive. First check which door you opened.
PostgreSQL Bonus: DISTINCT ON
PostgreSQL has a special construct:
SELECT DISTINCT ON (expression) ...
It works differently from regular DISTINCT.
Regular DISTINCT removes result rows that are completely identical.
For example:
SELECT DISTINCT country, city
FROM users;
keeps one row for each country + city combination.
DISTINCT ON, however, says:
Keep only one row for each value of this expression.
For example, suppose you need one product from each category:
SELECT DISTINCT ON (category)
category, name, price
FROM products
ORDER BY category, price DESC;
You can read this query step by step:
- split the rows by
category; - within each category, sort products by price from highest to lowest;
- keep the first row from each category.
The result looks like this:
| category | name | price |
|---|---|---|
| Books | Practical Algorithms | $16.90 |
| Clothing | Running Shoes | $54.90 |
| Electronics | Smartwatch | $89.90 |
| Home | Coffee Maker | $42.90 |
| Toys | RC Car | $32.90 |
Here, DISTINCT ON (category) keeps one row per category, while ORDER BY category, price DESC determines which row comes first within each category.
Important:
DISTINCT ON is a PostgreSQL . It is not part of standard SQL and is unavailable in many other DBMSs.
At this level, you do not need to memorize it as a required tool. Focus on the difference:
DISTINCTkeeps unique result rows;- PostgreSQL's
DISTINCT ONkeeps the first row for each group defined by the specified expression.
Interview question
Interview question:
What does DISTINCT do in SELECT?
Strong answer:
DISTINCT removes duplicate rows from the query result. It does not change the data in the table or delete duplicates from the database itself. It only affects the result set. If you select multiple columns, uniqueness is determined by the full combination of selected columns.
Interview question:
What does SELECT DISTINCT country, city FROM users return?
Strong answer:
The query returns unique country + city pairs. It does not deduplicate countries and cities independently. If one country has several cities, that country appears several times in the result, once in each unique pair.
Interview question:
How is SELECT DISTINCT x FROM t different from SELECT x FROM t GROUP BY x?
Strong answer:
Without functions, the result is often the same: both queries return unique values of x. Their purposes are different, though. Use DISTINCT when you need a list of the values that occur. Use GROUP BY when you need to divide rows into groups and calculate something for each group, such as COUNT(*), SUM(...), or AVG(...).
Interview question:
Does DISTINCT guarantee the sort order of the result?
Strong answer:
No. DISTINCT removes duplicates, but it does not define row order. If you need a predictable order, use ORDER BY.
Interview question:
When can DISTINCT in a query be a sign of a mistake?
Strong answer:
A warning sign is DISTINCT added only to remove duplicates after a JOIN. Those duplicates often appear because a one-to-many join multiplies rows or because the join condition is wrong. In that situation, DISTINCT hides the symptom and makes the database do extra work. It is better to find out why the rows multiplied and fix the query logic.
DISTINCT do in SELECT?SELECT DISTINCT country, city FROM users?DISTINCT and ORDER BY is correct?QUERY: Use
DISTINCTwhen you're deliberately silencing an echo. If you don't know where the echo came from, find the source first.
- Cities with PropertiesEASY
- Authors Who Viewed Their Own ArticlesEASY
- Unique category-supplier pairsEASY
SELECT DISTINCT status FROM orders ORDER BY status;