format() Quotes Identifiers And Literals
format() quotes identifiers with %I and escapes literals with %L so dynamically assembled SQL stays safe; %s inserts raw text for trusted fragments.
Code
WITH parts AS (
SELECT * FROM (VALUES
('orders', 'O''Brien Ltd'),
('user prefs', 'plain')
) AS t(table_name, client_label)
)
SELECT
table_name,
client_label,
-- %I emits a quoted safe identifier: spaces, reserved words and embedded quotes all get escaped
format('SELECT * FROM %I', table_name) AS identifier_sql,
-- %L emits a safe literal: single quotes double automatically, blocking injection
format('INSERT INTO log (label) VALUES (%L)', client_label) AS literal_sql,
-- %s splices raw text with no escaping: trusted fragments only
format('%s_%s_stats', 'public', table_name) AS plain_join
FROM parts;What the demo quotes
Two rows feed format() with awkward inputs. %I wraps each table name in double quotes, so user prefs survives its space and any embedded quote would double up, producing SELECT * FROM “orders” and its quoted sibling.
%L builds the INSERT literal, doubling the apostrophe in O’Brien Ltd so the generated SQL cannot break or inject. %s stays raw: public and the table name form the stats-table name with no quoting, which is exactly why it is reserved for trusted fragments.
Practical notes
- Identifiers and literals need different quoting: %I versus %L.
- %s is the escape hatch, not the default.
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.
FAQ
- When is %s acceptable in format()?
- Only for fragments you already trust, like a schema constant; anything derived from names or user data goes through %I or %L, as the demo shows for both.
Report a problem with this exampleOpens a pre-filled issue on GitHub.