SQL Tutorial - WHERE Clause
$count++; if($count == 1) { include "../mobilemenu.php"; } if ($count == 2) { include "../sharemediasubfolder.php"; } ?>
In SQL SELECT, a WHERE clause can be used to specify conditions to filter the table further. We can filter an SQL Table based on a single column or more than one column. Imagine we have table called CUSTOMERS, with the following data:
FIRSTNAME
LASTNAME
AGE
COUNTRY
Rambo
Robert
25
Belgium
Mugambo
Satraj
37
Norway
Nagashekar
Rao
47
India
Tom
Harry
27
Brazil
Dana
Laura
21
Australia
Rambo
Fox
57
New Zealand
Giselle
Chivvi
87
Japan
SELECT * from Customer WHERE FIRSTNAME = 'Rambo'
Result:
FIRSTNAME
LASTNAME
AGE
COUNTRY
Rambo
Robert
25
Belgium
Rambo
Fox
57
New Zealand
We can use the Following operators in WHERE clause.
Operator | Meaning |
= | Direct Equals Check |
!= and <> | Not Equals Check |
< | Columns Values that are less than the Right Hand Side value |
<= | Column Values that are less than or equal to the Right Hand Side value |
> | Column Values that are greater than the Right Hand Side value |
>= | Column Values that are greater than or equal to the Right Hand Side value |
IN | Gets ROWS where value is in the given set of values |
NOT IN | Gets ROWS where value is not in the given set of values |
BETWEEN | Gets ROWS where value is in between the given range |
NOT BETWEEN | Gets ROWS where value is not in between the given set of values |
Scenario 2: Get me all records where Customer's First name is Rambo, and Country is Belgium. We can combine two conditions with AND clause to achieve the above scenario.
SELECT * from Customer WHERE FIRSTNAME = 'Rambo' AND COUNTRY='Belgium'
Result:
FIRSTNAME
LASTNAME
AGE
COUNTRY
Rambo
Robert
25
Belgium
Scenario 3: Get me all records where Customer's First name is Rambo or Mugambo. We can combine two conditions with OR clause to achieve the above scenario.
SELECT * from Customer WHERE FIRSTNAME = 'Rambo' OR FIRSTNAME='Mugambo'
Result:
FIRSTNAME
LASTNAME
AGE
COUNTRY
Rambo
Robert
25
Belgium
Mugambo
Satraj
37
Norway
Rambo
Fox
57
New Zealand
Scenario 4: Get me all records where Customer's Age is below 30. We can use the less than < operator on Age column for the above scenario.
SELECT * from Customer WHERE AGE < 30
Result:
FIRSTNAME
LASTNAME
AGE
COUNTRY
Rambo
Robert
25
Belgium
Tom
Harry
27
Brazil
Dana
Laura
21
Australia