Pattern matching with LIKE #
= only matches an exact value. When you need to match part of a text value, use LIKE together with a wildcard.
Syntax #
SELECT
column_name
FROM
table_name
WHERE
column_name LIKE pattern;
Two wildcard characters can be used inside pattern:
%matches any sequence of zero or more characters._matches exactly one character.
Example #
To find every customer whose first name starts with J, we put the % wildcard after it:
SELECT
*
FROM
customers
WHERE
first_name LIKE 'J%';
Result:
+----+------------+-----------+-----+--------+
| id | first_name | last_name | age | gender |
+----+------------+-----------+-----+--------+
| 2 | Jonathan | Dixon | 71 | F |
| 4 | Juan | Campos | 99 | F |
| 10 | Jennifer | Ross | 100 | M |
+----+------------+-----------+-----+--------+
'J%' matches any value that starts with J, no matter how many characters follow. If we instead wanted names that end with a letter, we'd put the % before it, e.g. '%n' matches Jonathan. LIKE is case-insensitive by default in SQLite, so 'j%' would match the same rows.
Exercise #
Write a query that retrieves all columns from the customers table, keeping only the rows where first_name starts with 'J'.
- The result has a
first_namecolumn. - The result contains exactly the rows where
first_namestarts with'J', and no others.
Solution
SELECT
*
FROM
customers
WHERE
first_name LIKE 'J%';
Basic Data Retrieval
Filtering Data
Aggregating Data
Joining Tables
Creating and Managing Tables
Transactions and Data Integrity