SQL OR
SQL OR joins two conditions in a WHERE clause. A row is kept if either condition is true for it. When you mix OR with AND, put brackets around the OR part.
The examples below use this books table. Change a query and press Run to see its result.
Table: books
| title | genre | cover |
|---|---|---|
| Wonder | drama | paperback |
| Matilda | fantasy | hardback |
| Holes | adventure | paperback |
| The BFG | fantasy | paperback |
| Boy | memoir | hardback |
| Coraline | drama | hardback |
Keep rows that match either condition with OR
Write OR between the two conditions. This query keeps the books that are fantasy or drama:
SELECT title, genreFROM booksWHERE genre = 'fantasy' OR genre = 'drama';The result has four books: the two fantasy books and the two drama books. One true condition is enough for OR.
Put brackets around OR when you mix it with AND
Brackets make the database check the OR part as one group, like brackets in maths. This query keeps the paperbacks that are fantasy or drama:
SELECT title, genre, coverFROM booksWHERE cover = 'paperback' AND (genre = 'fantasy' OR genre = 'drama');Only Wonder and The BFG are in the result. Each one is a paperback, and its genre is one of the two.
See what goes wrong without brackets
Here is the same query without the brackets:
SELECT title, genre, coverFROM booksWHERE cover = 'paperback' AND genre = 'fantasy' OR genre = 'drama';Now Coraline is in the result too, though it is a hardback. AND is checked before OR, so every drama book gets through, whatever its cover.
See also: SQL AND.
Your turn
The query shows the hardbacks. Add a line so it shows only the hardbacks whose genre is memoir or drama.
title ----- Boy Coraline (2 rows)
-- add an AND line with OR in brackets, and move the ; to the endSELECT titleFROM booksWHERE cover = 'hardback';