SQL: Structured Query LanguageSQL FundamentalsDistinct Values and Query Results

How do you return only unique values with DISTINCT?

Question 20 of 30 · Updated

On this page

Use SELECT DISTINCT followed by the column or columns whose unique combinations you want to retrieve. DISTINCT removes duplicate rows from the query result, not from the stored table. Selecting one column returns one row per distinct value. Selecting multiple columns returns one row per distinct combination of all the selected values.

1. SQL DISTINCT syntax#

SQL
SELECT DISTINCT column_name FROM table_name;

For example, a dashboard may need a list of cities where visits occurred rather than a separate entry for every visit. DISTINCT appears immediately after SELECT, before the output column list. The default behavior is SELECT ALL: repeated output rows are retained unless another query operation removes them.

SQL
SELECT DISTINCT column_a, column_b FROM table_name WHERE condition ORDER BY column_a, column_b;

WHERE restricts input rows, the SELECT list determines what values appear in the output, and DISTINCT removes duplicate combinations from that output. ORDER BY controls presentation; DISTINCT does not itself guarantee sorted results. This is a logical description, not a mandatory physical execution sequence.

2. Example dataset: website visits#

Consider seven visits, each with a unique identifier, a possibly unknown city and a channel. The examples use a common table expression (CTE) with VALUES so they can be run directly in PostgreSQL without creating a permanent table. Each example repeats the small dataset and can be executed independently.

visit_idcitychannel
1Bengaluruweb
2Bengaluruweb
3Bengalurumobile
4Mumbaiweb
5Mumbaiweb
6NULLmobile
7NULLmobile

Even though visit IDs are unique, several visits have the same city. Repeated city names are legitimate data: a visit is not the same thing as a city. The objective is to construct a result at the city level, not delete visits.

3. Return unique values from one column#

SQL
WITH visits(visit_id,city,channel) AS ( VALUES (1,'Bengaluru','web'), (2,'Bengaluru','web'), (3,'Bengaluru','mobile'), (4,'Mumbai','web'), (5,'Mumbai','web'), (6,NULL,'mobile'), (7,NULL,'mobile') ) SELECT DISTINCT city FROM visits ORDER BY city NULLS LAST;

Result:

| city | |---| | Bengaluru | | Mumbai | | NULL |

Without DISTINCT, selecting city would produce seven rows: three Bengaluru values, two Mumbai values and two NULLs. The query with DISTINCT returns three rows. The source dataset still contains seven visits. NULLS LAST is supported by PostgreSQL and explicitly places NULL after known values; other products may use different defaults or syntax.

Loading diagram…

The flow represents the result transformation conceptually. PostgreSQL's optimizer is free to implement it differently. The projection does not require the database to materialize every intermediate list.

4. DISTINCT across multiple columns#

SQL
WITH visits(visit_id,city,channel) AS ( VALUES (1,'Bengaluru','web'), (2,'Bengaluru','web'), (3,'Bengaluru','mobile'), (4,'Mumbai','web'), (5,'Mumbai','web'), (6,NULL,'mobile'), (7,NULL,'mobile') ) SELECT DISTINCT city,channel FROM visits ORDER BY city NULLS LAST,channel;

Result:

citychannel
Bengalurumobile
Bengaluruweb
Mumbaiweb
NULLmobile

Bengaluru appears twice because its two channels differ. The duplicate pair Bengaluru/web is collapsed, as is Mumbai/web. DISTINCT applies to the entire selected row, not the first column alone. Writing SELECT DISTINCT(city), channel does not mean that city alone must be unique; parentheses around city are expression grouping in ordinary SQL.

If you include a unique identifier, every selected row can remain distinct:

SQL
WITH visits(visit_id,city,channel) AS ( VALUES (1,'Bengaluru','web'), (2,'Bengaluru','web'), (3,'Bengaluru','mobile'), (4,'Mumbai','web'), (5,'Mumbai','web'), (6,NULL,'mobile'), (7,NULL,'mobile') ) SELECT DISTINCT visit_id,city FROM visits ORDER BY visit_id;

The result contains seven rows, because visit_id differs for every row. This is why SELECT DISTINCT * often does not reduce the row count when a primary key is included. To build a list of cities, select city rather than every field in a visit.

5. Combine DISTINCT with a WHERE condition#

