← Python lessons

SQL LIKE

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

SQL LIKE keeps the rows whose text matches a pattern. In the pattern, % stands for any characters, so LIKE 'JF-2%' keeps text that starts with JF-2.

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

Table: books

titlecode
WonderJF-210
MatildaJF-245
HolesJF-318
BoyNF-102
Boy OverboardJF-221
CoralineJF-290

Keep text that starts with some characters

Write the column, then LIKE, then the pattern in single quotes. Put % after the start you know. This query keeps the books whose shelf code starts with JF-2:

SELECT title, codeFROM booksWHERE code LIKE 'JF-2%';

The result has four books. Holes is left out, because JF-318 starts with JF-3.

Use LIKE as one condition among others

LIKE is one condition, so it can follow another one with AND:

SELECT title, codeFROM booksWHERE title LIKE 'Boy%'  AND code LIKE 'JF-%';

Only Boy Overboard is in the result. Boy starts with Boy, but its code starts with NF-.

Note: Without %, the pattern must match the whole text: LIKE 'JF-2' keeps no rows here.

See also: SQL WHERE.

Your turn

Add a WHERE line with LIKE so the query shows only the books whose code starts with NF-.

🎯 Goal — make your query show exactly:
title
-----
Boy
(1 row)
-- add a WHERE line after FROM, and move the ; to the endSELECT titleFROM books;