Skip to content

SQL AND, OR and NOT Operators

A WHERE clause can test more than one condition at a time. Three operators join conditions together:

  • AND keeps a row only when every condition holds.
  • OR keeps a row when at least one condition holds.
  • NOT reverses a condition, keeping the rows where it does not hold.
SELECT column1, column2
FROM table_name
WHERE condition1 AND condition2;

The examples use the Productions table from the example database.

To find the drama series made in the UK, both conditions must hold:

SELECT Title
FROM Productions
WHERE Country = 'UK' AND Format = 'Drama series';
Title
The Lantern Keepers
Six Bells

Quarry Lane is made in the UK but is a feature film, so it is left out.

To find the productions that are either documentaries or made on a budget under five million, one condition is enough:

SELECT Title, Format, Budget
FROM Productions
WHERE Format = 'Documentary' OR Budget < 5000000;
Title Format Budget
Saltmarsh Feature film 3,900,000
Fennick’s Return Documentary 850,000

Fennick’s Return meets both conditions, but still appears only once.

To find every production made outside the UK:

SELECT Title, Country
FROM Productions
WHERE NOT Country = 'UK';
Title Country
Saltmarsh Ireland
Fennick’s Return Canada

WHERE Country <> 'UK' gives the same result.

When one WHERE clause mixes AND and OR, the database works out every AND before any OR, much as multiplication comes before addition. Brackets let you say which conditions belong together.

To find the drama series made in either the UK or Canada:

SELECT Title, Country
FROM Productions
WHERE Format = 'Drama series' AND (Country = 'UK' OR Country = 'Canada');
Title Country
The Lantern Keepers UK
Six Bells UK

Without the brackets, the same words ask a different question: drama series made in the UK, or anything made in Canada. The Canadian documentary then slips in:

SELECT Title, Country
FROM Productions
WHERE Format = 'Drama series' AND Country = 'UK' OR Country = 'Canada';
Title Country
The Lantern Keepers UK
Six Bells UK
Fennick’s Return Canada