Set operations, NULLs and dates
Combine results, handle missing values and group by time periods.
Combining results
UNIONstacks two results and removes duplicate rows.UNION ALLstacks them and keeps duplicates. It is faster, so use it when duplicates are impossible or wanted.INTERSECTkeeps rows found in both.EXCEPT(calledMINUSin Oracle) keeps rows of the first that are not in the second.
Both queries must return the same number of columns with compatible types, in the same order.
NULL is not a value
NULL means unknown or missing. Any comparison with NULL is unknown, so use IS NULL and IS NOT NULL, never = NULL.
SELECT COALESCE(phone, 'no phone') AS phone FROM users;
SELECT COUNT(*) AS rows, COUNT(phone) AS with_phone FROM users;COALESCE returns its first non-NULL argument. COUNT(column) ignores NULLs, while COUNT(*) counts rows.
Grouping by time
-- PostgreSQL
SELECT date_trunc('month', created_at) AS month, SUM(total)
FROM orders
GROUP BY 1
ORDER BY 1;NoteDate functions differ between databases (date_trunc in PostgreSQL, DATE_FORMAT in MySQL, strftime in SQLite). Store timestamps in UTC and convert when you display them.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.