Count Distinct in SQL
? COUNT DISTINCT in SQL
The COUNT(DISTINCT column) function counts the number of unique (distinct) non-NULL values in a column.
? Syntax
SELECT COUNT(DISTINCT column_name) FROM table_name;? Example
Consider a sales table with a column customer_id. To count how many unique customers made purchases:
SELECT COUNT(DISTINCT customer_id) AS unique_customersFROM sales;? Notes
Counts only distinct, non-null values.
If you use
COUNT(column_name)withoutDISTINCT, it counts all non-null values (including duplicates).You can also use
COUNT(DISTINCT col1, col2)in some databases to count unique combinations of columns (supported in MySQL, PostgreSQL 9.4+).
If you want, I can show you examples with multiple columns or in specific SQL dialects!