MySQL - Fetch rows where a field value is less than 5 chars

Viewed 19168

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!

5 Answers

You can use length

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

Check this out for more info.

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

You can do

SELECT * FROM table WHERE LENGTH(zip) <= 5;
Related