Explain the concept of subquery in SQL and provide an example.

Instruction: Using customers(customer_id PRIMARY KEY, customer_name) and sales(customer_id, purchase_amount), return each customer once if they have at least one sale above the overall average non-NULL sale amount. Use PostgreSQL subqueries and explain empty/NULL cases.

Context: This question evaluates the candidate's understanding of subqueries, which are nested queries used to perform operations that require multiple steps in a single query.

Updated

Official answer

A subquery is nested inside another SQL statement. Here the requirement is one customer row if that customer has at least one sale above the overall average non-NULL sale amount.

Assume PostgreSQL customers(customer_id integer PRIMARY KEY, customer_name text) and sales(customer_id integer, purchase_amount numeric):

SELECT c.customer_id, c.customer_name
FROM customers c
WHERE EXISTS (
  SELECT 1 FROM sales s
  WHERE s.customer_id = c.customer_id
    AND s.purchase_amount > (SELECT AVG(purchase_amount) FROM sales)
)
ORDER BY c.customer_id;

The aggregate scalar subquery computes the average; EXISTS checks for a qualifying sale without repeating a customer who has several matches. Purchase amounts belong to sales, not an unexplained customers column.

NULL sale amounts do not contribute to AVG or pass the comparison. If there are no non-NULL amounts, no customer qualifies. This is not a comparison of each customer's total spending or average purchase; those are different specifications. Check the plan before claiming a performance benefit.

Related Questions