BASEWEBMASTER

Brought To You By
Tomlin Ventures Ltd

WHERE Clause

Using the SQL WHERE clause

The WHERE clause is probably the most important part of the SQL statement and you will likely use it in most SQL queries. It define the criteria by which a value or values must meet for a row to be returned by the SQL query.

The WHERE clause generally appears after the FROM clause but before any grouping or ordering is applied to the statement. The query for a WHERE clause would appear as shown below.

SQL
SELECT * FROM table_name WHERE column_name = 'parameter'

This query would return any row from which the column_name value is exactly equal to the parameter, nothing more and nothing less.

Breaking the statement down firstly lets look at the operator in the where clause. There are various different operators which are recognised by SQL as shown below.

Operators Table
Operator Meaning
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
<> Does not equal
BETWEEN Between a range of values *
LIKE Contains string or pattern within it *
IN Equals one of a list of values *

* These options are explained in more detail later on.

The usage of these operators is fairly self explanatory, through the use of them it is possible to query any possible situation.

The parameter or value that is to be searched for must be shown correctly for the SQL statement to function.

It is important that this markup of parameter is followed, failier to do so may cause the query to return inaccurate results.

WHERE Example

The following WHERE clause example use the table below named ages.

ages
id name age
001 ben 16
002 bob 34
003 ann 18
004 amy 39
005 tim 24

So a valid query using the where clause would be.

SQL
SELECT name, age FROM age_table WHERE age >= 18 ORDER BY age ASC

And the results would look like this.

Results
id name age
003 ann 18
005 tim 24
002 bob 34
004 amy 39

Here the row is returned only if the value of the age column is greater than or equal to 18, the return rows are also ordered by the age value from lowest to highest.

Hit the next article below to see how we can build on the where clause and filter the data further before returning.

Share to Facebook Share to Twitter Digg This Stumble It Share to Reddit Share to Delicious Technorati LinkedIn Google Buzz Blogger More...

blog comments powered by Disqus