Sub topic 13
Building text with `format`, `quote_ident` and `quote_literal`
This chapter assumes basic SELECT, WHERE, and GROUP BY syntax, PostgreSQL data types, NULL, and the ability to run queries in psql or another SQL client.
PostgreSQL provides functions for building text from values. These functions are useful for messages, generated reports, and dynamic SQL, which is SQL assembled while a program runs. Dynamic SQL needs special care because identifiers and values follow different quoting rules.
Formatting text with `format`
format replaces placeholders in a template:
| Placeholder | Meaning | Example |
|---|---|---|
| `%s` | Insert text as supplied | `%s` |
| `%I` | Quote an SQL identifier | `%I` |
| `%L` | Quote an SQL literal | `%L` |
An identifier is a database object name, such as a table or column. A literal is a value, such as a string or number.
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'%s inserts its argument as text. %I produces a safely quoted identifier when needed. %L produces a safely quoted literal, including doubled single quotes inside the value.
format only returns text. It does not execute the text as SQL.
Quoting identifiers and values
quote_ident quotes an identifier when quoting is necessary:
SELECT quote_ident('My Table') AS identifier;This returns "My Table". The double quotes preserve the space and capitalization in the identifier.
quote_literal quotes a value for use as an SQL literal:
SELECT quote_literal('O''Reilly') AS literal;This returns 'O''Reilly'.
quote_literal(NULL) returns SQL NULL, not the characters 'NULL'. For nullable values, quote_nullable returns the text NULL when its argument is null. The %L conversion in format follows the nullable behavior.
Dynamic SQL with `format` and `USING`
The following complete example creates a temporary table and runs dynamic SQL. The table name is inserted with %I, while the customer value is passed separately as $1.
CREATE TEMP TABLE orders (customer text);
INSERT INTO orders (customer)
VALUES ('O''Reilly'), ('Ana');
DO $$
DECLARE
table_name text := 'orders';
customer_name text := 'O''Reilly';
matching_rows integer;
BEGIN
EXECUTE format(
'SELECT count(*) FROM %I WHERE customer = $1',
table_name
)
INTO matching_rows
USING customer_name;
RAISE NOTICE 'matching rows: %', matching_rows;
END
$$;The generated SQL contains a safely quoted table identifier. PostgreSQL supplies customer_name as a parameter, so its apostrophe cannot change the SQL structure.
Common errors
- Using
%sfor a table or column name can produce invalid SQL or unsafe SQL. - Concatenating an untrusted value directly into a query can allow SQL injection.
- Putting a value into
%Itreats it as an identifier, not as a string value. - Assuming
formatexecutes its result. UseEXECUTEinside PL/pgSQL when execution is required.
Exercise
Which expression should insert a table name, and which approach should insert a user-provided search value?
Show answer
Use format('%I', tablename) for the table name. Use a $1 placeholder with EXECUTE ... USING searchvalue for the user-provided value.