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
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:
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:
(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