Postgresql – Counting using window function with partition over an empty table

partitioningpostgresqlwindow functions

If i have an empty table (created but without rows in it), and i would like to get the number 0 from the below query, how i could achieve that?

select count(*) over (partition by field_name) 
from my_empty_table

Right now the postgres doesn't emmit any results as the table is empty.

Best Answer

Your query outputs one row for each row in the table, so an empty table must result in an empty output. (COALESCE handles NULL values, but what you have is not a NULL value, but no value at all.)

You could add another query:

select count(*) over (partition by field_name) 
from my_empty_table

union all

select 0
from my_empty_table
where not exists (select * from my_empty_table);