Pattern match

2 snippets across 2 stacks - Python, SQL

Also written as match patterns

PYPython

Match/Case Pattern Types

PY · Modern Features
Syntax
match value:
    case pattern:
        ...
Example
def describe(value):
    match value:
        case int(n) if n > 0:
            return f"positive int: {n}"
        case str(s) if len(s) > 5:
            return f"long string: {s!r}"
        case [first, *rest]:
            return f"list starting with {first}, {len(rest)} more"
        case {"type": "error", "code": code}:
            return f"error code {code}"
        case _:
            return "something else"

print(describe(42))
print(describe([1, 2, 3]))
print(describe({"type": "error", "code": 500}))
Output
positive int: 42
list starting with 1, 2 more
error code 500

Note Match/case supports literal, capture, sequence, mapping, class, guard (if), and OR (|) patterns. The _ wildcard matches anything.

SQLSQL

LIKE Pattern Matching

SQL · Filtering
Syntax
WHERE column LIKE 'pattern'
-- % = any number of characters
-- _ = exactly one character
Example
SELECT first_name, email
FROM users
WHERE email LIKE '%@gmail.com';
Output
-- All users with Gmail addresses

Note LIKE is case-sensitive in PostgreSQL but case-insensitive in MySQL (with default collation). PostgreSQL offers ILIKE for case-insensitive matching. A leading % prevents index usage.

Frequently asked questions

How does Python handle pattern match?
This task is covered in 2 stacks on this page: Python, SQL. The "Match/Case Pattern Types" snippet in Python uses `match value:`.
Which code does the Python example use?
The "Match/Case Pattern Types" snippet uses `match value:`, from the Modern Features section of the Python cheat sheet.
Which stacks cover "pattern match" on this page?
Python, SQL. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Match/Case Pattern Types": Match/case supports literal, capture, sequence, mapping, class, guard (if), and OR (|) patterns. The _ wildcard matches anything.