I got a mysql database column named country_id, like:
country_id
----------
1
2
59
435
2714
What I'm trying to accomplish now is to add leading zero's to each ID, so the result would be:
country_id
----------
0001
0002
0059
0435
2714
Each ID should have max 4 digits. That's it.
Is there any SQL statement I could use in PHPmyAdmin to update this country_id column in the way described above?
Best regards!
If
country_id
column is character datatype (NOT numeric), then you could prepend zeros and take the rightmost portion:(NOTE: Either of those statements will result in data loss, if any value of
country_id
is longer than 4 characters... the first gets the righmost characters, the second will rth get the four leftmost characters, if country_id is over four characters. If a value has e a leading '-' character, that will result in an odd looking value e.g. '00-4'. The LTRIM function is available to remove leading spaces.If, on the other hand,
country_id
is a numeric datatype, then you can't really add leading zeros.For an integer type, you can specify a display length and the ZEROFILL option, e.g.
But it's up to the client application to make use of the length modifier and the ZEROFILL attribute to do the specified formatting, there's not really anything being done "in the database" with those attributes. (The MySQL command line client will observe those settings, and display the value zero filled to a max of four characters. But other clients are not required to do that.)
You could also cast that value to character and pad it with leading '0' characters, in a query:
But note that's going to return a character type, not a numeric.
If you can change your DB structure use ZEROFILL
Declare
ZEROFILL
on the column: