Joins Lesson 16 of 21
SQL Subqueries and UNION
Use a query inside another query — in WHERE with IN and comparisons, in FROM as a temporary table — check existence with EXISTS, and stack results with UNION.
A subquery is a query inside another query, written in parentheses. The inner query runs first, and its result is used by the outer query. Subqueries let you answer questions in steps.
Subquery that returns one value
SELECT student_id, score
FROM grades
WHERE subject = 'Math'
AND score > (SELECT AVG(score) FROM grades WHERE subject = 'Math')
ORDER BY score DESC;
The inner query computes the average (85.3); the outer query keeps scores above it. You can't write score > AVG(score) directly, so this is the standard solution.
SELECT name, price
FROM products
WHERE price = (SELECT MAX(price) FROM products);
Subquery that returns a list: IN
SELECT name
FROM products
WHERE id IN (
SELECT oi.product_id
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
WHERE o.status = 'utang'
);
SELECT name
FROM customers
WHERE barangay = (SELECT barangay FROM customers WHERE name = 'Maria Santos')
AND name <> 'Maria Santos';
EXISTS
EXISTS checks whether the subquery returns any rows. It's often used with a correlated subquery, one that refers to the outer row:
SELECT c.name
FROM customers c
WHERE EXISTS (
SELECT 1 FROM orders o
WHERE o.customer_id = c.id AND o.status = 'paid'
);
For each customer, the inner query looks for a paid order belonging to that customer (o.customer_id = c.id). NOT EXISTS finds the opposite.
Subquery in FROM
A subquery can act like a temporary table. Give it an alias:
SELECT ROUND(AVG(order_total), 2) AS average_order
FROM (
SELECT oi.order_id, SUM(oi.qty * p.price) AS order_total
FROM order_items oi
JOIN products p ON p.id = oi.product_id
GROUP BY oi.order_id
) AS totals;
Step 1 (inner): compute the total of each order. Step 2 (outer): average those totals. Some questions need two levels of grouping like this.
WITH: naming a subquery
A WITH clause (a "common table expression") does the same thing but reads more clearly, top to bottom:
WITH totals AS (
SELECT oi.order_id, SUM(oi.qty * p.price) AS order_total
FROM order_items oi
JOIN products p ON p.id = oi.product_id
GROUP BY oi.order_id
)
SELECT ROUND(AVG(order_total), 2) AS average_order FROM totals;
UNION: stacking results
UNION puts the rows of two queries one after the other. Both queries must have the same number of columns:
SELECT name, 'customer' AS type FROM customers
UNION
SELECT first_name || ' ' || last_name, 'student' FROM students
ORDER BY type, name;
UNIONremoves duplicate rows.UNION ALLkeeps duplicates, and is faster.
Subquery or JOIN?
Many questions can be answered either way. Joins are usually better when you need columns from both tables in the result. Subqueries are often clearer for "filter by something computed elsewhere", like "above average" or "has at least one…". Use whichever is easier for you to read.
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04