Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - how to front pad zip code with "0"?

In my MySQL InnoDB database, I have dirty zip code data that I want to clean up.

The clean zip code data is when I have all 5 digits for a zip code (e.g. "90210").

But for some reason, I noticed in my database that for zipcodes that start with a "0", the 0 has been dropped.

So "Holtsville, New York" with zipcode "00544" is stored in my database as "544"

and

"Dedham, MA" with zipcode "02026" is stored in my database as "2026".

What SQL can I run to front pad "0" to any zipcode that is not 5 digits in length? Meaning, if the zipcode is 3 digits in length, front pad "00". If the zipcode is 4 digits in length, front pad just "0".

UPDATE:

I just changed the zipcode to be datatype VARCHAR(5)

like image 505
TeddyR Avatar asked Jul 08 '10 04:07

TeddyR


People also ask

What is the datatype for zip code in MySQL?

Zip codes are always 5 characters, hence you would need a CHAR datatype, rather than VARCHAR.

Can a ZIP code be a primary key?

Zip code can easily be a primary key in such structure, and are often used as such for not only normalization but also validation so the user does not have to enter the city name which can reduce the number of errors happening due to various forms of spelling/spelling mistakes.

What is Lpad in MySQL?

MySQL LPAD() Function The LPAD() function left-pads a string with another string, to a certain length.


2 Answers

Store your zipcodes as CHAR(5) instead of a numeric type, or have your application pad it with zeroes when you load it from the DB. A way to do it with PHP using sprintf():

echo sprintf("%05d", 205); // prints 00205 echo sprintf("%05d", 1492); // prints 01492 

Or you could have MySQL pad it for you with LPAD():

SELECT LPAD(zip, 5, '0') as zipcode FROM table; 

Here's a way to update and pad all rows:

ALTER TABLE `table` CHANGE `zip` `zip` CHAR(5); #changes type UPDATE table SET `zip`=LPAD(`zip`, 5, '0'); #pads everything 
like image 86
quantumSoup Avatar answered Sep 28 '22 05:09

quantumSoup


You need to decide the length of the zip code (which I believe should be 5 characters long). Then you need to tell MySQL to zero-fill the numbers.

Let's suppose your table is called mytable and the field in question is zipcode, type smallint. You need to issue the following query:

ALTER TABLE mytable CHANGE `zipcode` `zipcode`     MEDIUMINT( 5 ) UNSIGNED ZEROFILL NOT NULL; 

The advantage of this method is that it leaves your data intact, there's no need to use triggers during data insertion / updates, there's no need to use functions when you SELECT the data and that you can always remove the extra zeros or increase the field length should you change your mind.

like image 20
Anax Avatar answered Sep 28 '22 07:09

Anax