Aral Code

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

SQL Students who scored above the Math average
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.

SQL The most expensive product(s)
SELECT name, price
FROM products
WHERE price = (SELECT MAX(price) FROM products);

Subquery that returns a list: IN

SQL Products that appear in unpaid orders
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'
);
SQL Customers from the same barangay as Maria Santos
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:

SQL Customers who have at least one paid order
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:

SQL Average order value
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:

SQL Same answer using WITH
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:

SQL One contact list from two tables
SELECT name, 'customer' AS type FROM customers
UNION
SELECT first_name || ' ' || last_name, 'student' FROM students
ORDER BY type, name;
  • UNION removes duplicate rows.
  • UNION ALL keeps 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. 🙂

1. Which runs first?
2. A subquery returns several ids. Which operator should you use?
3. What does UNION do with duplicate rows?
4. What must be true for two queries joined by UNION?

By Sir Reyel · Last updated 2026-12-04