Skip to content
Advertisement

How to get a COUNT() value when GROUP BY has no row?

RDMS : MariaDB 10.1.23

MCRE :

SQLFiddle: http://sqlfiddle.com/#!9/f32a01/1


Consider the following query :

Without the GROUP BY clause, I know that COUNT() will return 0 if no row match the query.

I also know that, if my GROUP BY “fails” (If i have no row to group by, in my example, if no row satisfy e.created_at > CURRENT_DATE - INTERVAL 1 DAY) then, COUNT() will not return anything (0 row). How can I make sure COUNT() returns 0 (1 row with the value 0) in that case ?

Advertisement

Answer

Grouping is done after where clause is evaluated; if the where clause eliminates all rows then there is nothing to group.

I am guessing that you want conditional aggregation. Here is an example:

And query to count all female employees by department:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement