Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do count(distinct) for multiple columns

This does not work:

select count(distinct colA, colB) from mytable

I know I can simply solve this by making a double select.

select count(*) from (
    select distinct colA, colB from mytable
)

Is there anyway I can do this without having to do the sub-select?

like image 559
econmajorr Avatar asked Jun 25 '26 03:06

econmajorr


2 Answers

Subquery is standard solution which I recommend too. Concatenation-based solutions, except they are error-prone if dangerous character occurs, might be also worse in performance.

Note: in case you collected obscure solutions how to avoid subquery, window function usage is also possible here (Not to be used in production - your code reviewers won't praise you for it):

select distinct count(*) over ()
from my_table
group by colA, colB
like image 53
Tomáš Záluský Avatar answered Jun 26 '26 19:06

Tomáš Záluský


Just for fun, you can (ab)use window functions and limit clause. These are evaluated after grouping. So:

SELECT COUNT(*) OVER()
FROM t
GROUP BY col_a, col_b
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
like image 38
Salman A Avatar answered Jun 26 '26 19:06

Salman A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!