Ira SQL ProIra SQL Pro

SQL DISTINCT Keyword

beginnerbasics
2 min read

What is DISTINCT?

The DISTINCT keyword removes duplicate rows from the result set. When you need a list of unique values, DISTINCT is the simplest approach.

Syntax

SELECT DISTINCT column1, column2
FROM table_name;

PostgreSQL also supports DISTINCT ON:

SELECT DISTINCT ON (column1) column1, column2
FROM table_name
ORDER BY column1, column2;

When to Use

  • Getting a unique list of categories, departments, or statuses
  • Removing accidental duplicate rows
  • Counting unique values with COUNT(DISTINCT column)

Key Points

  1. Applies to Entire RowDISTINCT considers all selected columns. Two rows must match on every column to be considered duplicates.
  2. DISTINCT ON — A PostgreSQL extension that returns the first row for each unique value in the specified column(s). Requires ORDER BY.
  3. PerformanceDISTINCT requires sorting or hashing. On large tables it can be expensive.
  4. With AggregatesCOUNT(DISTINCT column) counts unique values in a column.
  5. NULL Treatment — Multiple NULLs are treated as duplicates and collapsed into one.

Guided Practice

Solve the challenge below. Use hints when stuck and check your answer for instant feedback.

Practice challengeGuided learning mode

SQL DISTINCT Keyword Challenge

Write a query that solve this task: get a list of all distinct grades assigned to students.

Expected result

A single column showing each unique grade value (e.g., A, B, C).

Hidden checks

  • Returned rows and values
  • Output columns and result shape
  • Final database state after the query runs

Lesson guidance

What is DISTINCT?

Initializing database...Each run starts from fresh sample data.

More Examples

Count distinct departments

Count how many unique departments exist in the employees table.

Initializing database...Each run starts from fresh sample data.

Frequently Asked Questions

What is the difference between DISTINCT and GROUP BY?
DISTINCT removes duplicate rows from the result. GROUP BY groups rows so you can apply aggregate functions. When used without aggregates, they produce similar results, but GROUP BY is more flexible.
Does DISTINCT affect performance?
Yes. DISTINCT requires the database to sort or hash the result to remove duplicates, which adds processing time on large result sets.

Related Topics