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:
- Clean first, then group or compare.
lower(trim(x))fixes most casing and space noise. - Pull out parts with
split_part,substringorposition. - For matching,
likewith%(any run of characters) and_(one character), orilikefor case-insensitive. - 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
UNIONversusUNION ALL.UNIONremoves duplicates, which costs a sort and can hide real repeats. If duplicates cannot happen or you want them, useUNION ALL. Counting after aUNIONcan give a different answer.- Column order, not names. Set operations match columns by position. Swapping two columns of the same type produces wrong results with no error.
- NULLs in sets.
UNION,INTERSECTandEXCEPTtreat two NULLs as equal, unlike=. That is usually helpful and sometimes a surprise. EXCEPTis one way.a except bis notb except a. For a symmetric difference, combine both.- Case and spaces.
'Gmail.com 'and'gmail.com'are different strings. Clean before you compare. LIKEwith special characters.%and_in the data are wildcards in the pattern. Escape them, or usestarts_withstyle functions when available.- Leading wildcard.
like '%abc'cannot use an index. Fine for a screen, worth saying in a real job. - Counting characters.
lengthcounts characters in PostgreSQL. In some engines it counts bytes. Know which.
Variations
- Split into rows.
unnest(string_to_array(tags, ','))turns a delimited string into one row per piece. - Extract with a regular expression.
substring(col from '[0-9]+')orregexp_replaceto strip characters. - Concatenate.
a || ' ' || b, orconcat_ws(' ', a, b), which skips NULLs. INTERSECT. Rows present in both queries, with duplicates removed.- Union to stack months. Build one table from several tables of the same shape, adding a literal column for the source.
In other warehouses
- Snowflake, BigQuery, SQL Server and Databricks support
UNION,INTERSECTandEXCEPT. BigQuery requiresUNION ALLorUNION DISTINCT,EXCEPT DISTINCTandINTERSECT DISTINCTexplicitly. Snowflake also acceptsMINUS. - MySQL supports
UNIONeverywhere, andINTERSECTandEXCEPTfrom version 8.0.31. ILIKEworks in PostgreSQL, Snowflake, Redshift and Databricks. In BigQuery and SQL Server writelower(col) like 'a%'.- Splitting.
split_partexists in PostgreSQL, Snowflake and Redshift. BigQuery usesSPLIT(email, '@')[OFFSET(1)]. SQL Server has nosplit_part, so useSUBSTRINGwithCHARINDEX.