← All lessons
SQL from zero · Lesson 7 of 10

Searching and changing text

= needs the whole text to match. LIKE matches a pattern, where % stands for any number of characters (even none) and _ for exactly one. Products whose name starts with "Rain":

SELECT name
FROM products
WHERE name LIKE 'Rain%';
Returns
name
----------
Rain boots
Raincoat
(2 rows)

'%book%' means "book" anywhere in the text, and '%s' means ending in s:

SELECT name
FROM products
WHERE name LIKE '%s';
Returns
name
----------
Rain boots
Binoculars
(2 rows)

In SQLite, LIKE ignores capital letters for plain English letters, so 'rain%' would find the same rows. PostgreSQL's LIKE doesn't ignore them and it has ILIKE for that. When it matters, make both sides the same case first, which works everywhere: LOWER(name) LIKE 'rain%'.

Functions take a value in brackets and give back a new one. UPPER and LOWER change the case, and LENGTH counts the characters:

SELECT name, UPPER(name), LENGTH(name)
FROM customers
WHERE city = 'Boston';
Returns
name | UPPER(name) | LENGTH(name)
-----+-------------+-------------
Dev  | DEV         | 3
Gus  | GUS         | 3
(2 rows)

|| (two upright bars) joins pieces of text together. SQL Server uses + instead, and MySQL uses the CONCAT() function. If any piece is NULL, the whole result is NULL.

SELECT name || ' lives in ' || city
FROM customers
WHERE city = 'Denver';
Returns
name || ' lives in ' || city
----------------------------
Ben lives in Denver
Eve lives in Denver
(2 rows)

A few more you'll see: TRIM(x) takes spaces off both ends, REPLACE(x, 'a', 'b') swaps every a for b, and SUBSTR(x, 1, 3) takes three characters starting from the first.

Practice

The names of the products that start with B.

The tables
  • customers (id, name, city, joined)
  • products (id, name, category, price)
  • orders (id, customer_id, ordered_on, status)
  • order_items (order_id, product_id, qty)
  • signups (id, email, name, signed_up_at)
  • payments (id, order_id, amount, currency, paid_at)
  • events (id, received_at, payload (JSON text))
  • staff (id, name, role, manager_id, salary, hired)
  • logins (customer_id, day)
More info

Quick reference

x LIKE 'a%'Pattern match: % any characters, _ exactly one.
UPPER(x), LOWER(x)Capitals, small letters.
LENGTH(x)How many characters.
a || bJoin text (+ in SQL Server, CONCAT() in MySQL).
TRIM, REPLACE, SUBSTRStrip spaces, swap text, take part of it.

The other AI and data engineering courses