← Python lessons

SQL AND

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

SQL AND joins two conditions in a WHERE clause. A row is kept only if both conditions are true for it.

The examples below use this books table. Change a query and press Run to see its result.

Table: books

titleauthorgenrecover
WonderR. J. Palaciodramapaperback
MatildaRoald Dahlfantasyhardback
HolesLouis Sacharadventurepaperback
The BFGRoald Dahlfantasypaperback
BoyRoald Dahlmemoirhardback

Keep rows that match two conditions with AND

Write AND between the two conditions. This query keeps the books by Roald Dahl that are also fantasy:

SELECT title, author, genreFROM booksWHERE author = 'Roald Dahl'  AND genre = 'fantasy';

Only Matilda and The BFG are in the result. Boy is by Roald Dahl, but it is not fantasy, so it is left out. One true condition is not enough.

Add more conditions with AND

Each extra AND adds one more condition, and a row must pass all of them. Putting each condition on its own line keeps the query easy to read:

SELECT title, coverFROM booksWHERE author = 'Roald Dahl'  AND genre = 'fantasy'  AND cover = 'paperback';

Only The BFG passes all three conditions, so it is the only row in the result.

Note: The ; goes once, at the very end of the query, after the last condition.

See also: SQL WHERE.

Your turn

Add a condition with AND so the query counts only the books by Roald Dahl whose cover is hardback.

🎯 Goal — make your query show exactly:
COUNT(*)
--------
2
(1 row)
-- add a second condition with AND, and move the ; to the endSELECT COUNT(*)FROM booksWHERE author = 'Roald Dahl';