Subqueries and Nested Queries

Discuss my database trends and their role in business.
Post Reply
mahbubamim
Posts: 145
Joined: Thu May 22, 2025 5:25 am

Subqueries and Nested Queries

Post by mahbubamim »

In SQL, subqueries (also called nested queries) are queries embedded inside another SQL query. A subquery is a query within a query, used to perform intermediate steps or filter data based on complex conditions. Subqueries enhance the power of SQL by allowing multi-step data retrieval in a single statement.

What is a Subquery?
A subquery is an SQL query enclosed within parentheses and used inside another query’s SELECT, INSERT, UPDATE, or DELETE statement. The outer query is called the main query or parent query, and the subquery is executed first. Its result is then used by the main query to complete the operation.

Example:

sql
Copy
Edit
SELECT employee_name
FROM employees
WHERE department_id = (
SELECT department_id
FROM departments
WHERE department_name = 'Sales'
);
Here, the subquery finds the department_id for the “Sales” department, and the outer query returns employees working in that department.

Types of Subqueries
Single-row subqueries: Return a single value and are used iceland phone number list with comparison operators like =, <, >.

Multiple-row subqueries: Return multiple rows and are used with operators like IN, ANY, or ALL.

Multiple-column subqueries: Return more than one column and are used with operators like IN combined with tuples.

Correlated vs Non-correlated Subqueries
Non-correlated subqueries are independent of the outer query and can be executed alone. They run once and their result is passed to the outer query.

Correlated subqueries depend on values from the outer query. They are executed repeatedly, once for each row processed by the outer query. For example:

sql
Copy
Edit
SELECT e1.employee_name
FROM employees e1
WHERE salary > (
SELECT AVG(salary)
FROM employees e2
WHERE e2.department_id = e1.department_id
);
Here, the subquery calculates the average salary for the department of each employee from the outer query.

Benefits of Subqueries
Simplify complex queries: Subqueries break down a problem into smaller parts.

Improve readability: Encapsulate complex logic within queries.

Enable dynamic filtering: Subqueries allow filtering based on dynamically computed values.

Limitations
Performance: Correlated subqueries can be slow as they run repeatedly.

Complexity: Deeply nested subqueries can be difficult to read and maintain.

Alternatives
Sometimes, subqueries can be replaced by JOINs, which may improve performance and clarity depending on the situation.

In conclusion, subqueries and nested queries are powerful SQL tools that allow querying data flexibly and efficiently by embedding queries within queries. They help perform sophisticated filtering and data retrieval tasks that would be difficult with simple queries alone.
Post Reply