// SQL snippet

Pad numbers with leading zeros in SQL

Invoice and account numbers are stored as integers but must print as fixed-width strings with leading zeros.

Main statement
PostgreSQL
还支持
SQL Server MySQL SQLite

The task

Invoice 7 has to appear as INV-00000007. LPAD pads the string form of the number with zeros on the left up to the target width.

The snippet

Written for PostgreSQL. Versions for SQL Server, MySQL and SQLite are under Variations.

PostgreSQL
SELECT 'INV-' || LPAD(invoice_no::text, 8, '0') AS invoice_key
FROM invoices;

工作原理

LPAD(text, width, '0') left-pads with zeros until the value is eight characters long. Careful: LPAD also truncates longer values to the width, so 123456789 becomes '12345678' on PostgreSQL, MySQL and Oracle. Cast the number to text first on PostgreSQL, since LPAD works on strings.

Variations

SQL Server

SQL Server
SELECT 'INV-' + FORMAT(invoice_no, 'D8') AS invoice_key
FROM invoices;

MySQL

MySQL
SELECT CONCAT('INV-', LPAD(invoice_no, 8, '0')) AS invoice_key
FROM invoices;

SQLite

SQLite
SELECT 'INV-' || printf('%08d', invoice_no) AS invoice_key
FROM invoices;

Questions that come up

What happens to a number wider than the pad width?

It depends on the function. LPAD cuts the string to the width, so LPAD('123456789', 8, '0') returns '12345678', a wrong invoice number. SQL Server's FORMAT(n, 'D8') and SQLite's printf('%08d', n) treat 8 as a minimum and return all nine digits, while the old RIGHT('00000000' + ..., 8) trick truncates too. Check LENGTH before padding if values can outgrow the width.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.