mysql format number leading zeros

Solutions on MaxInterview for mysql format number leading zeros by the best coders in the world

showing results for - "mysql format number leading zeros"
Alma
21 Jan 2020
1Here’s an example of padding a single digit number with two zeros:
2
3SELECT LPAD(7, 3, 0);
4Result:
5
6+---------------+
7| LPAD(7, 3, 0) |
8+---------------+
9| 007           |
10+---------------+
11In this case, two leading zeros were added because we specified 3 as the required length.
12
13So if we start with a two digit number, only one zero is added:
14
15SELECT LPAD(17, 3, 0);
16Result:
17
18+----------------+
19| LPAD(17, 3, 0) |
20+----------------+
21| 017            |
22+----------------+
23Non-Zero Values
24The LPAD() function isn’t limited to just zeros. As mentioned, it can be used to pad any string with any other string. So you can pad a number with leading 1s, or leading letters, or other symbols if required.
25
26SELECT LPAD(7, 10, '.');
27Result:
28
29+------------------+
30| LPAD(7, 10, '.') |
31+------------------+
32| .........7       |
33+------------------+
34And because it’s actually a string function, it can be used to pad any non-numeric string. And it’s not limited to just one padding character – it can be padded with multiple characters if need be:
35
36SELECT LPAD('Cat', 21, 'Meow! ') AS Result;
37Result:
38
39+-----------------------+
40| Result                |
41+-----------------------+
42| Meow! Meow! Meow! Cat |
43+-----------------------+