January 21st, 2012
SQL Where
The WHERE statement is used to retrieve if you want to limit data extracted based on certain criteria. The ebasic syntax for DISTINCT is as follows
SELECT column1, column2 WHERE column(s) operator value FROM table;
WHERE Example Usage
The Persons Table
| ID | First_Name | Last_Name | Gender | Occupation |
|---|---|---|---|---|
| 123 | Fabian | Salvador | Male | Fireman |
| 543 | James | Parker | Male | Wrestler |
| 345 | Abigail | Grant | Female | Fireman |
| 223 | Chloe | Strange | Female | Secretary |
| 545 | Emma | Rogers | Female | Model |
| 275 | Gwen | Watson | Female | Model |
| 522 | Stephen | Rogers | Male | Salesman |
If we want to retrieve the persons with the Last_Name of Rogers, our SQL Statement would look like this:
SELECT * FROM Persons WHERE Last_Name = 'Rogers'
The result would look like this:
| ID | First_Name | Last_Name | Gender | Occupation |
|---|---|---|---|---|
| 545 | Emma | Rogers | Female | Model |
| 522 | Stephen | Rogers | Male | Salesman |
If we want to select the Male Persons from the Persons table, our SQL statement would look like this
SELECT * FROM Persons WHERE Gender = 'Male'
| ID | First_Name | Last_Name | Gender | Occupation |
|---|---|---|---|---|
| 123 | Fabian | Salvador | Male | Fireman |
| 543 | James | Parker | Male | Wrestler |
| 545 | Emma | Rogers | Female | Model |
| 522 | Stephen | Rogers | Male | Salesman |
Using SELECT DISTINCT and WHERE together
| ID | First_Name | Last_Name | Gender | Occupation |
|---|---|---|---|---|
| 123 | Fabian | Salvador | Male | Fireman |
| 543 | James | Parker | Male | Wrestler |
| 345 | Abigail | Grant | Female | Fireman |
| 223 | Chloe | Strange | Female | Secretary |
| 545 | Emma | Rogers | Female | Model |
| 275 | Gwen | Watson | Female | Model |
| 522 | Stephen | Rogers | Male | Salesman |
In this example we would like to retrieve the Occupations of Female persons and we don’t like duplicates.
SELECT DISTINCT Occupation FROM Persons WHERE Gender = 'Female'
The result will be as follows:
| Occupation |
|---|
| Fireman |
| Secretary |
| Model |