Skip to main content

Conditional statements part 2


Creating a query with only one condition is not sufficient. Sometimes we would like to check something more complicated. For that SQL (and many other programming languages) have the ANDOR, and NOT keywords to increase our ability to fetch the right result we need.

The AND and OR keywords are used like this:

SELECT col1, col2 
FROM table1
WHERE condition1 AND condition2 OR condition3 ...

We can stack as many conditions as we want together.


people

nameagegender
Joas13male
Holwa17male
Nohlas24female
Polar23male
Loopa18female

The AND keyword means that both conditions must be true; if either of them is not, then the condition will not be met.

For example, if we will write

SELECT * 
FROM people
WHERE gender = "female" AND age < 20

It means that we are looking for all records that the gender is "female" and the age is less than 20.

This will be the result:

nameagegender
Loopa18female

The OR keyword means that we want one of the conditions will be true.

For example, if we take the same example from above and change the AND keyword to OR

SELECT * 
FROM people
WHERE gender = "female" OR age < 20

It means that we are looking for all records that either the gender is female or the age is less than 20.

This will be the result:

nameagegender
Joas13male
Holwa17male
Nohlas24female
Loopa18female

The NOT keywords mean that we don't want the condition to be met.

For example, if we write:

SELECT * 
FROM people
WHERE NOT gender = "male"

This will be the result:

nameagegender
Nohlas24female
Loopa18female

Challenge

Easy