← Вернуться к курсу: SQL and databases from scratch

UNION, CASE and week 5 review

Видео скоро появится

This lesson closes the week with two very different but equally useful tools. UNION and its relatives combine the results of several queries one below the other, and CASE brings conditional logic inside a query, something like an if. With them you will be able to classify data, create reports with your own categories and do conditional counts that used to seem impossible in SQL.

UNION, INTERSECT and EXCEPT

While a JOIN adds columns from another table, UNION stacks rows. The combined queries must have the same number of columns and compatible types; the column names are taken from the first query. UNION removes duplicate rows (and therefore does extra work); UNION ALL keeps them and is faster, so use it when you know there are no duplicates or you do not care. INTERSECT returns only the rows present in both results, and EXCEPT those from the first that are not in the second (in Oracle it is called MINUS; MySQL supports them since 8.0.31).

sql
-- One list with the name of every person and product, tagged by type
SELECT name, 'customer' AS kind FROM customers
UNION ALL
SELECT name, 'product' AS kind FROM products
ORDER BY kind, name;

-- Customers who never ordered (EXCEPT)
SELECT customer_id FROM customers
EXCEPT
SELECT customer_id FROM orders;

-- Customers who have both a delivered and a pending order (INTERSECT)
SELECT customer_id FROM orders WHERE status = 'delivered'
INTERSECT
SELECT customer_id FROM orders WHERE status = 'pending';

CASE: conditional logic

CASE evaluates conditions in order and returns the result of the first one that holds; if none holds, it returns what you put in ELSE (or NULL if there is no ELSE). It always closes with END. It can go in SELECT to create new columns, in ORDER BY to sort with your own criterion and inside aggregates. Since conditions are evaluated from top to bottom, order matters: put the most specific first.

sql
-- Price tiers and stock status
SELECT name, price,
       CASE
         WHEN price < 10  THEN 'cheap'
         WHEN price < 100 THEN 'medium'
         ELSE 'premium'
       END AS price_tier,
       CASE WHEN stock = 0 THEN 'out of stock' ELSE 'available' END AS availability
FROM products
ORDER BY price;

-- Count products per tier: group by the CASE expression
SELECT CASE WHEN price < 10 THEN 'cheap' WHEN price < 100 THEN 'medium' ELSE 'premium' END AS price_tier,
       COUNT(*) AS products
FROM products
GROUP BY 1
ORDER BY products DESC;

CASE inside aggregates

Combining SUM with CASE lets you count or sum only the rows that meet a condition, and get several counts in a single row, like a small dashboard. The technique works in every engine. Each CASE returns 1 when the row counts and 0 when it does not, and SUM adds up those ones. PostgreSQL also has FILTER, which we saw earlier, but CASE is portable to MySQL and SQLite.

sql
SELECT SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS delivered,
       SUM(CASE WHEN status = 'pending'   THEN 1 ELSE 0 END) AS pending,
       SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM orders;

To close the week, remember when to use each tool. If you need columns from another table, use JOIN; if you need to stack rows from similar queries, use UNION; if you need a value that depends on a condition, use CASE; and if you need the result of one query inside another, use a subquery or a CTE. Choosing the right tool is more important than memorizing syntax, and that choice is learned by solving many different problems on the same database.

Проверьте себя

Вопрос 1 из 6

What is the difference between UNION and UNION ALL?

✎ Мои заметки

Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов

← НазадДалее →