Skip to content

Text and set operations

Clean and split text, match patterns, and combine result sets with UNION, INTERSECT and EXCEPT.

Practise: 4 questions

When you need it

"Normalise the email domain", "customers whose name starts with a vowel", "emails that appear in both lists", "users in January but not February", "stack two tables". Words that signal it: "contains", "starts with", "domain", "trim", "both lists", "either", "only in".

Text work turns messy strings into something you can group by. Set operations combine whole result sets by row.

The shape of the query

Text cleanup:

select lower(trim(col)) as clean,
       split_part(email, '@', 2) as domain,
       col ilike 'a%' as starts_with_a
from t;

Set operations:

select col from a
union all          -- keep every row
select col from b;

Step by step:

  1. Clean first, then group or compare. lower(trim(x)) fixes most casing and space noise.
  2. Pull out parts with split_part, substring or position.
  3. For matching, like with % (any run of characters) and _ (one character), or ilike for case-insensitive.
  4. For sets, both queries must return the same number of columns with compatible types, in the same order.
select split_part(email, '@', 2) as domain,
       count(*) as customers
from customers
where email is not null
group by 1
order by customers desc, domain
limit 5;

Customers in one list and not another, using except:

select customer_id from customers
except
select customer_id from orders
order by customer_id
limit 10;

Traps interviewers look for

Variations

In other warehouses

Practise text and set operations