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.

SqlSecurity Boundaries

Code

snippet
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

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.