🗄️ Databases

Subquery

Subquery

A query within a query. Expresses complex conditions.

Detailed Explanation

A subquery is another SELECT statement contained within a SQL statement, which provides results for the outer query to use. It is also called a nested query, and can be used in various positions such as the WHERE, FROM, and SELECT clauses.

Subqueries are broadly classified into scalar subqueries (returning a single value), inline views (used in the FROM clause), and correlated subqueries (referencing the outer query). They are useful when complex conditions or calculations are needed, but excessive use can cause performance degradation.

Some subqueries can be converted into a JOIN to improve performance. The query optimizer sometimes optimizes them automatically, but if a developer converts them intentionally, a better execution plan can be obtained.

Code Example

-- 스칼라 서브쿼리 (SELECT 절)
SELECT
    name,
    salary,
    (SELECT AVG(salary) FROM employees) as avg_salary
FROM employees;

-- WHERE 절 서브쿼리
SELECT name, department
FROM employees
WHERE department_id IN (
    SELECT id FROM departments
    WHERE location = 'Seoul'
);

-- 상관 서브쿼리 (Correlated Subquery)
SELECT e.name, e.salary
FROM employees e
WHERE e.salary > (
    SELECT AVG(salary)
    FROM employees
    WHERE department_id = e.department_id
);

-- EXISTS 서브쿼리
SELECT c.name
FROM customers c
WHERE EXISTS (
    SELECT 1 FROM orders o
    WHERE o.customer_id = c.id
    AND o.order_date > '2024-01-01'
);

-- 인라인 뷰 (FROM 절 서브쿼리)
SELECT dept_name, avg_salary
FROM (
    SELECT d.name as dept_name, AVG(e.salary) as avg_salary
    FROM departments d
    JOIN employees e ON d.id = e.department_id
    GROUP BY d.name
) dept_stats
WHERE avg_salary > 5000000;

Practical Conversation Example

Backend developer: This query is too slow, and it has several nested subqueries.

DBA: It's a correlated subquery. The subquery is executed for every row of the outer query, so it's bound to be slow.

Backend developer: Would it get better if we changed it to a JOIN?

DBA: Yes, in most cases a JOIN is more efficient. The optimizer can build a better execution plan.

Interviewer: What is the difference between a subquery and a JOIN, and in what situations do you use a subquery?

Candidate: Subqueries have good readability when obtaining complex conditions or a single value. However, correlated subqueries are executed for each row, which causes performance issues, so it is better to convert them to a JOIN where possible. EXISTS is efficient when you only need to check whether data exists.

Interviewer: What should one watch out for with scalar subqueries?

Candidate: A scalar subquery must return exactly one row and one column. If multiple rows are returned, an error occurs.

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

Senior: In this code, the subquery queries the same table three times.

Junior: Yes, it was needed for each condition.

Senior: If you query once with a WITH clause (CTE) and reuse the result, or refactor with a JOIN, performance will improve a lot. You should avoid duplicate subqueries.

Cautions

Related Terms

Learn More