Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding leading zeros to a number

Tags:

mysql

I was wondering if there was a way to add leading zeros to numbers when selected that are less than 4 characters and cast as a string.

I appreciate any advice, thanks in advance!

Something like:

SELECT PAD(CAST(last4 as string), 4) as last4 from numbers

Desired output:

1 => 0001
100 => 0100
112 => 0112
15 => 0015
like image 583
AnchovyLegend Avatar asked Mar 10 '26 10:03

AnchovyLegend


1 Answers

You were very near:

SELECT LPAD(last4, 4, '0') as last4 FROM numbers;

see https://dev.mysql.com/doc/refman/5.6/en/string-functions.html#function_lpad

like image 144
VMai Avatar answered Mar 13 '26 10:03

VMai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!