← Python lessons

SQL WHERE

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

SQL WHERE keeps only the rows of a table that match a condition. It goes after FROM, and the other rows are left out of the result.

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

Table: books

titleauthorpages
WonderR. J. Palacio320
MatildaRoald Dahl240
HolesLouis Sachar272
The BFGRoald Dahl208

Keep rows that match with WHERE

WHERE author = 'Roald Dahl' keeps only the rows whose author is exactly Roald Dahl:

SELECT title, authorFROM booksWHERE author = 'Roald Dahl';

Only the two books by Roald Dahl are in the result. A text value goes inside single quotes, 'like this', and the ; moves to the end of the query.

Match capital letters exactly

Text must match exactly, capital letters included. Here the query asks for 'roald dahl' in small letters:

SELECT title, authorFROM booksWHERE author = 'roald dahl';

The result is (0 rows): no row matched. The table stores 'Roald Dahl' with capitals, and 'roald dahl' is a different text.

Note: SQL keywords like WHERE work in any case. Only the text inside the quotes must match the table exactly.

See also: SQL SELECT and FROM.

Your turn

Add a WHERE line so the query shows only the books by Louis Sachar.

🎯 Goal — make your query show exactly:
title | pages
------+------
Holes | 272
(1 row)
-- add a WHERE line after FROM, and move the ; to the endSELECT title, pagesFROM books;