Predicate pushdown and decorrelation
Overview
Predicate pushdown moves a filter closer to its source when legal; projection pushdown reduces needed columns. Decorrelation transforms some correlated subqueries into joins or related set-based operations. These transformations must preserve semantics, especially outer-join NULL extension, LIMIT, aggregates, volatile expressions and duplicate handling.
First example
SELECT c.id FROM opt_customer c WHERE EXISTS(SELECT 1 FROM opt_order o WHERE o.customer_id=c.id) ORDER BY c.id;Observed SQLite result (rows in JSON):
[ [ 1 ], [ 2 ], [ 3 ]]How it works
The EXISTS query returns customers 1, 2 and 3, excluding customer 4. Grouping the join by unique customer id yields the same result; a plain inner join repeats customers. This is a manual semantic rewrite, not proof of automatic decorrelation. An edge test observes the amount predicate being used for an indexed search within a DISTINCT subquery. A LIMIT boundary can prevent safe pushdown. Join elimination requires proof that removed joins do not affect the result; partition pruning similarly excludes partitions only when predicates justify it.
Practical example
SELECT c.id FROM opt_customer c JOIN opt_order o ON o.customer_id=c.id GROUP BY c.id ORDER BY c.id;Observed SQLite result (rows in JSON):
[ [ 1 ], [ 2 ], [ 3 ]]Practice and mistakes
Practice: find customers without orders using NOT EXISTS, then LEFT JOIN with WHERE o.id IS NULL. Hint: o.id cannot be NULL for real matches. Expect ID 4. Explain why filtering the right table in WHERE after a LEFT JOIN can change results.
PostgreSQL 17 example — NOT RUN
BEGIN;SET LOCAL statement_timeout='10s';SET LOCAL lock_timeout='2s';CREATE TEMP TABLE opt_customer(id INTEGER PRIMARY KEY, name TEXT NOT NULL);INSERT INTO opt_customer VALUES(1,'Ada'),(2,'Reza'),(3,'Sara'),(4,'Mina');CREATE TEMP TABLE opt_order(id INTEGER PRIMARY KEY,customer_id INTEGER NOT NULL REFERENCES opt_customer(id),amount INTEGER NOT NULL,status TEXT NOT NULL,region TEXT NOT NULL);WITH RECURSIVE n(i) AS (VALUES(1) UNION ALL SELECT i+1 FROM n WHERE i<100)INSERT INTO opt_order SELECT i,1+(i%3),10*i,CASE WHEN i<=10 THEN 'rare' ELSE 'common' END,CASE WHEN i<=10 THEN 'east' ELSE 'west' END FROM n;CREATE INDEX opt_amount ON opt_order(amount);CREATE INDEX opt_status ON opt_order(status);CREATE INDEX opt_region ON opt_order(region);CREATE INDEX opt_customer_idx ON opt_order(customer_id);CREATE TEMP TABLE opt_line(id INTEGER PRIMARY KEY,order_id INTEGER NOT NULL REFERENCES opt_order(id));INSERT INTO opt_line VALUES(1,1),(2,1),(3,2),(4,42);CREATE INDEX opt_line_order ON opt_line(order_id);ANALYZE opt_order;ANALYZE opt_customer;ANALYZE opt_line;
EXPLAIN (VERBOSE) SELECT c.id FROM opt_customer c WHERE EXISTS(SELECT 1 FROM opt_order o WHERE o.customer_id=c.id);EXPLAIN (VERBOSE) SELECT id FROM (SELECT DISTINCT id,amount FROM opt_order) x WHERE amount=420;ROLLBACK;Expected result, not executed: "Inspect possible semijoin and pushed filter, not guaranteed."