Teach nbtree to avoid evaluating row compare keys.
authorPeter Geoghegan <pg@bowt.ie>
Mon, 15 Sep 2025 20:56:49 +0000 (16:56 -0400)
committerPeter Geoghegan <pg@bowt.ie>
Mon, 15 Sep 2025 20:56:49 +0000 (16:56 -0400)
commit7d9cd2df5ffc2939ac84581c9463b8afc4ca4c41
tree6b4a8a9925b3541d4ed19aaacf815f8bb14e3dcf
parentce71993ae46930ddb1ff790807114384898b86a7
Teach nbtree to avoid evaluating row compare keys.

Add logic to _bt_set_startikey that determines whether row compare keys
are guaranteed to be satisfied by every tuple on a page that is about to
be read by _bt_readpage.  This works in essentially the same way as the
existing scalar inequality logic.  Testing has shown that the new logic
improves performance to about the same degree as the existing scalar
inequality logic (compared to the unoptimized case).  In other words,
the new logic makes many row compare scans significantly faster.

Note that the new row compare inequality logic is only effective when
the same individual row member is the deciding subkey for all tuples on
the page (obviously, all tuples have to satisfy the row compare, too).
This is what makes the new row compare logic very similar to the
existing logic for scalar inequalities.  Note, in particular, that this
makes it safe to ignore whether all row compare members are against
either ASC or DESC index attributes (i.e. it doesn't matter if
individual subkeys don't all use the same inequality strategy).

Also stop refusing to set pstate.startikey to an offset beyond any
nonrequired key (don't add logic that'll do that for an individual row
compare subkey, either).  We can fully rely on our firstchangingattnum
tests instead.  This will do the right thing when a page has a group of
tuples with NULLs in a lower-order attribute that makes the tuples fail
to satisfy a row compare key -- we won't incorrectly conclude that all
tuples must satisfy the row compare, just because firsttup and lasttup
happen to.  Our firstchangingattnum test prevents that from happening.
(Note that the original "avoid evaluating nbtree scan keys" mechanism
added by commit e0b1ee17 couldn't support row compares due to issues
with tuples that contain NULLs in a lower-order subkey's attribute.
That original mechanism relied on requiredness markings, which the
replacement _bt_set_startikey mechanism never really needed.)

Follow up to commit 8a510275, which added the _bt_set_startikey
optimization.  _bt_set_startikey is now feature complete; there's no
remaining kind of nbtree scan key that it still doesn't support.

Author: Peter Geoghegan <pg@bowt.ie>
Reviewed-By: Chao Li <li.evan.chao@gmail.com>
Discussion: https://postgr.es/m/CAH2-WznL6Z3H_GTQze9d8T_Ls=cYbnd-_9f-Jo7aYgTGRUD58g@mail.gmail.com
src/backend/access/nbtree/nbtutils.c