StringsPostgreSQL only

FORMAT

Builds a string from a template, substituting values for %s.

Syntax

FORMAT('<template>', <value1>, <value2>, …)

In the template, %s is a slot for a value as text, %I — for a table or column name (quoted if needed), %L — for a value as an SQL literal in single quotes. More convenient than long chains of ||, especially when there are many values.

Data for the examples

employees

namedepartmentsalarybonusphone
Emmabackend1200300+44 7700 900123
Liambackend1000NULLNULL
Oliviafrontend1350150+44 7700 900456
Noahfrontend950NULL+44 7700 900789
Sophiadesign1200200NULL

These tables already exist in the sandbox — the examples below use them. Want to try this in your own database? Copy the SQL.

Substitute a value
SELECT FORMAT('Hello, %s!', 'Emma') AS greeting;
greeting
Hello, Emma!
A sentence for each employee
SELECT FORMAT('%s works in %s and earns %s', name, department, salary) AS sentence
FROM employees;
sentence
Emma works in backend and earns 1200
Liam works in backend and earns 1000
Olivia works in frontend and earns 1350
Noah works in frontend and earns 950
Sophia works in design and earns 1200
Safe SQL query textAdvanced
SELECT FORMAT('SELECT * FROM %I WHERE name = %L', 'employees', 'O''Brien') AS query;
query
SELECT * FROM employees WHERE name = 'O''Brien'

%L put the value in single quotes and doubled the apostrophe inside by itself. That's how SQL is built in PL/pgSQL functions without fear of SQL injection.

Watch out

NULL through %s becomes an empty string: FORMAT('phone: %s', NULL) gives phone: . %L, on the other hand, writes the word NULL.

To output a percent sign itself, write %%: FORMAT('%s%%', 50) gives 50%.

Fewer values than slots in the template is an error: too few arguments for format().

Related functions