PostgreSQL 9.4 The table is created as follows:
CREATE TABLE foo ( id integer, date date, value numeric(14,3) );
I am optimizing the query using the window function ROW_NUMBER() and COALESCE . For the most efficient, I tend to use Index Only Scan in the following query:
SELECT id, c_val FROM ( SELECT id, COALESCE(value, 0) c_val, ROW_NUMBER() OVER(PARTITION BY id ORDER BY date DESC NULLS LAST) rn FROM foo) sbt WHERE sbt.rn = 1;
So, if I create an index as follows:
CREATE INDEX ON foo (id, date DESC NULLS LAST, value);
the scheduler decides to use Index Only Scan , but if I do it like this:
CREATE INDEX ON foo (id, date DESC NULLS LAST, COALESCE(value, 0));
the scheduler will only perform Index Scan .
Why? I am trying to avoid the cost of evaluating the COALESCE function during query execution. Why does this not work with Index Only Scan ?
source share