Menu

SQL

Combining Conditions in SQL

You can join two or more conditions in a WHERE clause using AND or OR. The keyword you choose changes which records are returned, so the two are not interchangeable.

AND needs every condition to be true

AND returns a record only when every combined condition is true. For this table:

ClubDayMembersSpaces
Chess ClubTuesday186
Drama ClubTuesday220
Coding ClubThursday154
Art ClubTuesday122
Science ClubFriday200

SELECT Club FROM TblClubs WHERE Day = "Tuesday" AND Spaces > 0 returns Chess Club and Art Club. Drama Club is on Tuesday, but it fails the second condition because it has no spaces left.

OR needs at least one condition to be true

OR returns a record when at least one combined condition is true. Using the same table, SELECT Club FROM TblClubs WHERE Day = "Tuesday" OR Spaces > 0 returns Chess Club, Drama Club, Coding Club and Art Club. Drama Club is included because its day is Tuesday, even though it has no spaces. Science Club is left out because both parts are false. The AND query returned two clubs and the OR query returned four, so swapping the keywords would give different records.

Each side is a full comparison

Write a complete comparison on each side of AND or OR, so the field name is repeated: Day = "Tuesday" AND Spaces > 0. Writing Day = "Tuesday" AND > 0 does not work, because the second part does not say what to compare. The same rule applies with OR.

Practise this