DSA Factory
Free SQL queries lessonsSQL queries · Stage 1 · Shaping the results · Step 3

Match text with patterns

Find rows by part of a text with LIKE, and join or reshape text with functions. About 8 minutes.

LIKE finds text by shape

Equals needs the whole value. When you only know part of it, a book whose title starts with "The", a city ending in "pur", use LIKE with a pattern.

Two characters are special. The percent sign stands for any run of characters, even none. The underscore stands for exactly one character. Everything else must match itself.

%: any run of characters. _ is exactly one.
In code
city LIKE 'S%'      -- starts with S
city LIKE '%pur'    -- ends with pur
city LIKE '%an%'    -- contains an
code LIKE 'B__'     -- B and two more
WHERE city LIKE '%pur'
stations
idcity
1Jaipur
2Pune
3Udaipur
4Mumbai
5Kanpur

Jaipur ends in pur, and % covers the Jai. Kept.

Move 1 of 5

Reshape text with functions

Functions work on the text in a column. lower() and upper() change the case, and length() counts the characters. Two bars, ||, join pieces together.

One thing to watch: in SQLite, LIKE ignores capital letters for English letters, so 'an' matches 'Anan'. Postgres is case-sensitive unless you ask otherwise, and MySQL depends on its settings. Also, joining anything with NULL gives NULL.

|| with NULL: the whole result becomes NULL.
In code
SELECT upper(name) || ' (' || city || ')'
FROM members;
Quick check

Which value does name LIKE 'R_n' match?

  1. ARon
  2. BRohan
  3. CRn
Show the answer

Ron. R, then exactly one character, then n.

Your problem

Names with an

The students table has one row per student. Show the name of every student whose name contains the letters an anywhere, in any capitalisation, A to Z.

Tables
students(id, name, branch)

Up to 2,000 students

Write the query in your browserFree account, no card. Your query runs on real tables, with hints if you get stuck, and your progress is saved.
Sign up free to solve