Skip to content
Advertisement

Join a count query on generate_series() and retrieve Null values as ‘0’

I want to count ID’s per month using generate_series(). This query works in PostgreSQL 9.1:

This is my output:

But what I want to get is this output (‘0’ value in January):

Months without id should be listed nevertheless.
Any ideas how to solve this?

Sample data:

Advertisement

Answer

Untangled, simplified and fixed, it might look like this:

db<>fiddle here

Among all the noise, misleading identifiers and unconventional format the actual problem was hidden here:

You made correct use of RIGHT [OUTER] JOIN. But adding a WHERE clause that requires an existing row from mytable converts the RIGHT [OUTER] JOIN to an [INNER] JOIN effectively.

Move that filter into the JOIN condition to make it work.

I simplified some other things while being at it.

Better, yet

db<>fiddle here

It’s much cheaper to aggregate first and join later – joining one row per month instead of one row per day.

It’s cheaper to base GROUP BY and ORDER BY on the date value instead of the rendered text.

count(*) is a bit faster than count(id), while equivalent in this query.

generate_series() is a bit faster and safer when based on timestamp instead of date. See:

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