Skip to main content

COUNT_DISTINCT

Aggregate function.

The count(distinct ...) function calculates the uniq value of a set of values.

To obtain an estimated result from large data sets with little memory and time, consider using APPROX_COUNT_DISTINCT.

caution

NULL values are not counted.

Syntax

COUNT(distinct <expr> ...)
UNIQ(<expr>)

Arguments

ArgumentsDescription
<expr>Any expression, size of the arguments is [1, 32]

Return Type

UInt64

Example

Create a Table and Insert Sample Data

CREATE TABLE products (
id INT,
name VARCHAR,
category VARCHAR,
price FLOAT
);

INSERT INTO products (id, name, category, price)
VALUES (1, 'Laptop', 'Electronics', 1000),
(2, 'Smartphone', 'Electronics', 800),
(3, 'Tablet', 'Electronics', 600),
(4, 'Chair', 'Furniture', 150),
(5, 'Table', 'Furniture', 300);

Query Demo: Count Distinct Categories

SELECT COUNT(DISTINCT category) AS unique_categories
FROM products;

Result

| unique_categories |
|-------------------|
| 2 |
Did this page help you?
Yes
No
Explore Databend Cloud for FREE
Low-cost
Fast Analytics
Easy Data Ingestion
Elastic Scaling
Try it today