-
Notifications
You must be signed in to change notification settings - Fork 3
postgres patern matching like similar regexp
ghdrako edited this page May 1, 2024
·
1 revision
- https://www.postgresql.org/docs/current/functions-matching.html
- https://data-nerd.blog/2022/06/14/beyond-like-operator-advanced-pattern-matching-in-postgresql/
SELECT *
FROM employees
WHERE email LIKE '%@gmail.com';
SELECT *
FROM users
WHERE
email LIKE '%@gmail.com'
OR email LIKE '%@yahoo.com'
Like LIKE
, SIMILAR TO
uses _
and %
as wildcard characters denoting any single character and any string, respectively.
SELECT *
FROM users
WHERE email SIMILAR TO '%@gmail.com|%@yahoo.com'
SELECT *
FROM users
WHERE email ~ '@gmail\.com$|@yahoo\.com$'
PostgreSQL has an ANY operator that is used to compare a scalar value with a set of values returned by a subquery. And in this case, the sub-query is an array for patterns to match.
SELECT *
FROM users
WHERE email ~ ANY(ARRAY['@gmail\.com$', '@yahoo\.com$'])
This query uses the ANY operator to match against an array of patterns. If an email matches any of the patterns, the condition will be true. This approach is easier to work with from a host language such as Python:
with connection.cursor() as cursor:
cursor.execute('''
SELECT *
FROM users
WHERE email ~ ANY(ARRAY%(patterns)s)
''' % {
'patterns': [
'@gmail\.com$',
'@yahoo\.com$',
],
})
Unlike the previous approach that used SIMILAR TO, using ANY you can bind a list of patterns to the variable.
Test