A join puts tables side by side. Set operations stack two query results on top of each other. The queries must return the same number of columns, in the same order and of the same kinds; the column names come from the first one.
UNION ALL keeps every row from both. UNION also removes duplicate rows, which costs a sort, so use UNION ALL unless you need the duplicates gone. Everyone the shop knows by name, labelled:
SELECT 'customer' AS kind, name FROM customers WHERE city = 'Boston'
UNION ALL
SELECT 'staff', name FROM staff WHERE role = 'Sales'
ORDER BY kind, name;
Returns
kind | name
---------+-----
customer | Dev
customer | Gus
staff | Kai
staff | Mia
(4 rows)
ORDER BY goes once, at the very end, and sorts the combined result.
INTERSECT keeps the rows that both queries return, and EXCEPT the rows the first returns that the second doesn't (Oracle calls it MINUS). Customers who both ordered and logged in, then customers who ordered but never logged in:
SELECT customer_id FROM orders
INTERSECT
SELECT customer_id FROM logins;
Returns
customer_id
-----------
1
2
3
4
(4 rows)
SELECT customer_id FROM orders
EXCEPT
SELECT customer_id FROM logins;
Returns
customer_id
-----------
5
6
(2 rows)
Both remove duplicates, like UNION. Unlike NOT IN, EXCEPT treats NULLs as equal to each other, so a NULL in the second list doesn't wipe out the result. It's a tidy way to compare two lists: what's in last week's export but not this week's, for example.
Practice
Every customer id that appears in orders or in logins (or both), each once.