Saturday 5 January 2013

Episode 19: WHERE Clause



The beast clause called WHERE deserves its own little section because it’s really the meat of the query. (No offense to the other guys, but they are pretty much “no brainers.”) WHERE is like a cool big brother that can really do some interesting stuff. While SELECT tells MySQL which fields you want to see, WHERE tells it which records you want to see. It is used as follows:

SELECT * FROM customers
//retrieves all information about all customers
SELECT * FROM customers WHERE gender = “Male”
//retrieves all information about male customers

Let’s look at the WHERE clause a little more in-depth:

Comparison operators are the heart of the WHERE clause, and they include the following:
=, <, >, <=, >=, !=

LIKE and %: Oh how we like LIKE. LIKE lets you compare a piece of text or number and gives you the % as a wildcard. The wildcard allows you to search even if you only know a piece of what’s in the field, but you don’t want an exact match.
Example:

SELECT * FROM products WHERE description LIKE “%shirt%”

This gives you any records that have the word or text pattern of “shirt” in the description,
such as “t-shirt,” “blue shirts,” or “no shirts here.” Without the %s you would get
only those products that have a description of “shirt” and nothing else.

Logical operators are also accepted in the WHERE clause:

SELECT * FROM products WHERE description LIKE “%shirt%” AND price < 25

This gives you all the products that have the word or text pattern of “shirt” in the description and that have a price of less than $25.


Written by ‘Shojib’.

No comments:

Post a Comment