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.
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.
|>=||Greater than or equal to|
|<=||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.
- Text string - Must be enclosed within quotation marks - 'example'
- Number string - Must not be enclosed within quotation marks - 123
It is important that this markup of parameter is followed, failier to do so may cause the query to return inaccurate results.
The following WHERE clause example use the table below named ages.
So a valid query using the where clause would be.
SELECT name, age FROM age_table WHERE age >= 18 ORDER BY age ASC
And the results would look like this.
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.
blog comments powered by Disqus