2

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
3
  • you've edited your question to leading zeroes in your example :-) Those you get with LPAD(), trailing ones you get with RPAD().
    – VMai
    May 8, 2014 at 17:13
  • @VMai, got it, thanks! p.s. please don't shoot me down for editing the question for I am a good hearted man ;) May 8, 2014 at 17:25
  • please edit the headline and the first line of your question too - so no one would be irritated that an answer that gives leading zeroes was the right one after being asked for trailing ones ...
    – VMai
    May 8, 2014 at 17:28

1 Answer 1

3

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.