I have a large table (about 11,000,000 rows) and I need to find the first item given a sorting condition.
Note that column Date
does NOT accept nulls
Why isn't Postgres using the index:
CREATE INDEX track_ix_date
ON "Track"
USING btree
("Date" DESC NULLS LAST);
On this simple query:
select * from "Track" order by "Date" desc limit 1
But it does use it on this other query:
select * from "Track" order by "Date" desc nulls last limit 1
The second query is in fact much more faster that the first query.
I have read the indexes and ORDER BY documentation and says that in the special case of an ORDER BY
with a LIMIT
clause is much more efficient to use the index instead of scanning the table, because the sorting would need to scan the full table just to get a single item
Shouldn't Postgres detect that nulls last / first
doesn't matter since the column doesn't accept nulls and just use the fastest method?
NULLS LAST
at all if you know that yourDATE
column isNOT NULL
?DATE IS NOT NULL
so I put theNULLS LAST
by thinking that postgre was checking that condition because when ordering in descending order the first element was considered as a posible nullexplain (analyze, verbose)
. Formatted text please, no screen shots