appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Set operations, NULLs and dates

Lesson 4 of 410 minIntermediate

Combine results, handle missing values and group by time periods.

Combining results

  • UNION stacks two results and removes duplicate rows.
  • UNION ALL stacks them and keeps duplicates. It is faster, so use it when duplicates are impossible or wanted.
  • INTERSECT keeps rows found in both. EXCEPT (called MINUS in 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.

1. Which operator keeps duplicate rows when stacking two queries?
2. What does COUNT(phone) count?
HintUse IS NULL, not = NULL.

Key terms