Dynamic SQL — Complete Guide
Dynamic SQL — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of PostgreSQL Tutorial on Toolliyo Academy.
On this page
PostgreSQL Tutorial · Lesson 45 of 100
Dynamic SQL
SQL ✓ → Advanced
Advanced · 2 — Production · ~6 min · PostgreSQL — Functions & Automation
What is this?
Dynamic SQL builds and executes statement strings at runtime — EXECUTE in PL/pgSQL with format() and %I/%L for safe identifier and literal quoting.
Why should you care?
PostgresVerse admin tool sorts any whitelisted column without writing 50 static queries — dynamic ORDER BY with validation.
See it live — copy this example
Run in pgAdmin or psql.
CREATE OR REPLACE FUNCTION list_products(sort_col text, lim int)
RETURNS SETOF products
LANGUAGE plpgsql
AS $$
BEGIN
IF sort_col NOT IN ('price','name','rating') THEN
RAISE EXCEPTION 'invalid sort column';
END IF;
RETURN QUERY EXECUTE format(
'SELECT * FROM products ORDER BY %I NULLS LAST LIMIT %s',
sort_col, lim
);
END;
$$;
SELECT * FROM list_products('price', 5);
What happened?
- format %I quotes identifier safely.
- Whitelist blocks SQL injection via sort_col.
- EXECUTE runs generated SELECT returning product rows.
Practice next
- Create function and call with price and name.
- Try invalid sort_col and read exception.
- Log generated SQL with RAISE NOTICE in dev.
- Add USING clause with bound parameter: EXECUTE ... USING cust_id.
- Build pivot report over whitelisted metric columns.
Remember
EXECUTE runs string SQL inside plpgsql. format %I for columns/tables; %L for literals. Whitelist dynamic parts.
PostgresVerse admin grid
Internal ops UI passes sort column; function validates and runs one query plan family.
Outcome: Feature ships without ORM supporting every sort permutation.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!