15. Like

The SQL like operator allows you to compare text in a column to a pattern. like allows the use of two different wildcard operators:

  • % matches zero or more characters
  • _ (underscore) matches exactly one character

Let's look at an example. Say we want to get a list of all source codes that fit this pattern:

  • M in the first position
  • Any 2 characters in positions 2-3
  • 03 in positions 4-5
  • Any number of characters after that

In SQL, we can do this as follows:

select
    *
from source_codes
where source_code like 'M__03%'

This query tells the database, "Give me all rows from the source code table where the source code starts with M, followed by any two characters, followed by 03, with any number of characters (including 0) after the 03." All of these would match this pattern:

  • M2703
  • MZY03NFK
  • MMM03KDFJHO3434ER990

The most important thing to remember about like is that the _ wildcard matches exactly one character while the % operator matches zero or more characters.

Exercise 1: Simple like

Write an SQL statement using like to select the account ID, first name, and last name for all donors in the database whose first name begins with "Alex".

No Results

Exercise 2: Complex like

Save the Birds and Trees' source codes are structured such that positions 2-3 represent two-digit calendar years and positions 4-5 represent two-digit calendar months. Write a query using like to identify all source codes from April 2024.

No Results