I'd like to select an entity based on it's name and based on alphabetical order, select the name of the next row. The name column is a varchar, is unique and has an index.
Using the Lead window function this is what I've come up with:
SELECT *
FROM (
SELECT
*,
LEAD("name", 1, '') OVER(ORDER BY name) AS next
FROM entity
ORDER BY "name"
) results
WHERE "name" = 'CACTUS';
However the query performance degrades as the size of the entity table increases.
The query plan looks like:
Subquery Scan on results (cost=0.42..31205.95 rows=1 width=299)
Filter: ((results.""name"")::text = 'CACTUS'::text)"
-> WindowAgg (cost=0.42..29002.24 rows=176297 width=299)"
-> Index Scan using ""IDX_2fbbd02c0f1ee2a4dda593705d"" on entity (cost=0.42..26357.79 rows=176297 width=235)"
Is there a more efficient way of doing this?
postgresql version 11+
lead()without an order by doesn't really make sense to begin with - there is no such thing as "the next row" unless you specify anorder by. But yes it is expected that this gets slower the more rows you have, because the inner query has to sort all rows in the table