Advanced Reporting
Dynamic SQL Basics
Senior Data Analyst
March 24, 2026
6 min read
The Scenario
The list of columns to pivot changes weekly. Hardcoding them is unsustainable. I needed to generate the SQL dynamically.
Dynamic SQL
In stored procedures (PL/pgSQL, T-SQL), you can build a string and execute it.
-- PostgreSQL example (conceptual)
DO $$
DECLARE
sql_query TEXT;
BEGIN
sql_query := 'SELECT * FROM orders WHERE status = ''shipped''';
EXECUTE sql_query;
END $$;
The Danger: SQL Injection
Never concatenate user input directly into dynamic SQL!
Pro Tip
Use parameterized queries whenever possible. Dynamic SQL should be a last resort.
*Day 84: Stored Procedures vs. Functions.*