format
(formatstr
text
[,formatarg
"any"
[, ...] ])
formatstr
is a format string
that specifies how the result should be formatted. Text in the format
string is copied directly to the result, except where format
specifiers are used. Format specifiers act as placeholders in
the string, defining how subsequent function arguments should be
formatted and inserted into the result. Each formatarg
argument is converted to text according to the usual output rules for
its data type, and then formatted and inserted into the result string
according to the format specifier(s).
Format specifiers are introduced by a %
character and have the form
%[position
][flags
][width
]type
where the component fields are:
position
(optional)
n
$
where n
is the index of the
argument to print. Index 1 means the first argument after formatstr
.
If the position
is omitted,
the default is to use the next argument in sequence.
flags
(optional)
-
)
which will cause the format specifier's output to be left-justified.
This has no effect unless the width
field is also specified.
width
(optional)
-
flag)
with spaces as needed to fill the width. A too-small width does not
cause truncation of the output, but is simply ignored. The width may
be specified using any of the following: a positive integer; an
asterisk (*
) to use the next function
argument as the width; or a string of the form *
n
$
to use the n
th function
argument as the width.
-
flag had been specified)
within a field of length abs
(width
).type
(required)
s
formats the argument value as a
simple string. A null value is treated as an empty string.
I
treats the argument value as an SQL
identifier, double-quoting it if necessary. It is an error for the
value to be null (equivalent to quote_ident
).
L
quotes the argument value as an SQL
literal. A null value is displayed as the string NULL
,
without quotes (equivalent to quote_nullable
).
In addition to the format specifiers described above, the special
sequence %%
may be used to output a
literal %
character.
Here are some examples of the basic format conversions:
SELECT format('Hello %s', 'World'); Result:Hello World
SELECT format('Testing %s, %s, %s, %%', 'one', 'two', 'three'); Result:Testing one, two, three, %
SELECT format('INSERT INTO %I VALUES(%L)', 'Foo bar', E'O\'Reilly'); Result:INSERT INTO "Foo bar" VALUES('O''Reilly')
SELECT format('INSERT INTO %I VALUES(%L)', 'locations', 'C:\Program Files'); Result:INSERT INTO locations VALUES('C:\Program Files')
Here are examples using width
fields and the -
flag:
SELECT format('|%10s|', 'foo'); Result:| foo|
SELECT format('|%-10s|', 'foo'); Result:|foo |
SELECT format('|%*s|', 10, 'foo'); Result:| foo|
SELECT format('|%*s|', -10, 'foo'); Result:|foo |
SELECT format('|%-*s|', 10, 'foo'); Result:|foo |
SELECT format('|%-*s|', -10, 'foo'); Result:|foo |