← Back to PostgreSQL Course | Chapter 7: Aggregations & Grouping | Lesson 4 of 7

DISTINCT with aggregates

COUNT(DISTINCT col) and similar forms aggregate only unique values.

In this page:

  1. DISTINCT with aggregates
Syntax
sql
SELECT COUNT(DISTINCT column), SUM(DISTINCT column)
FROM table_name;

DISTINCT with aggregates

COUNT(DISTINCT city) counts unique cities, and SUM(DISTINCT x) adds each different value once.

In PostgreSQL you can also use aggregate functions like string_agg(DISTINCT name, ', ') and array_agg(DISTINCT x). DISTINCT inside aggregates is different from SELECT DISTINCT, which removes duplicate rows.

Note: COUNT(DISTINCT x) is a common way to count unique visitors.

Example: DISTINCT with aggregates

sql
CREATE TABLE visits (id INTEGER PRIMARY KEY, visitor TEXT, page TEXT);
INSERT INTO visits VALUES (1,'ada','home'),(2,'bob','home'),(3,'ada','pricing'),(4,'ada','home'),(5,'cy','pricing');
SELECT COUNT(*) AS hits, COUNT(DISTINCT visitor) AS unique_visitors FROM visits;
SELECT page, COUNT(*) AS hits, COUNT(DISTINCT visitor) AS unique_visitors FROM visits GROUP BY page ORDER BY page;

-- Output:
-- hits | unique_visitors
-- 5 | 3
-- page | hits | unique_visitors
-- home | 3 | 2
-- pricing | 2 | 2
Related Topics
Common Mistakes
  1. Confusing SELECT DISTINCT with COUNT(DISTINCT)
  2. Using DISTINCT to hide bad joins
  3. Forgetting DISTINCT costs a sort or hash
Chapter Summary
  • COUNT(DISTINCT x) counts unique values
  • SUM(DISTINCT x) adds unique values
  • Works inside grouped queries
  • Different from SELECT DISTINCT
🔒

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.