Count distinct values
Need to know the number of unique entries? You got it! Use COUNT(DISTINCT column_name)
. Say, we are dealing with a customers
database and need to know the count of unique customer_id
s:
Voila, you get the count of unique customer IDs.
Counting distincts with precision
Want to run a uniqueness check? That's where DISTINCT
becomes your best friend. To count distinct values across more than one column, you can combine them like so:
Grouping unique values
To get a clear visual of the distribution of unique values, good old GROUP BY
comes into play:
This gives us the unique counts of another_column
for each distinct value present in column
.
Up the performance game with subqueries
Who said sorting out distinct values has to be hard? Use subqueries for smoother operations:
This subquery first finds the distinct values, then the main query counts them, all in one go!
Present distinct counts
Exciting, isn't it? Now, by using SELECT count(column) AS count, column
, we can display distinct counts along with the values:
No assumptions, only clarity
When data schemas are cryptic or requirements aren't clear, don't guess. Then it's time to seek clarity, ensuring the SQL query aligns perfectly with the data.
Visual aid for clarity
Visual formats, such as a simple table, often provide more context:
Statistical measure alongside counting
Sometimes, you need more than just the count. Like an average
too:
This gives you the average of distinct values in the column, rounded to two decimal places.
Was this article helpful?