tags:

views:

95

answers:

4

I need to fetch all the rows where the 'zip' field is less than 5 characters. How can I achieve this using only SQL? I google'd first, but only found info on CHAR_LENGTH().

ie, psudeo code: SELECT * FROM users WHERE STRLEN(zip_code) < 5

Thanks!

+6  A: 

CHAR_LENGTH(zip_code) < 5

Ignacio Vazquez-Abrams
Thanks, this is exactly what I was looking for.
John Himmelman
Do note the difference between `LENGTH()` and `CHAR_LENGTH()`; `LENGTH()` gives the length in bytes, whereas `CHAR_LENGTH()` gives the length in characters. This doesn't matter with an 8-bit encoding, but with UTF-8 and the like they can give different results.
Ignacio Vazquez-Abrams
+6  A: 

For MySQL you would use the LENGTH() function ie.

select * from users where length(zip_code) < 5

Refer to the docs at http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_length for more information.

wimvds
Thanks, for the source
John Himmelman
+2  A: 

You can use length

SELECT * FROM table WHERE LENGTH(myfield) < 5; 

Check this out for more info.

Daniel
You have your comparison wrong, he wants *less than* 5.
Anthony Forloney
Very true. Edited for correctness. Thanks for the catch.
Daniel
+1  A: 

If you are searching for bad zip codes then char_length(zip_code) < 5 is a start, but it will still pass invalid ZIP codes.

use SELECT * from users where char_length(zip_code) < 5 OR zip_code NOT REGEXP '^([0-9]{5})$'

The regexp part basically searches for zip_codes where the first 5 characters are not numbers between 0-9

Have Fun