TECHNOLOGIESTieInn Technologies

Subqueries

SQL · 14 questions

Short notes

Key idea

A subquery is a query inside another query. Use it when one answer depends on another: "orders above the average", "customers who bought X".

Syntax

-- a single value
WHERE amount > (SELECT AVG(amount) FROM orders)
-- a list
WHERE customer_id IN (SELECT customer_id FROM vip)
-- a table
FROM (SELECT ... ) AS t
-- correlated: runs per outer row
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id)

Example

Products priced above their own category's average:

SELECT p.name, p.price
FROM products p
WHERE p.price > (SELECT AVG(price) FROM products x
                 WHERE x.category = p.category);

Traps

  • A subquery after = must return one row. If it returns several, the query fails; use IN.
  • NOT IN with a NULL in the subquery returns nothing. Prefer NOT EXISTS.
  • Give a subquery in FROM an alias; several databases refuse it without one.
  • Deep nesting is hard to read. If you nest more than twice, switch to a CTE.

Want the full lesson with step-by-step examples, a project and a certificate? SQL course, ₹120 →

Questions

Open in Code Lab5 free questions
5 questions

    Subqueries

  1. Question 1easy

    Which query finds products priced above the average price?

  2. Subqueries

  3. Question 2medium

    The average product price is about ₹1,704. What does this return?

    SELECT COUNT(*) FROM products
    WHERE price > (SELECT AVG(price) FROM products);
  4. Subqueries

  5. Question 3medium

    What does this return?

    SELECT COUNT(*) FROM orders
    WHERE customer_id IN (
      SELECT customer_id FROM customers WHERE city = 'Chennai'
    );
  6. Subqueries

  7. Question 4hard

    SELECT * FROM customers WHERE customer_id NOT IN (SELECT referred_by FROM signups). The subquery returns some NULLs. What happens?

  8. Subqueries

  9. Question 5hard

    10 customers live in Chennai. What happens when you run SELECT COUNT(*) FROM orders WHERE customer_id = (SELECT customer_id FROM customers WHERE city = 'Chennai');?

9 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.