SQLite Tutorial SQLite Advanced SQLite Database SQLite References

SQLite PRINTF() Function



The SQLite PRINTF() function works like the printf() function from the standard C library. The first argument is a format string that specifies how to construct the output string using values taken from subsequent arguments. If the format argument is missing or NULL then the result is NULL. The %n format is silently ignored and does not consume an argument. The %p format is an alias for %X. The %z format is interchangeable with %s. If there are too few arguments in the argument list, missing arguments are assumed to have a NULL value, which is translated into 0 or 0.0 for numeric formats or an empty string for %s.

Note: This function is an alias for the SQLite FORMAT() function.

Syntax

PRINTF(format, ...)

Parameters

format Specify the format string.
... (additional arguments) Depending on the format string, a sequence of additional arguments should be passed in the function, each containing a value to replace a format specifiers in the format string. If there are too few arguments in the argument list, missing arguments are assumed to have a NULL value, which is translated into 0 or 0.0 for numeric formats or an empty string for %s. Additional arguments will be ignored by this function.

Return Value

Returns the formatted string.

Example 1: printf() example

The example below shows the usage of PRINTF() function.

SELECT PRINTF("Decimals: %d %i", 200, 300);
Result: Decimals: 200 300

SELECT PRINTF("More Decimals: %ld %li", 20000, 30000);
Result: More Decimals: 20000 30000

SELECT PRINTF("Octals: %o %#o", 100, 100);
Result: Octals: 144 0144

SELECT PRINTF("Hexadecimals: %x %#x %X %#X", 100, 100, 100, 100);
Result: Hexadecimals: 64 0x64 64 0X64

SELECT PRINTF("Strings: %s", "Hello");
Result: Strings: Hello

SELECT PRINTF("Scientific notation: %e %E", 123.45, 123.45);
Result: Scientific notation: 1.234500e+02 1.234500E+02

SELECT PRINTF("Floats: %2.0f %2.2f %2.4f", 3.1416, 3.1416, 3.1416);
Result: Floats:  3 3.14 3.1416

SELECT PRINTF("Positive signed number = %+.2f", 3.1416); 
Result: Positive signed number = +3.14

SELECT PRINTF("Padded number = %05d", 89);
Result: Padded number = 00089

SELECT PRINTF("Number with Width = %*d", 5, 89);
Result: Number with Width =    89

Example 2: Format date string

Consider a database table called BirthDay with the following records:

NameDayMonthYear
John252001
Marry782003
Kim3101995
Jo2531985
Suresh15111998
Ramesh2782000

The statement given below can be used to get the full date using values of Day, Month and Year columns.

SELECT *, PRINTF("%04d-%02d-%02d", Year, Month, Day) AS FullDate FROM Birthday;

This will produce the result as shown below:

NameDayMonthYearFullDate
John2520012001-05-02
Marry7820032003-08-07
Kim31019951995-10-03
Jo25319851985-03-25
Suresh151119981998-11-15
Ramesh27820002000-08-27

❮ SQLite Functions