Suppose you want a dropdown of cities associated with web visits, not mobile visits. Use a filter:

SQL
WITH visits(visit_id,city,channel) AS ( VALUES (1,'Bengaluru','web'), (2,'Bengaluru','web'), (3,'Bengaluru','mobile'), (4,'Mumbai','web'), (5,'Mumbai','web'), (6,NULL,'mobile'), (7,NULL,'mobile') ) SELECT DISTINCT city FROM visits WHERE channel='web' ORDER BY city;

Result: Bengaluru and Mumbai. The four matching web visits are projected to city values, and repeated values are removed. If you want only known cities regardless of channel, use WHERE city IS NOT NULL. DISTINCT alone does not remove missing values.

6. What happens to NULL values?#

SQL uses three-valued logic for comparisons: NULL = NULL is unknown, not true. However, duplicate elimination treats NULL values as not distinct from one another when the other selected values also match. Consequently SELECT DISTINCT city returns at most one NULL row. For multiple selected columns, (NULL, 'web') and (NULL, 'mobile') would remain two distinct combinations.

This does not mean NULL represents a real city, an empty string or zero. Applications should decide whether unknown values belong in a result. A city dropdown might exclude NULL explicitly, while a data-quality report might retain an unknown category.

7. DISTINCT versus COUNT(DISTINCT ...)#

SQL
WITH visits(visit_id,city,channel) AS ( VALUES (1,'Bengaluru','web'), (2,'Bengaluru','web'), (3,'Bengaluru','mobile'), (4,'Mumbai','web'), (5,'Mumbai','web'), (6,NULL,'mobile'), (7,NULL,'mobile') ) SELECT COUNT(*) AS rows, COUNT(city) AS known, COUNT(DISTINCT city) AS known_unique, (SELECT COUNT(*) FROM ( SELECT DISTINCT city FROM visits ) AS d) AS distinct_rows FROM visits;
rowsknownknown_uniquedistinct_rows
7523

SELECT DISTINCT city returns unique values as rows, including one NULL in this dataset. COUNT(DISTINCT city) returns one number: the count of distinct non-NULL city values. COUNT(city) counts all non-NULL city values, even repeated ones. COUNT(*) counts rows regardless of whether city is NULL. Counting the rows of the distinct subquery includes the NULL category. This introductory contrast prevents a common counting mistake; detailed distinct-count aggregation is a separate curriculum lesson.

8. DISTINCT versus GROUP BY#

SQL
WITH visits(visit_id,city,channel) AS ( VALUES (1,'Bengaluru','web'), (2,'Bengaluru','web'), (3,'Bengaluru','mobile'), (4,'Mumbai','web'), (5,'Mumbai','web'), (6,NULL,'mobile'), (7,NULL,'mobile') ) SELECT city,COUNT(*) AS visits FROM visits GROUP BY city ORDER BY city NULLS LAST;
cityvisits
Bengaluru3
Mumbai2
NULL2

Use DISTINCT when you simply need unique result rows. Use GROUP BY when you need one row per group and want to calculate aggregates such as counts, sums or averages. GROUP BY city without an aggregate can also yield one row per city, but DISTINCT expresses duplicate elimination directly. Do not assume identical execution plans or universal performance superiority.

RequirementTypical SQL
List unique citiesSELECT DISTINCT city FROM visits
List unique city/channel pairsSELECT DISTINCT city, channel FROM visits
Count known unique citiesSELECT COUNT(DISTINCT city) FROM visits
Count visits per citySELECT city, COUNT(*) FROM visits GROUP BY city
Prevent invalid duplicate source recordsAppropriate UNIQUE constraint or key
Choose one representative source record per groupDeterministic selection, e.g. a window function

9. Expressions, case sensitivity and data quality#

Duplicate elimination operates on selected expressions using the data type and applicable comparison or collation rules. If the business deliberately wants case-insensitive city labels, one option is to select a normalized expression:

SQL
SELECT DISTINCT LOWER(city) AS city FROM (VALUES ('Mumbai'),('MUMBAI'),('mumbai')) AS v(city);

Result: one row with mumbai. This was tested on the connected PostgreSQL instance for these ASCII strings. LOWER is not a universal Unicode normalization or case-folding solution. Do not silently collapse identifiers, codes, spellings or values when case or other distinctions carry business meaning. Case, accents, trailing spaces, character types and collation can change what an engine considers equivalent. Choose normalization rules intentionally and test representative values.

