The pganalyze team demonstrates using the pg_query open-source library to programmatically rewrite SQL queries and fix inefficient Postgres query plans. The article walks through practical examples including adding expressions to ORDER BY clauses to prevent index misuse, and transforming multiple OR conditions into ANY expressions for better performance. By parsing queries into structured parse trees, modifying nodes, and regenerating valid SQL, pg_query enables safe, deterministic query transformations that would be difficult to achieve with regex or AI-based approaches.
Table of contents
Query rewrite 101Example #1 - Add +0 to ORDER BY to avoid index misuseExample #2 - Transform multiple OR clauses to ANYConclusionSort: