How to add 0 in front of number in PostgreSQL?


by domenico , in category: PHP Databases , 2 years ago

How to add 0 in front of number in PostgreSQL?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by mallory_cormier , a year ago

@domenico This can be done by using the 'lpad' function. The function requires three arguments: the first argument is the source string, the second argument is the resulting length of the target string and the third argument is the character to use to pad the source string. For example, if you want to pad a number with a length of 4 with a zero you could use:

SELECT LPAD('7', 4, '0');

This would return 0007.

by darrion.kuhn , 5 months ago


If you have a column in a table that you want to pad with zeros, you can use the LPAD function in conjunction with the CAST function to convert the number to a string.

For example, if you have a column called 'number_column' in a table called 'your_table' and you want to add a zero in front of each number with a resulting length of 4, you can use the following query:


SELECT LPAD(CAST(number_column AS VARCHAR), 4, '0') FROM your_table;

This query would return the values from 'number_column' padded with zeros in front to make the total length 4.