0Pricing
SQL Academy · Lesson

Counting Unique Values

COUNT(DISTINCT ...) in practice.

Why Count Unique Values?

When you use COUNT(*), you count every row — including duplicates. But sometimes you only want to know how many distinct values exist in a column.

For example: how many different countries do your customers come from? How many unique products were ordered last month? This is where COUNT(DISTINCT ...) comes in.

Setting Up a Sample Table

Let's create an orders table to practice with. Each order has a customer name, a product, and a country.

Notice that some customers and countries appear more than once — that's intentional, so we can see the difference between counting all rows and counting distinct values.

CREATE TABLE orders (
  id INT,
  customer VARCHAR(50),
  product VARCHAR(50),
  country VARCHAR(50)
);

INSERT INTO orders VALUES
  (1, 'Alice', 'Laptop', 'USA'),
  (2, 'Bob', 'Phone', 'UK'),
  (3, 'Alice', 'Tablet', 'USA'),
  (4, 'Carol', 'Laptop', 'Canada'),
  (5, 'Bob', 'Laptop', 'UK'),
  (6, 'Dave', 'Phone', 'USA'),
  (7, 'Carol', 'Phone', 'Canada'),
  (8, 'Eve', 'Tablet', 'Germany');

All lessons in this course

  1. SELECT DISTINCT Basics
  2. DISTINCT on Multiple Columns
  3. PostgreSQL DISTINCT ON
  4. Counting Unique Values
← Back to SQL Academy