Showing posts with label Formatting. Show all posts
Showing posts with label Formatting. Show all posts

Friday, September 4, 2026

MySQL: Generate Fixed-Length Numbers with Leading Zeros

There may be situations where you need to display a number from the database in a specific format.

For example, you may want to display a number from 001 to 999 instead of 1 to 999.

The following MySQL query can be used to add leading zeros to a number.

MySQL Query

SELECT LPAD(intfield_id, 3, '0') AS columnname FROM test;

For example:

intfield_idResult
1001
9009
25025
100100
999999

The LPAD() function adds characters to the left side of a string until it reaches the specified length.

In this example:

LPAD(intfield_id, 3, '0')

means that the value should have a total length of 3 characters, and 0 should be added to the left when necessary.

This can be useful when a database value needs to be displayed as a fixed-length number, such as 001, 002, 003, and so on.