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

name age gender
Joas 13 male
Holwa 17 male
Nohlas 24 female
Polar 23 male
Loopa 18 female

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:

name age gender
Loopa 18 female

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:

name age gender
Joas 13 male
Holwa 17 male
Nohlas 24 female
Loopa 18 female

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:

name age gender
Nohlas 24 female
Loopa 18 female