Monday, August 29, 2011

SQL Where Command


The SQL WHERE clause is used to select data conditionally, by adding it to already existing SQL SELECT query. We are going to use the Company table from the previous chapter, to illustrate the use of the SQL WHERE command.

Table: Company


LastName
Email
DOB
Phone
Scott
Armstrong
Armstrong.yahoo.com
2/4/1968
887-676-2321
Adam
Red
red@himail.com
4/4/1978
792 343-2422
Santo
Harry
Harry@livingin.org
5/24/1978
416 323-3232
Jackson
Jimmy
Jimmy@supermail.co.uk
20/10/1980
416 323-8888


If we want to select all Company from our database table, having last name 'Armstrong' we need to use the following SQL syntax:

SELECT *
FROM Company
WHERE LastName = 'Armstrong'
The result of the SQL expression above will be the following:
FirstName
LastName
Email
DOB
Phone
Scott
Armstrong
Armstrong.yahoo.com
2/4/1968
887-676-2321

In this simple SQL query we used the "=" (Equal) operator in our WHERE criteria:
LastName = 'Armstrong'
 
But we can use any of the following comparison operators in conjunction with the SQL WHERE clause:

<> (Not Equal)

SELECT *
FROM Company
WHERE LastName <> 'Armstrong'

> (Greater than)

SELECT *
FROM Company
WHERE DOB > '1/1/1970'

>= (Greater or Equal)

SELECT *
FROM Company
WHERE DOB >= '1/1/1970'

< (Less than)

SELECT *
FROM Company
WHERE DOB < '1/1/1970'

<= (Less or Equal)

SELECT *
FROM Company
WHERE DOB =< '1/1/1970'

LIKE (similar to)

SELECT *
FROM Company
WHERE Phone LIKE '626%'

Between (Defines a range)

SELECT *
FROM Company
WHERE DOB BETWEEN '1/1/1970' AND '1/1/1975'.


MORE BASIC SQL COMMANDS


No comments:

Post a Comment