I have a query that I am trying to optimize for PostgreSQL 9.2:
select coalesce(max(id),0) as m from tbl
It takes for forever to run, so I figured I could rewrite it as
select id from tbl order by id desc limit 1
except it needs to return 0
if there are no rows in the table. I've tried a few combinations of case statements, but they don't seem to work. Any suggestions?
Plan for an empty table:
Aggregate (cost=11.25..11.26 rows=1 width=4)
-> Seq Scan on tbl (cost=0.00..11.00 rows=100 width=4)
The cost is 58k with a table with 1,190,000 rows, same execution plan though.