10. DISTINCT does not repair duplicate records#

DISTINCT changes query results only. It cannot enforce uniqueness for future inserts, repair inconsistent data, merge records or remove persistent duplicates. A UNIQUE constraint enforces an appropriate business rule at the storage boundary; its treatment of NULL depends on the engine and configuration. In this example, city must not be unique because many visits legitimately occur in the same city.

If a join unexpectedly multiplies rows, first verify the intended relationship and join predicate. Adding DISTINCT may hide incorrect join cardinality while also discarding meaningful repeated results. If you need one complete row per group, ordinary DISTINCT on all selected columns does not choose which row to retain. Use a deterministic approach based on a business rule, such as latest event time with an ID tie-breaker. PostgreSQL's DISTINCT ON is a separate, PostgreSQL-specific feature with ordering requirements; it is not equivalent to ordinary SELECT DISTINCT and is not demonstrated here.

11. Performance and production considerations#

Duplicate elimination can require extra database work. Depending on the engine, data distribution, indexes and query plan, PostgreSQL may use sorting and a Unique operation, hashing, or another strategy. Wide DISTINCT results generally give the engine more values to compare or store than narrow results. In a large workload, sort or hash operations can use substantial memory or spill to disk. An index aligned with the query may help, but DISTINCT does not automatically imply index use, and it is not automatically slow.

Keep the output list limited to what the consumer needs. Apply logically appropriate filters and verify that joins return the intended grain. Use EXPLAIN to inspect a query plan; EXPLAIN ANALYZE actually executes a statement and should be used with appropriate workload safeguards. Supabase's Query Optimization documentation discusses aligning indexes with filters and joins. These are general planning considerations, not a benchmark or a claim that a particular index accelerates every DISTINCT query. No indexes were created and no performance measurement was attempted here.

12. Common mistakes#

  • Placing DISTINCT after a column name instead of immediately after SELECT.
  • Expecting SELECT DISTINCT city, channel to guarantee one row per city.
  • Adding a primary key to the SELECT list and expecting duplicate city values to disappear.
  • Assuming DISTINCT removes NULL entirely, or that COUNT(DISTINCT city) includes it.
  • Assuming the result is sorted without ORDER BY.
  • Treating a query result as a permanent cleanup of the source table.
  • Hiding an incorrect join behind DISTINCT instead of correcting the query.

13. Interview-ready answer#

Use SELECT DISTINCT column_name FROM table_name to return unique values of a column. DISTINCT eliminates duplicate rows from the result after the selected expressions are considered, so with multiple columns it returns unique combinations rather than unique values of each individual column. It does not modify the source table. NULL values can appear once in a distinct single-column result, whereas COUNT(DISTINCT column_name) ignores NULL. Add WHERE to filter input rows and ORDER BY for guaranteed ordering. Use GROUP BY for grouped aggregates and database constraints to enforce persistent uniqueness.

14. Quick interview checks#

Does DISTINCT remove duplicates from the table? No, it removes duplicate output rows only.

Can a DISTINCT query contain repeated values in one column? Yes, when other selected columns differ.

Does DISTINCT guarantee order? No. Use ORDER BY.

Is DISTINCT the same as UNIQUE? No. DISTINCT is query-result semantics; UNIQUE is a schema-level constraint.

**Why might SELECT DISTINCT * return every row?** A selected primary key can make every complete result row unique.

15. Validation and references#

Seven read-only PostgreSQL queries were executed on synthetic VALUES data: single-column DISTINCT, multi-column DISTINCT, WHERE filtering, distinct rows including a unique identifier, count comparison, GROUP BY, and normalized expression DISTINCT. All returned the results described above. No educational DDL, DML or application-data access was necessary. The Mermaid flowchart was structurally checked and stored in a literal fenced mermaid block; a Mermaid parser and live public-page rendering were unavailable. Live web research was unavailable under the established offline exception. The Supabase Query Optimization documentation was consulted through the documentation connector; PostgreSQL links below are authoritative reference destinations, not independently fetched during this session. No cross-engine benchmark was performed.

Related questions

Explore other topics:Forward Deployed EngineeringPythonAI System DesignMachine Learning