SQL Practice Logo

SQLPractice Online

Pattern Matching (LIKE, REGEX): Examples

Module: Advanced Filtering

Basic LIKE Patterns

basic

Find customers whose names start with "John"

SELECT customer_id, name, email

FROM customers

WHERE name LIKE 'John%'

ORDER BY name;

customer_id | name | email

101 | John Smith | john.smith@email.com

102 | Johnny Doe | johnny@email.com

103 | Johnson Lee | johnson.lee@email.com

LIKE with % wildcard matches any characters after "John". Finds John, Johnny, Johnson, etc.

All

Underscore Wildcard

intermediate

Find products with 4-character SKU codes

SELECT product_id, sku, product_name

FROM products

WHERE sku LIKE '____'

ORDER BY sku;

product_id | sku | product_name

1 | ABCD | Widget A

2 | EFGH | Widget B

3 | WXYZ | Widget C

Four underscores match exactly 4 characters. Each _ matches one character.

All

Email Domain Filtering

intermediate

Find all Gmail users

SELECT user_id, email

FROM users

WHERE email LIKE '%@gmail.com'

ORDER BY email;

user_id | email

101 | alice@gmail.com

102 | bob@gmail.com

103 | charlie@gmail.com

% before @gmail.com matches any characters before the domain. Finds all Gmail addresses.

All

REGEX Pattern Matching (PostgreSQL)