Sub topic 12
Dynamic SQL with `EXECUTE` and `format()`
This chapter assumes you know basic SQL, PostgreSQL data types, PL/pgSQL functions, and parameterized queries. Dynamic SQL is SQL assembled while a function runs. Use it when the SQL structure must change, such as when a table or column name comes from a function argument.
Prefer ordinary SQL when the structure is fixed. PostgreSQL can often reuse a plan for ordinary statements. Dynamic SQL adds parsing work and creates more opportunities for mistakes.
When dynamic SQL is needed
SQL parameters can represent values, but they cannot represent identifiers. An identifier is a database object name, such as a table, column, or schema.
SELECT count(*)
FROM $1
WHERE $2 = $3;This does not treat $1 as a table name or $2 as a column name. PostgreSQL parameters work only where a value is expected.
Use EXECUTE when the statement text must be built at runtime:
| Dynamic part | Safe method | Example |
|---|---|---|
| Value | `USING` | `WHERE status = $1` |
| Identifier | `format('%I', name)` | `format('FROM %I', table_name)` |
| Fixed keyword choice | Allowlist | `ASC` or `DESC` after validation |
`format()` and `EXECUTE`
format() creates a string. EXECUTE runs that string. The %I placeholder safely quotes an identifier. For example, a table name containing uppercase letters or spaces is quoted correctly.
Pass values separately with USING. This keeps values out of the SQL text and prevents SQL injection.
CREATE TEMP TABLE customer_labels (
id integer,
label text
);
INSERT INTO customer_labels VALUES
(1, 'vip'),
(2, 'standard'),
(3, 'vip');
CREATE FUNCTION count_label(
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;
$$;
SELECT count_label('customer_labels', 'label', 'vip');The function inserts the table and column names into the statement, but it sends 'vip' as a parameter. INTO stores the single result from the dynamic query in v_count.
Quoting values and validating fragments
%L formats a value as an SQL literal. It is useful when a value must become part of a statement that cannot use parameters, but USING is usually clearer and safer.
SELECT format('status = %L', 'active');This produces a quoted SQL fragment. Do not use %s with untrusted input. %s inserts text without quoting.
Some SQL fragments cannot be parameters or identifiers. For example, a sort direction is a keyword. Validate it against an allowlist before inserting it:
IF upper(p_direction) NOT IN ('ASC', 'DESC') THEN
RAISE EXCEPTION 'invalid sort direction: %', p_direction;
END IF;Common errors
- Using
$1for a table or column name. - Concatenating user input directly into SQL.
- Using
%swhere%Iis required. - Forgetting that unqualified names depend on
search_path. - Assuming dynamic SQL automatically reuses the plan of a static statement.
- Allowing arbitrary table names when the function should access only approved tables.
Exercise
How should a function safely insert a caller-provided column name and value into a dynamic WHERE clause?
Show answer
Insert the column name with format('%I', column_name) and pass the value through USING, referenced in the SQL as $1.