Sub topic 13
Building text with format, quote_ident and quote_literal
This chapter assumes you can concatenate strings with || and concat, and that you know how NULL behaves in string expressions. It covers format, which builds text from a template, and the quoting functions quote_ident, quote_literal and quote_nullable. Together they let you generate SQL text without breaking it on odd characters.
Why not just concatenate?
You can build a message with ||:
SELECT 'Hello, ' || 'Ana' || '! You have ' || 3 || ' messages.' AS msg;This works for plain text. It becomes hard to read as the number of pieces grows, and a single NULL operand turns the whole result into NULL. It is also unsafe for generated SQL, because the pieces are pasted in without any quoting. format fixes these problems. It works like printf in C: a template string contains placeholders, and the remaining arguments fill them in.
The format function
The signature is format(template text, VARIADIC args "any"). Placeholders start with %.
SELECT format('Hello, %s! Table: %I, value: %L', 'Ana', 'My Table', 'it''s') AS message;The result is Hello, Ana! Table: "My Table", value: 'it''s'. Each specifier handles its argument differently.
| Specifier | Meaning | Example argument | Output |
|---|---|---|---|
| `%s` | Plain text, no quoting | `Ana` | `Ana` |
| `%I` | SQL identifier, quoted only if needed | `My Table` | `"My Table"` |
| `%L` | SQL literal, always quoted | `it's` | `'it''s'` |
| `%%` | A literal percent sign | none | `%` |
Arguments are converted to text first, so numbers, dates and booleans all work with %s.
Width, alignment and positions
A number after % sets a minimum width. Text is right-aligned by default, and a minus sign left-aligns it.
SELECT format('%-10s|%5s|', 'ab', 'cd') AS padded;This returns ab | cd|. Width works with %s, %I and %L.
A position such as %2$s selects an argument by number, counting from 1. This lets you reorder or reuse arguments.
SELECT format('%2$s %1$s, %2$s!', 'world', 'Hello') AS greeting;This returns Hello world, Hello!. Do not mix positional and non-positional placeholders in a way that confuses you. A plain %s takes the next argument after the previous placeholder, whichever style that placeholder used.
Passing an array
If your values are already in an array, use the VARIADIC keyword to expand it into separate arguments.
SELECT format('%s-%s-%s', VARIADIC ARRAY['2026', '11', '27']) AS date_text;This returns 2026-11-27. The array length must match the number of placeholders you use. Too few arguments raises an error with the message "too few arguments for format()". Extra arguments are ignored.
NULL handling in format
NULL behaves differently for each specifier. This is the main source of surprises.
SELECT format('[%s]', NULL) AS as_text,
format('[%L]', NULL) AS as_literal;The first column is [], because %s turns NULL into an empty string. The second is [NULL], because %L turns NULL into the bare keyword NULL with no quotes. That is correct for building an INSERT statement, because it produces a real SQL NULL.
%I is stricter. format('%I', NULL) raises an error, because an identifier cannot be NULL.
The quoting functions
format is built on three standalone functions. You can call them directly when you assemble text in other ways.
SELECT quote_ident('users') AS plain_name,
quote_ident('Users') AS mixed_case,
quote_ident('select') AS reserved_word,
quote_ident('My "Table"') AS embedded_quote;The results are users, "Users", "select" and "My ""Table""". quote_ident adds double quotes only when the name would otherwise be misread. That includes names with uppercase letters, spaces, special characters, or a reserved keyword. Any double quote inside the name is doubled.
SELECT quote_literal('it''s') AS with_quote,
quote_literal(42) AS number,
quote_literal(NULL) AS null_literal,
quote_nullable(NULL) AS nullable_null,
quote_nullable('abc') AS nullable_text;quote_literal returns 'it''s' and '42'. For NULL input it returns NULL, not the text NULL. That is a trap when you concatenate: the whole statement becomes NULL. quote_nullable returns the four-character text NULL for NULL input and behaves like quote_literal otherwise. format with %L behaves like quote_nullable.
If the string contains a backslash, quote_literal returns an E'...' string with the backslash doubled. This keeps the result correct regardless of the standard_conforming_strings setting.
Building dynamic SQL safely
The main use of these tools is dynamic SQL, where table or column names come from variables. In PL/pgSQL you run the generated text with EXECUTE.
CREATE TABLE "Audit Log" (id int, note text);
DO $$
DECLARE
tbl text := 'Audit Log';
note text := 'it''s done';
BEGIN
EXECUTE format('INSERT INTO %I (id, note) VALUES (%s, %L)', tbl, 1, note);
END
$$;
SELECT * FROM "Audit Log";The statement that runs is INSERT INTO "Audit Log" (id, note) VALUES (1, 'it''s done'). The table name is quoted by %I. The text value is quoted by %L, so the apostrophe cannot end the string early.
Why quoting matters: SQL injection
Suppose a variable holds hostile input.
SELECT format('SELECT * FROM %I', 'users; DROP TABLE users') AS safe_sql,
format('SELECT * FROM %s', 'users; DROP TABLE users') AS unsafe_sql;safe_sql is SELECT * FROM "users; DROP TABLE users". This refers to one table with a strange name, so the query fails harmlessly. unsafe_sql contains two statements, and the second one drops a table. Use %s only for text you control completely, such as a fixed keyword or an already-validated number.
Prefer USING for values
For values, a better option than %L is to pass them as parameters with USING. The value is sent separately from the SQL text, so it is never parsed as SQL. Reserve format for the parts that cannot be parameters, which are identifiers and keywords.
DO $$
DECLARE
tbl text := 'Audit Log';
note text := 'second row';
BEGIN
EXECUTE format('INSERT INTO %I (id, note) VALUES ($1, $2)', tbl)
USING 2, note;
END
$$;Parameters keep the original data type and avoid converting everything to text. %L is still useful when the statement must be a single text string, for example when generating a script to run elsewhere.
Choosing the right tool
Common errors
- Using
%sfor user input. It does no quoting, so it allows injection. Use%Ifor names and%LorUSINGfor values. - Using
%Ion a qualified name.format('%I', 'public.users')produces"public.users", a single identifier with a dot in it. Quote the schema and table separately:format('%I.%I', 'public', 'users'). - Passing NULL to
%I. This raises an error. Check for NULL first, or useCOALESCE. - Concatenating
quote_literalresults. A NULL input makes the whole expression NULL. Usequote_nullableorformat('%L'). - Too few arguments.
format('%s %s', 'a')raises an error. Count your placeholders. - Wrong text length. Width in
formatcounts characters, not bytes, so multibyte text pads as you would expect.
Exercise
A PL/pgSQL function receives a table name in tbl and a search term in term. Write the format call that builds SELECT count(*) FROM <table> WHERE name = <term> so that both parts are quoted correctly, and say what %L produces if term is NULL.
Show answer
Use format('SELECT count(*) FROM %I WHERE name = %L', tbl, term). The table name goes through %I and the search term through %L. If term is NULL, %L produces the unquoted keyword NULL, giving WHERE name = NULL. That comparison is never true, so the count is 0. Use IS NOT DISTINCT FROM if you want NULL to match NULL. Alternatively, pass the term with USING and a $1 placeholder.
Exercise
What does SELECT format('%s|%I|%L', NULL, 'Order Items', 'O''Brien') return?
Show answer
It returns |"Order Items"|'O''Brien'. %s turns NULL into an empty string, %I quotes the name because it contains a capital letter and a space, and %L doubles the apostrophe inside the quoted literal.