HomeBrainDump Page 2 - Beginning SQL the SEQUEL: Working with Advanced SQL Statements
AND and OR...Or OR and And - BrainDump
So you made it through the first tutorial and now you are back for more. Well buckle up for the ride, because this episode teaches you the glories of advanced SQL statements. By the end of this article you'll be able to sort data, join data, you name it.
If it's any comfort, that title hurt my head typing it as much as it did yours reading it. In the previous tutorial we spoke about the WHERE CLAUSE and its uses. Here, we will go a little more in-depth and add some power to it using the AND and OR operators.
AND
Say you wanted to list all the people in our employee database that had the first name Homer and the last name Sampson (if you remember in the first tutorial I had you add Homer's twin brother, Homer, to the table). One way we could do this is by joining the WHERE clause with the AND operator (think Voltron with words).
SELECT * from EMPLOYEES
WHERE FirstName='Homer'
AND LastName='Sampson';
The above sample would return the following dataset:
First Name
Last Name
Position
Salary
Homer
Sampson
CEO
$75,000
Homer
Sampson
CFO
$75,000
So let's say that Homer Sampson has a daughter, we'll call her, I don't know...Liza (to avoid a lawsuit from Matt Groening and Sam Simon). She isn't married yet because she is a high-powered business woman, devoted to her job, so her last name is still Sampson. Her salary is a little more than her father's, because she is the CTO and daddy's little baby. So let's give her $85,000 a year. Go ahead and add her to the employee table.
OR
Now that we have added Liza Sampson to our employee table, let's do some more coding. In this example, we want to list all people with either the first name Liza, or the last name of Sampson.
SELECT * from EMPLOYEES
WHERE FirstName="Liza'
OR LastName='Sampson";
Here's how that should look in your table:
First Name
Last Name
Position
Salary
Homer
Sampson
CEO
$75,000
Homer
Sampson
CFO
$75,000
Liza
Sampson
CTO
$85,000
Lastly, you can combine the might of the AND and OR statements. I know -- how can one man wield that much power? Well you can -- and will -- with the following code.