Sub topic 3
Matching patterns with LIKE and ILIKE
This chapter assumes you can write SELECT, WHERE and GROUP BY, know PostgreSQL's text and varchar types, and can run queries in psql. It covers pattern matching, splitting and joining text, regular expressions, safe SQL text building, encoding effects, and indexes for text searches.
Pattern matching with LIKE and ILIKE
LIKE tests whether a string matches a pattern. In the pattern, % matches any run of characters and _ matches exactly one character. ILIKE works the same way but ignores case.
SELECT name
FROM products
WHERE name LIKE 'Pro%';
SELECT name
FROM products
WHERE name ILIKE '%phone%';Splitting strings and aggregating rows into text
split_part returns one field from a delimited string. string_to_array returns all fields as an array. string_agg joins values from many rows into one string.
SELECT split_part('a,b,c', ',', 2) AS second_item,
string_to_array('a,b,c', ',') AS items;
SELECT department,
string_agg(name, ', ' ORDER BY name) AS members
FROM employees
GROUP BY department;Regular expressions: ~, regexp_replace and regexp_match
The ~ operator tests a POSIX regular expression. regexp_replace rewrites matched text, and regexp_match returns the captured groups as an array. PostgreSQL arrays start at index 1.
SELECT 'abc123' ~ '^[a-z]+[0-9]+$' AS matches,
regexp_replace('2026-11-27', '(\d+)-(\d+)-(\d+)', '\3/\2/\1') AS reordered,
(regexp_match('order #1234 shipped', '#(\d+)'))[1] AS order_number;Building text with format, quote_ident and quote_literal
format builds a string from a template. %s inserts text as is, %I quotes an identifier, and %L quotes a literal value. Use %I and %L when names or values come from user input, because they protect the query from injection.
SELECT format('Hello, %s! Table: %I, value: %L', 'Ana', 'My Table', 'it''s') AS message;Encoding and collation effects on string results
Length depends on what you measure. In a UTF8 database, char_length('héllo') returns 5 characters, but octet_length('héllo') returns 6 bytes because é takes two bytes. Collation also changes sort order: in an en_US collation, a sorts before B, but in the C collation, B sorts before a.
Indexing for lower(), LIKE and trigram searches
A B-tree index on lower(email) supports case-insensitive equality, but only when the query uses the same expression. For ILIKE '%phone%', a trigram index from the pg_trgm extension is needed.
CREATE INDEX idx_users_email_lower ON users (lower(email));
SELECT id
FROM users
WHERE lower(email) = lower('[email protected]');
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX idx_products_name_trgm
ON products USING gin (name gin_trgm_ops);Exercise
Which index helps the query WHERE name ILIKE '%phone%' on the products table?
Show answer
A trigram GIN index on name, created with gintrgmops after enabling pg_trgm. A plain B-tree index cannot help with a leading wildcard.