Main Content

SELECT in MySQL - choosing the rows you want

Archive - Originally posted on "The Horse's Mouth" - 2005-11-22 08:27:40 - Graham Ellis

The SELECT command in MySQL allows you to examine rows in a table (or more than one table if you like). Good news - but sometimes there's an awful lot of data and you just want rows chosen by particular criteria, or just the first (so many) rows.

The WHERE clause on your select allows you to write a number of conditions which can be linked with AND and OR keywords, and there's a great deal of choice in the conditions. Here are some examples:

WHERE name = "Graham"
Will look for the string Graham (exactly) and nothing else in the field called name. Note that this selection is case sensitive if name is specified as being a binary field, and case insensitive otherwise.

WHERE name IN ("Graham","Lisa","Leah")
Will look for any one of the strings Graham Lisa or Leah (exactly in each case; same rule about case as in the example above).

WHERE name LIKE "%Graham%"
Will return any row that contains the word Graham within the name field. This is similar to file name matching (also known as globbing) except that the % metacharacter means "anything" and the _ character (that's an underscore) means any one character ... in place of * and ? in file name matching.

WHERE name RLIKE "^[[:graph:]]+$"
Will return any row with a single name in the name field - this is a regular expression which provides a huge flexibility in matching. Regular Expressions are notable in that you can ask a lot in a very obtuse string of just a few characters!