SQL

SELECT DISTINCT and Counting Uniques

admin by @admin ADMIN
Jun 12, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`DISTINCT` removes duplicate rows. Combine with `COUNT(DISTINCT col)` to count uniques in aggregations — different from `COUNT(*)`.
SQL
Raw
-- Unique country list
SELECT DISTINCT country FROM users ORDER BY country;

-- Unique combinations of two columns
SELECT DISTINCT country, state FROM users ORDER BY country, state;

-- Count unique values vs total rows
SELECT COUNT(*)             AS total_orders,
       COUNT(DISTINCT user_id) AS unique_customers,
       SUM(amount)          AS total_revenue
FROM   orders
WHERE  created_at >= '2025-01-01';

-- Distinct-on (PostgreSQL only) — first row per group, by ORDER BY
SELECT DISTINCT ON (user_id) user_id, created_at, status
FROM   orders
ORDER  BY user_id, created_at DESC;   -- → newest order per user
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.