If country_id
column is character datatype (NOT numeric), then you could prepend zeros and take the rightmost portion:
UPDATE foo SET country_id = RIGHT(CONCATENATE('0000',country_id),4)
UPDATE foo SET country_id = LPAD(country_id, 4, '0')
(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.
country_id INT(4) ZEROFILL
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:
SELECT LPAD(country_id, 4, '0') AS country_id
But note that's going to return a character type, not a numeric.