-- the keys of a correlated `LIMIT 1` child that is an Index Only Scan (an EXISTS over the columns of the index), probed in the btree itself a batch at a time: the visibility map decides which entries ask the heap -- label: 3,000 keys over {rows} fact rows, `JOIN LATERAL (SELECT 1 FROM links l WHERE l.parent_id = e.foreign_id AND l.flag_a = false LIMIT 1) ON true` over a lookup table of 3 x {rows} rows with about 330 entries a key, btree on `(parent_id, flag_a)` -- ordered: yes --@ setup DO $do$ BEGIN IF to_regclass('pi_events') IS NULL THEN CREATE TABLE pi_events (id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, foreign_id int NOT NULL, kind text NOT NULL, deleted_at timestamptz, a_count int NOT NULL); INSERT INTO pi_events (foreign_id, kind, deleted_at, a_count) SELECT 1 + floor(power(random(), 1.7) * 3000)::int, 'k' || (g % 11), CASE WHEN random() < .03 THEN now() END, (random() * 100)::int FROM generate_series(1, {rows}) g ORDER BY random(); CREATE INDEX pi_events_col ON pi_events USING sift_col (id, foreign_id, kind, deleted_at, a_count) WITH (key_cut = foreign_id); CREATE TABLE pi_links (id bigserial PRIMARY KEY, parent_id int NOT NULL, flag_a boolean NOT NULL, label text NOT NULL); INSERT INTO pi_links (parent_id, flag_a, label) SELECT 1 + (g::bigint * 7919) % 3000, (g % 17) <> 0, 'lbl_' || (g % 500) FROM generate_series(1, {rows} * 3) g ORDER BY random(); CREATE INDEX pi_links_parent ON pi_links (parent_id, flag_a); END IF; END $do$; VACUUM (FREEZE, ANALYZE) pi_events, pi_links --@ pg SELECT e.kind, count(*) AS n FROM pi_events e JOIN LATERAL (SELECT 1 FROM pi_links l WHERE l.parent_id = e.foreign_id AND l.flag_a = false LIMIT 1) x ON true WHERE e.deleted_at IS NULL GROUP BY 1 ORDER BY 1