← Back to PostgreSQL Course | Chapter 2: Basic Queries | Lesson 7 of 7

DISTINCT

DISTINCT removes duplicate rows from a result.

In this page:

  1. DISTINCT
Syntax
sql
SELECT DISTINCT column1, column2
FROM table_name;

DISTINCT

SELECT DISTINCT col returns each unique value once, and DISTINCT over several columns returns unique combinations. PostgreSQL also has DISTINCT ON (col), which keeps the first row for each value according to ORDER BY.

DISTINCT can be expensive on large data, so use it deliberately.

Note: DISTINCT ON is a PostgreSQL extension for picking one row per group.

Example: DISTINCT

sql
CREATE TABLE visits (id INTEGER PRIMARY KEY, city TEXT, browser TEXT);
INSERT INTO visits VALUES (1,'Oslo','chrome'),(2,'Oslo','firefox'),(3,'Rome','chrome'),(4,'Oslo','chrome');
SELECT DISTINCT city FROM visits ORDER BY city;
SELECT DISTINCT city, browser FROM visits ORDER BY city, browser;
SELECT COUNT(DISTINCT city) AS cities FROM visits;

-- Output:
-- city
-- Oslo
-- Rome
-- city | browser
-- Oslo | chrome
-- Oslo | firefox
-- Rome | chrome
-- cities
-- 2
Related Topics
Common Mistakes
  1. Adding DISTINCT to hide a join mistake
  2. Expecting DISTINCT to apply to one column only
  3. Using it on huge unindexed data
Chapter Summary
  • DISTINCT returns unique rows
  • Applies to the whole selected row
  • DISTINCT ON is PostgreSQL-only
  • Use it deliberately
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.