// strings reference

SQLite printf function

Builds a string from a C-style format pattern and a list of arguments.

Категория
Strings
Returns
string
In this category
115 of 172

Синтаксис

printf(format, arg, ...)
format(format, arg, ...)  -- alias from 3.38

Each block is a separate form. The support table and the examples show which engine takes which.

Поддержка движка

ДвижокSupportЗаметки
SQL Server Different name or syntax FORMATMESSAGE('%s has %d', a, b) takes printf-style placeholders.
PostgreSQL Different name or syntax format() with %s, %I and %L; no width or precision for numbers.
MySQL Not built in No printf-style function; CONCAT and FORMAT.
SQLite Да Supported under this name.
Oracle Not built in No printf-style SQL function; TO_CHAR and ||.

Примеры

SQLite

SELECT printf('%s: %.2f', 'total', 12.5) AS line;  -- total: 12.50

SQLite

SELECT printf('%05d', id) AS zero_padded
FROM invoices;

SQLite

SELECT format('%s=%Q', k, v) AS pair
FROM settings;

Полезно знать

  • printf has been in SQLite for a long time; format() was added in 3.38.0 as another name for it.
  • Patterns follow C: %d for integers, %.2f for two decimals, %s for text, %% for a literal percent sign. SQLite adds a ',' flag for thousands separators: printf('%,d', 1234567) is '1,234,567'.
  • %q doubles single quotes without adding outer quotes; %Q also wraps the value in quotes and turns NULL into the bare word NULL. %w doubles double quotes for identifiers.

Questions about PRINTF

Is format() the same as printf() in SQLite?

Yes. format() arrived in SQLite 3.38.0 as an alias; both accept the same patterns, including %q, %Q and %w.

How do I zero-pad a number in SQLite?

printf('%05d', n) pads to five digits with zeros. The width comes before the type letter, and a leading 0 in the width enables zero fill.

What does %Q do that %s does not?

%Q wraps the text in single quotes and doubles embedded quotes, producing a literal that is safe to embed in generated SQL; %s substitutes the raw text.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, SQLite.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.