Query rewriting
Overview
Rewriting transforms a query into a semantically equivalent representation. Examples include expanding views, folding constants and replacing suitable OR predicates with IN. Distinguish the PostgreSQL rule rewriter (including view expansion) from later planner transformations. A rewrite must preserve duplicates, NULL behavior and side effects, not merely look simpler.
First example
SELECT id FROM opt_order WHERE amount=30 OR amount=40 ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 3 ], [ 4 ]]How it works
The equality alternatives on the same column produce IDs 3 and 4; using IN produces the same ordered result. This verifies equivalence for the fixture, not the actual internal rewrite. SQLite may use its OR-to-IN optimization. Rewrites involving volatile expressions, outer joins or NOT IN require special care. NOT IN can become UNKNOWN when its list contains NULL.
Practical example
SELECT id FROM opt_order WHERE amount IN (30,40) ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 3 ], [ 4 ]]Practice and mistakes
Practice: rewrite amount=50 OR amount=60 using IN; expect IDs 5 and 6. Hint: keep the same column and values. Compare ordered results, then investigate NOT IN (50,NULL). Do not replace OR with UNION ALL blindly: overlapping predicates can duplicate rows.
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;
CREATE TEMP VIEW opt71_view AS SELECT id,amount FROM opt_order;EXPLAIN (VERBOSE) SELECT id FROM opt71_view WHERE amount=20+10;SELECT id FROM opt71_view WHERE amount=20+10;ROLLBACK;Expected result, not executed: "Inspect view expansion and constant simplification; ID 3."