SQL printf / format function
Formats a template with arguments like C's sprintf. SQLite's printf and format and PostgreSQL's format() cover the niche between CONCAT and TO_CHAR.
- Категория
- Strings
- Returns
string- In this category
- 20 of 172
Синтаксис
printf(format, args...)
format(format, args...)
Each block is a separate form. The support table and the examples show which engine takes which.
Поддержка движка
| Движок | Support | Заметки |
|---|---|---|
| SQL Server | Not built in | No built-in equivalent. |
| PostgreSQL | Да | format() with %s, %I and %L placeholders |
| MySQL | Not built in | No built-in equivalent. |
| SQLite | Да | printf() from 3.8.3; format() alias from 3.38.0 |
| Oracle | Not built in | No built-in equivalent. |
Примеры
SQLite
SELECT printf('%05d', 42) AS padded; -- 00042
PostgreSQL
SELECT format('%s (%s)', 'draft', 'v2') AS label; -- draft (v2)
PostgreSQL
SELECT format('%I = %L', 'order details', 'it''s') AS safe; -- "order details" = 'it''s'
Полезно знать
- SQLite printf supports the C staples: %d, %s, %f, width and zero-fill like %05d. PostgreSQL's format is simpler: %s, %I (identifier), %L (literal), with %1$s positional reuse.
- PostgreSQL's format has no %.1f-style precision; use to_char or round() first, then feed the result in as %s.
- SQL Server's nearest tool is FORMATMESSAGE; MySQL and Oracle have no sprintf-style function; CONCAT chains or TO_CHAR do the work.
- In SQLite, format() and printf() are the same function. format() only exists from SQLite 3.38.0, so use printf() when older builds are in play.
Questions about printf / format
What is the difference between printf and format in SQLite?
None. They are the same function. printf() came first (3.8.3); format() was added as an alias in 3.38.0, matching the name PostgreSQL uses.
What do %I and %L mean in PostgreSQL's format()?
%I quotes the value as an identifier (safe for dynamic SQL object names), %L as a literal (quotes and doubles embedded quotes). %s substitutes plain text.
Can I zero-pad numbers with printf?
Yes: printf('%06d', 1234) is 001234 in SQLite. That is also the standard SQLite answer to LPAD-style padding, which SQLite does not have.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Convert a number to formatted text in SQL Server, PostgreSQL, MySQL, SQLite and Oracle Dialect comparison
- Format money and currency values as strings in SQL Snippet
- Grant SELECT on all tables Snippet
- List materialized views and refresh times Snippet
- Move a table between schemas Snippet
- Pad numbers with leading zeros in SQL Snippet
Cheat sheets for the engines that have it: PostgreSQL, SQLite.
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.