Subqueries

Estimated reading: 2 minutes 18 views

1. What is a subquery, and how is it used in SQL?

A subquery is a query nested inside another SQL query. It is used to perform intermediate calculations or fetch data that can be used by the outer query. Subqueries can appear in SELECT, FROM, WHERE, or HAVING clauses.

Example (Find employees in a specific department):

				
					SELECT name 
FROM employees 
WHERE department_id = (SELECT id FROM departments WHERE department_name = 'Sales');

				
			

2. Write a query to find employees with salaries higher than the average salary.

You can use a subquery in the WHERE clause to calculate the average salary and compare it to individual salaries.
Example:

				
					SELECT name, salary 
FROM employees 
WHERE salary > (SELECT AVG(salary) FROM employees);

				
			

3. How does a correlated subquery differ from a regular subquery?

  • A regular subquery is independent of the outer query and is executed once.
  • A correlated subquery depends on the outer query and is executed repeatedly for each row processed by the outer query.

Example of a correlated subquery (Find employees earning more than the average salary of their department):

				
					SELECT name, salary 
FROM employees e1 
WHERE salary > (SELECT AVG(salary) 
                FROM employees e2 
                WHERE e2.department_id = e1.department_id);

				
			

Here, the subquery references e1.department_id, which ties it to the outer query.

Leave a Comment

Share this Doc

Subqueries

Or copy link

CONTENTS