// strings reference

SQL LPAD function

Pads a string to a target width with a fill string: zero-padded invoice numbers, aligned codes, fixed-width exports. PostgreSQL, MySQL and Oracle have it built in; SQL Server and SQLite build it from other functions.

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

Синтаксис

LPAD(string, width [, fill])

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

ДвижокSupportЗаметки
SQL Server Not built in no LPAD; use RIGHT(REPLICATE('0', n) + s, n) or FORMAT
PostgreSQL Да Supported under this name.
MySQL Да Supported under this name.
SQLite Not built in no LPAD; use printf('%05d', x) for numbers
Oracle Да Supported under this name.

Примеры

PostgreSQL

SELECT LPAD(CAST(invoice_no AS text), 6, '0') AS invoice
FROM invoices;

SQL Server

SELECT RIGHT(REPLICATE('0', 6) + CAST(invoice_no AS varchar(10)), 6) AS invoice
FROM invoices;

SQLite

SELECT printf('%06d', invoice_no) AS invoice FROM invoices;

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

  • If the string is longer than the width, it is cut to width: LPAD('123456', 4, '0') is '1234'. LPAD never returns more than width characters.
  • Zero-padding numbers is the common use. PostgreSQL needs text: LPAD(CAST(n AS text), 5, '0'), because there is no LPAD(integer, ...). MySQL and Oracle convert the number for you: LPAD(42, 5, '0') is '00042'.
  • SQLite's printf (also spelled format from 3.38) handles numeric padding: printf('%05d', 42) is 00042.

Questions about LPAD / RPAD

Why does LPAD truncate my value?

LPAD pads up to the target width and truncates anything longer. It is a to-width function, not a minimum-width function.

How do I zero-pad a number in SQL Server?

There is no LPAD. RIGHT(REPLICATE('0', 6) + CAST(x AS varchar), 6) is the classic; FORMAT(x, '000000') works but is slow for large sets.

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

// 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.