Sub topic 12
Dynamic SQL with EXECUTE and format()
This chapter assumes you can write a PL/pgSQL function with variables and SELECT INTO, and that you know the basics of SQL injection. You should also know how to read RAISE errors. Everything here builds on the way PL/pgSQL runs SQL statements.
Why dynamic SQL exists
Static SQL in PL/pgSQL is parsed once and its plan can be cached. That works because the statement's shape is fixed when you write the function. Variables can only stand in for values, such as a number in a WHERE clause. They cannot stand in for identifiers such as table names or column names.
This fails:
-- Does not work: a variable cannot be a table name
CREATE FUNCTION broken_count(p_table text)
RETURNS bigint
LANGUAGE plpgsql
AS $$
DECLARE
v_count bigint;
BEGIN
SELECT count(*) INTO v_count FROM p_table;
RETURN v_count;
END;
$$;PL/pgSQL looks for a table named p_table, not for the table whose name is in the variable. The fix is dynamic SQL: you build the statement as a string at run time and hand it to EXECUTE.
Use dynamic SQL when the structure of the statement changes: the table, the column, the sort order, or the set of conditions. Do not use it just to insert values. Values belong in parameters.
The EXECUTE statement
The general form is:
EXECUTE command_string [ INTO [STRICT] target ] [ USING expression [, ...] ];command_stringis any text expression that holds one SQL statement.INTOstores the first row of the result in a variable, record, or list of variables.USINGsupplies values for the placeholders$1,$2, and so on inside the string.
Three behaviors differ from static SQL:
- The string is parsed and planned each time
EXECUTEruns. There is no plan caching across calls, so dynamic statements cost more per call. - PL/pgSQL variables are not visible inside the string. The string is sent to the SQL engine as plain text. Only the
USINGvalues reach it. INTOwithoutSTRICTkeeps the first row and silently discards the rest. If no row comes back, the target becomesNULL. WithSTRICT, zero rows raiseNO_DATA_FOUNDand more than one row raisesTOO_MANY_ROWS.
Also, FOUND is not set by EXECUTE. To learn how many rows a dynamic INSERT, UPDATE, or DELETE affected, use GET DIAGNOSTICS:
GET DIAGNOSTICS v_rows = ROW_COUNT;Building the string safely with format()
You could build the string with || concatenation, but that is how injection bugs start. The format() function is the better tool. It works like sprintf in C: it takes a template with placeholders and a list of arguments.
The placeholders that matter here:
| Placeholder | Meaning | Use for |
|---|---|---|
| `%I` | Quote as an identifier, only if needed | Table, column, schema, function names |
| `%L` | Quote as a literal, and `NULL` becomes the word `NULL` | Values you cannot pass with `USING` |
| `%s` | Insert the text as is, with `NULL` becoming an empty string | Trusted fragments only |
| `%%` | A literal percent sign | Text containing `%` |
%I wraps a name in double quotes when it needs them, for example when it has uppercase letters, spaces, or is a reserved word. It also doubles any embedded double quote. An attacker cannot break out of the identifier by including a quote character.
You can also number the arguments, such as %1$I, which lets you reuse one argument several times in the template.
SELECT format('SELECT %I FROM %I', 'Order Total', 'sales data');
-- SELECT "Order Total" FROM "sales data"Identifiers with %I, values with USING
Here is the example from this tutorial's plan, a generic row counter:
CREATE FUNCTION count_where(p_table text, p_column text, p_value text)
RETURNS bigint
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
v_count bigint;
BEGIN
EXECUTE format('SELECT count(*) FROM %I WHERE %I = $1', p_table, p_column)
INTO v_count
USING p_value;
RETURN v_count;
END;
$$;Walk through what happens when you call count_where('orders', 'status', 'shipped'):
format()fills the two%Iplaceholders and producesSELECT count(*) FROM orders WHERE status = $1.EXECUTEsends that text to the SQL engine. The$1is still a placeholder.USING p_valuebinds the value'shipped'to$1as data. It is never parsed as SQL.INTO v_countstores the single result row.
Even if p_value were 'x'' OR ''1''=''1', the engine would compare the column against that exact string. No injection is possible through the value.
One limit to know: $1 has the type of the USING expression, here text. If status were an integer column, the comparison integer = text would fail with an operator error. Cast inside the string, for example $1::integer, or pass an argument of the right type.
When to use %L instead of USING
USING is the default for values. A few situations need %L:
- The value must appear in a part of the statement that does not accept parameters. Utility commands such as
CREATE TABLE ... DEFAULT 'x',COMMENT ON, orALTER ROLE ... PASSWORDare examples. Parameters only work inSELECT,INSERT,UPDATE,DELETE, andMERGE-style statements. - You are building a string once and running it many times with different structures.
Example with a utility command:
CREATE FUNCTION set_table_comment(p_table text, p_comment text)
RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
EXECUTE format('COMMENT ON TABLE %I IS %L', p_table, p_comment);
END;
$$;%L produces a correctly escaped literal such as 'it''s fine'. If p_comment is NULL, you get the bare word NULL, which is valid here.
Avoid %s for anything that came from outside the function. It performs no quoting at all. It is acceptable for fragments you build yourself, for example a fixed ASC or DESC chosen from your own CASE expression.
Allowlisting for things you cannot quote
Some parts of a statement are keywords, not identifiers or values. A sort direction is the usual case. %I would turn DESC into "DESC", which is invalid. Check the input against a short list instead:
CREATE FUNCTION newest_orders(p_direction text DEFAULT 'desc', p_limit integer DEFAULT 10)
RETURNS TABLE (order_id integer, created_at timestamptz)
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
v_dir text;
BEGIN
v_dir := CASE lower(p_direction)
WHEN 'asc' THEN 'ASC'
WHEN 'desc' THEN 'DESC'
ELSE NULL
END;
IF v_dir IS NULL THEN
RAISE EXCEPTION 'invalid direction: %', p_direction
USING ERRCODE = 'invalid_parameter_value';
END IF;
RETURN QUERY EXECUTE
format('SELECT id, created_at FROM orders ORDER BY created_at %s LIMIT $1', v_dir)
USING p_limit;
END;
$$;Here %s is safe because v_dir can only be one of two constants. The limit still goes through USING. The function uses RETURN QUERY EXECUTE, the dynamic form of RETURN QUERY, which returns the rows of a dynamic query as a set.
Dynamic statements that change data
EXECUTE runs any single statement, including DDL. A common use is creating objects with computed names. Use GET DIAGNOSTICS to count the rows:
CREATE FUNCTION purge_status(p_table text, p_status text)
RETURNS bigint
LANGUAGE plpgsql
AS $$
DECLARE
v_rows bigint;
BEGIN
EXECUTE format('DELETE FROM %I WHERE status = $1', p_table)
USING p_status;
GET DIAGNOSTICS v_rows = ROW_COUNT;
RETURN v_rows;
END;
$$;Because p_table is a plain text argument, a caller can pass the name of any table the function owner can touch. If you want to limit it, check the name against a list or against pg_catalog before building the statement. Also see the next point about schemas.
Schema-qualified names
%I treats its argument as one identifier. If you pass 'public.orders', it produces "public.orders", a single table name with a dot in it, and the statement fails. There are two ways to handle schema-qualified names:
- Take the schema and table as two arguments and use
%I.%I. - Take a single argument of type
regclassand format it with%s. Aregclassvalue converts to text with proper quoting and schema qualification when needed.
SELECT format('SELECT count(*) FROM %s', 'public.orders'::regclass);The cast also checks that the table exists, and it raises an error if it does not.
Dynamic SQL in loops
FOR ... IN EXECUTE loops over the rows of a dynamic query, just as FOR ... IN SELECT does for a static one:
CREATE FUNCTION column_max(p_table regclass, p_column text)
RETURNS numeric
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
r record;
v_max numeric;
BEGIN
FOR r IN EXECUTE format('SELECT %I AS v FROM %s', p_column, p_table)
LOOP
IF v_max IS NULL OR r.v > v_max THEN
v_max := r.v;
END IF;
END LOOP;
RETURN v_max;
END;
$$;This works, but SELECT max(%I) FROM %s is a single statement and much faster. A loop is only worth it when you need per-row logic that SQL cannot express.
Common errors
- Using a PL/pgSQL variable inside the string. Writing
'... WHERE id = p_id'inside the quoted text raises "column p_id does not exist". Pass the variable throughUSING. - Concatenating values.
'... = ''' || p_value || ''''breaks on a quote character and allows injection. UseUSINGor%L. - Using
%sfor a name. It skips quoting. A mixed-case or reserved-word name then fails, and a hostile name can inject. - Expecting
FOUNDto be set.EXECUTEdoes not update it. UseGET DIAGNOSTICS ... ROW_COUNT. - Passing
NULLto%I.format()raises an error because an identifier cannot be null. Validate the argument first. - Running several statements in one string.
EXECUTEwithUSINGaccepts one statement only. Use oneEXECUTEper statement. - Placeholder count mismatch. The
$nnumbers must match theUSINGlist, and unused numbers still need a value in the list.
Performance notes
Each EXECUTE is planned from scratch. For one call in a batch job, that is negligible. In a hot path called thousands of times per second, it adds up, and the plan cannot benefit from a prepared-statement cache. Alternatives:
- Write static SQL when only values change.
- Write a few static variants and choose among them with
IF, when the number of shapes is small. - Keep dynamic SQL for administrative and generic helper code.
Dynamic code is also harder to test. Errors show up at run time, not when you run CREATE FUNCTION. Cover each branch of the statement-building logic with a test call, and print the built string with RAISE NOTICE '%', v_sql; while you develop. Building the string in a variable first makes this easy:
DO $$
DECLARE
v_sql text;
BEGIN
v_sql := format('SELECT count(*) FROM %I WHERE %I = $1', 'orders', 'status');
RAISE NOTICE '%', v_sql;
END;
$$;Exercise
A function receives ptable (text) and pmin (numeric) and must return the number of rows in that table whose column "amount" is greater than p_min. Which parts of the statement should use %I, and which should use USING? Write the EXECUTE statement.
Show answer
The table name is an identifier, so it goes through %I. The threshold is a value, so it goes through USING as $1. For example: EXECUTE format('SELECT count(*) FROM %I WHERE amount > $1', ptable) INTO vcount USING p_min; The column name "amount" is fixed, so it can be written directly in the template.
Exercise
A colleague writes EXECUTE 'DELETE FROM orders WHERE id = ' || p_id; and then checks IF FOUND THEN ... to see whether a row was deleted. Name two problems and give the fix for each.
Show answer
First, the value is concatenated into the string. Pass it with USING: EXECUTE 'DELETE FROM orders WHERE id = $1' USING pid; Second, EXECUTE does not set FOUND, so the check never reflects the dynamic statement. Use GET DIAGNOSTICS vrows = ROWCOUNT; and test vrows > 0.
Exercise
Why does format('SELECT * FROM %I', 'public.orders') fail, and what are two ways to fix it?
Show answer
%I treats the whole argument as one identifier and produces "public.orders", a table with a dot in its name, which does not exist. Fix it by passing schema and table separately and using %I.%I, or by passing a regclass value and formatting it with %s.