sqlcmd.net validated sql reference
beginner aggregation MySQL MariaDB SQL Server PostgreSQL SQLite

Count Unique Values With COUNT DISTINCT

Count only the distinct values in a column, ignoring duplicates.

Docker-validated Not currently validation-green

Count how many distinct customers placed orders

There are 4 rows but only 3 distinct customers — Alice appears twice. COUNT(DISTINCT customer) returns 3. COUNT(*) on the same table would return 4.

Rows loaded before the example query runs.
Setup
CREATE TABLE orders (id INT, customer VARCHAR(50), status VARCHAR(20));

INSERT INTO
  orders (id, customer, status)
VALUES
  (1, 'Alice', 'shipped'),
  (2, 'Alice', 'pending'),
  (3, 'Bob', 'shipped'),
  (4, 'Carol', 'shipped');
Shared across supported engines.
SQL
SELECT
  COUNT(DISTINCT customer) AS unique_customers
FROM
  orders;
Returned rows for the shared example.
unique_customers
3

Output is identical across all engines.

Where this command helps.

  • counting how many unique values appear in a column
  • finding the number of distinct customers or categories in a result

What the command is doing.

COUNT(DISTINCT column) counts how many unique non-NULL values exist in a column, skipping duplicates. This is different from COUNT(*), which counts every row, and COUNT(column), which counts non-NULL rows but includes duplicates. It is commonly used to count unique customers, users, or categories in a dataset.