tags:

views:

29

answers:

3

Hello

I need to make a selection based on the first 2 characters of a field, so for example

SELECT * from table WHERE postcode LIKE 'rh%'

But this would select any record that contains those 2 characters at any point in the "postcode" field right? I am in need of a query that just selects the first 2 characters. Any pointerS?

Thanks

+4  A: 

Your query is correct. It searches for postcodes starting with "rh".

In contrast, if you wanted to search for postcodes containing the string "rh" anywhere in the field, you would write:

SELECT * from table WHERE postcode LIKE '%rh%'

Edit:

To answer your comment, you can use either or both % and _ for relatively simple searches. As you have noticed already, % matches any number of characters whereas _ matches a single character.

So, in order to match postcodes starting with "RHx " (where x is any character) your query would be:

SELECT * from table WHERE postcode LIKE 'RH_ %'

(mind the space after _). For more complex search patterns, you need to read about regular expressions.

Further reading:

http://dev.mysql.com/doc/refman/5.1/en/pattern-matching.html

http://dev.mysql.com/doc/refman/5.1/en/regexp.html

Anax
Many thanks for your response.Yes it seems that query is selecting any postcode field starting with 'RH'. This is the issue I am having:Let's say I only want postcodes that start with RH1, for example:RH1 3JSRH2 7YHBut my query would also select:RH16 3NP RH17 3THIs there a way to stop the selection after 3 (or any number) of characters?Many thanks
Dave
Many thanks Anax for the code and the links, i have got the majority of the query working how I would like now, cheers.
Dave
A: 

LIKE '%rh%' will return all rows with 'rh' anywhere

LIKE 'rh%' will return all rows with 'rh' at the beginning

LIKE '%rh' will return all rows with 'rh' at the end.

If you want to get only first two characters 'rh', use MySQL SUBSTR() function http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_substr

dwich
This is very helpful, MySQL SUBSTR() looks promising
Dave
A: 

Dave, your way seems correct to me (and works on my test data). Using a leading % as well will match anywhere in the string which obviously isn't desirable when dealing with postcodes.

Leo
Thanks! yep it does work correctly, but I have further comments (see above)
Dave
I haven't tested it but you might have some success with '_'. see http://dev.mysql.com/doc/refman/5.1/en/pattern-matching.html
Leo