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.

String query = "";
query += "SELECT name ";
query += "FROM products ";
query += "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. show(db, query) prints your rows, and your query must make it print exactly this:

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

Your task: the connection db to shop.db and the empty string query are already there. Add to 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 inside the Java string. 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.


STEP 1 OF 4
    Ctrl + Enter to check