When joining rows from two tables using SET operators, which SQL clause is allowed to be used only at the end?
order by
column names in result set are decided by column names present in the first query.
Avoid retrieving IDs in select clause, since they lose their meaning in the result set after UNION.
Find employees who are not customers at the same time.
Hint: use minus (except) clause
select firstname, lastname from employees except select firstname, lastname from customers;
Find employees who are also customers.
select firstname, lastname
from employees
intersect
select firstname, lastname
from customers
You copied data from table X in DB A to table Y in DB B.
How to check if all the data was moved completely?
select * from A.X except select * from B.Y
The count of above result set must be zero (empty).
Your source table gets data inserted from application, and on each insert you need to check if this row (entry) is new or not.
For example, unique visits on a website.
Use EXCEPT operator to fetch unique user IDs.
MINUS
Find the c.id and c.first_name of customers who bought iphone and/or samsung but never xiomi.
– customers: Id(int), Name(varchar)
– orders: Id(int), Customer_id(int), Product_id(int)
– products: Id(int), Name(varchar)
-- Customers who bought iPhone or Samsung
SELECT DISTINCT c.id, c.first_name
FROM customers c
JOIN orders o ON c.id = o.customer_id
JOIN products p ON o.product_id = p.id
WHERE p.name IN ('iphone','samsung')
EXCEPT
-- Customers who bought Xiaomi
SELECT DISTINCT c.id, c.first_name
FROM customers c
JOIN orders o ON c.id = o.customer_id
JOIN products p ON o.product_id = p.id
WHERE p.name = 'xiomi';