Start learning free

LESSON 40 OF 173 · BACKEND: SQL

Match Text with LIKE

Practice

A WHERE with = keeps a row only when the text is exactly the same: name = 'Pen' finds the Pen and nothing else. To find every name that starts with a letter, or has a letter inside, SQL has LIKE: it compares the text with a pattern.

In a pattern, % stands for any text, even none. The pattern has to fit the whole text, so where you put the % matters: 'T%' is a T, then anything; '%t' is anything, then a t at the very end; '%e%' has an e anywhere.

var query = "SELECT name " +
    "FROM products " +
    "WHERE name LIKE '%t' ";

This query keeps the names that end with t: Plant and Teapot. You can join two tests with OR: a row is kept when either one is true. The check prints your rows with show(db, query), and your query must print exactly this:

name | price
Notebook | 7
Pen | 2
Plant | 15
Teapot | 22
(4 rows)

Your task: the connection db to shop.db is already there. Write query, one clause per line: the name and price of the products whose name starts with P or contains an o.


Assignment
Follow the Coding Tutorial to write the query one line at a time: SELECT, FROM, a WHERE with LIKE, then an OR with a second pattern.


Hint
Patterns go in single quotes. For names that start with P, the % goes after the P; to find an o anywhere, put a % on both sides of it. End each string with a space so the clauses don't run together, join the lines with +, and end the last one with ;.


STEP 1 OF 4
    Ctrl + Enter to check