sql count unique

Galaxy Glossary

How do you count unique values in a SQL table?

The `COUNT(DISTINCT column)` function in SQL is used to count the unique values within a specified column. It's crucial for getting a precise count of distinct items, avoiding duplicates. This is essential for tasks like finding the number of unique customers or products.
Sign up for the latest in SQL knowledge from the Galaxy Team!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Description

The `COUNT(DISTINCT column)` function in SQL is a powerful tool for counting unique values in a specific column of a table. Unlike the standard `COUNT()` function, which counts all rows, `COUNT(DISTINCT column)` only counts each unique value once. This is particularly useful when you need to know the number of distinct items, such as the number of unique product names, customer IDs, or order numbers. It's a fundamental aggregate function used in various database queries. For example, in an e-commerce database, you might want to know the total number of unique products sold. Using `COUNT(DISTINCT product_name)` would give you that precise count. This function is also crucial for data analysis, reporting, and business intelligence tasks. It helps in understanding the variety and breadth of data within a dataset.

Why sql count unique is important

The `COUNT(DISTINCT)` function is vital for accurate data analysis. It allows for precise counts of unique items, which is essential for understanding the variety and breadth of data. This is crucial for reporting, business intelligence, and decision-making.

Example Usage

```sql -- Sample table: Orders CREATE TABLE Orders ( order_id INT PRIMARY KEY, customer_id INT, product_name VARCHAR(50) ); INSERT INTO Orders (order_id, customer_id, product_name) VALUES (1, 101, 'Laptop'), (2, 102, 'Mouse'), (3, 101, 'Keyboard'), (4, 103, 'Laptop'), (5, 101, 'Monitor'); -- Count unique product names SELECT COUNT(DISTINCT product_name) AS unique_products FROM Orders; ```

Common Mistakes

Want to learn about other SQL terms?