-- NOT IN over a large btree table (neither side can be NULL) and a comma join to it, probed in the btree for each key the scan meets, with the rows of an all-visible page taken from the entries -- label: {rows} * 1.5 events of 3,000 parents, a links table of 5 * {rows} rows (about 333 per parent), `parent_id NOT IN (SELECT parent_id FROM links WHERE weight = 1 AND status = 0)` for the 60 parents of a range, btree on `(parent_id, status) INCLUDE (label, weight)` -- ordered: yes --@ setup DO $do$ BEGIN IF to_regclass('pn_events') IS NULL THEN CREATE TABLE pn_events (id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, foreign_id int NOT NULL, kind int NOT NULL, deleted_at timestamptz); INSERT INTO pn_events (foreign_id, kind) SELECT 1 + (random() * 2999)::int, g % 7 FROM generate_series(1, {rows} * 3 / 2) g; CREATE TABLE pn_links (id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, parent_id int NOT NULL, label text NOT NULL, status smallint NOT NULL, weight int NOT NULL); INSERT INTO pn_links (parent_id, label, status, weight) SELECT 1 + g % 3000, 'lbl_' || g / 3000 % 10, g / 3000 % 5, g % 4 FROM generate_series(1, {rows} * 5) g ORDER BY random(); CREATE INDEX pn_links_parent_status ON pn_links (parent_id, status) INCLUDE (label, weight); CREATE INDEX pn_events_col ON pn_events USING sift_col (id, foreign_id, kind, deleted_at) WITH (key_cut = foreign_id); END IF; END $do$; VACUUM (FREEZE, ANALYZE) pn_events, pn_links --@ pg SELECT e.kind, count(*) AS n FROM pn_events e WHERE e.foreign_id BETWEEN 100 AND 159 AND e.deleted_at IS NULL AND e.foreign_id NOT IN (SELECT l.parent_id FROM pn_links l WHERE l.weight = 1 AND l.status = 0 AND l.label = 'lbl_7') GROUP BY 1 ORDER BY 1