Previous
SELECT Statement 
Next
Sorting the Results using ORDER BY 
SQL(Structured Query Language) Tutorial
WHERE is the new if

'WHERE' is the new 'if'

All languages I know use 'if' for conditions - except SQL. It uses where for conditional statements. For example, let's say we need the details of just Bart...

SELECT * FROM Character WHERE name='Bart Simpson'

If you want to find only the people with above average intelligence, try this query...

SELECT * FROM Character WHERE iq>100

AND/OR

As is all major languages, you can combine conditions using AND/OR. Say you want all the male members with above average intelligence...

SELECT * FROM Character WHERE iq>100 AND sex='m'

If you want the data of all people associated with the school, do this...

SELECT * FROM Character WHERE job='Student' OR job='Principal' OR job='Groundskeeper' or job='Teacher'

You can change the order of the statements using brackets...

SELECT * FROM Character WHERE (name LIKE '%Simpson' AND iq>100) OR name='Bart Simpson'

Operaters

OperatorMeaningExample
=is equal toname='Bart Simpson'
!=is not equal tojob != 'Student'
<is less than iq < 100
<= is less than or equal to iq <= 100
>is greater than iq > 100
>=is greater than or equal to iq => 100
LIKEstring matchname LIKE '%Simpson'

The LIKE operator matches string. For example, this query can be used to find all the Simpsons...

SELECT * FROM Character WHERE name LIKE '%Simpson'

The '%' is a wild card - means any string(think '.*' if you know regular expression). 'Homer%' means that the string must start with 'Homer' - then anything goes. '%Simpson' means that the string must end with 'Simpson'. You can search for middle parts of a string as well...

SELECT * FROM Character WHERE name LIKE '%er%'

There are a few other operators as well - like REGEXP. But the above once are all you need for most things.

Previous
SELECT Statement 
Next
Sorting the Results using ORDER BY 
Subscribe to Feed