0% found this document useful (0 votes)
19 views4 pages

Sub Queries

A subquery is a nested query that runs before the outer query, allowing for complex data retrieval in SQL. It can be utilized in various clauses such as WHERE, SELECT, FROM, and HAVING to filter or calculate data dynamically. Subqueries can replace joins, retrieve nested data, and compare rows against sets of values, making them a powerful tool in SQL operations.

Uploaded by

214g1a0450
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views4 pages

Sub Queries

A subquery is a nested query that runs before the outer query, allowing for complex data retrieval in SQL. It can be utilized in various clauses such as WHERE, SELECT, FROM, and HAVING to filter or calculate data dynamically. Subqueries can replace joins, retrieve nested data, and compare rows against sets of values, making them a powerful tool in SQL operations.

Uploaded by

214g1a0450
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Subquery

A subquery is a query that is nested within another query. Think of it as a query inside a query.
The subquery runs first and provides its result to the outer query. This allows you to perform
more complex data retrieval operations, which would otherwise require multiple steps or more
complicated joins.
Subqueries can be placed in different parts of a SQL query:
WHERE Clause – for filtering records based on dynamic values.
SELECT Clause – for retrieving data calculated from another query.
FROM Clause – when you need to use the result of a subquery as a virtual table.
HAVING Clause – for filtering results after applying aggregate functions.

Subqueries can be extremely useful in various scenarios:


When you need to filter results using aggregated data: For example, you can use subqueries to
find records based on average salary, total sales, or any other aggregate calculation.
When you need to retrieve nested data: Subqueries allow you to retrieve related data
dynamically. For instance, you might need to find employees working in departments where the
average salary is above a certain threshold.
When you want to perform operations that would normally require joins: Subqueries can
sometimes replace joins, especially when data needs to be aggregated or filtered before joining.
When you need to compare each row with a set of values: A correlated subquery allows you to
compare the outer query’s rows with values generated from the inner query. It’s powerful when
you need to compare the data from one row against other rows in the same table.

We will use two tables, departments and employees, for our subquery.

Departments Table – Holds information about different departments in the company.

Employees Table – Contains employee data, including names, salaries, and their respective
department IDs.

Create the 'departments' table


CREATE TABLE departments ( department_id INT AUTO_INCREMENT PRIMARY KEY,
department_name VARCHAR(255) NOT NULL );

INSERT INTO departments (department_name) VALUES ('HR'), ('IT'), ('Sales'), ('Marketing');


Create the 'employees' table

CREATE TABLE employees ( employee_id INT AUTO_INCREMENT PRIMARY KEY,


name VARCHAR(255), salary INT, department_id INT,
FOREIGN KEY (department_id) REFERENCES
departments(department_id) );

INSERT INTO employees (name, salary, department_id) VALUES ('John', 50000, 1),
('Jane', 70000, 2), ('Sam', 60000, 3), ('Sara', 80000, 2),('Mike', 75000, 4);
General Syntax of Subqueries
Subqueries can be used in several parts of a SQL query, and here’s a look at the general syntax
for each scenario:

1. Subquery in the WHERE Clause


The WHERE clause subquery is used to filter data based on a dynamically calculated value.

General Syntax:
SELECT column_name FROM table_name WHERE column_name operator (SELECT
column_name FROM another_table WHERE condition);

Find the names of employees whose salary is greater than the average salary of all employees.
SELECT name FROM employees WHERE salary > (SELECT AVG(salary) FROM employees);

The subquery (SELECT AVG(salary) FROM employees) calculates the average salary of all
employees.
The outer query filters the employees whose salary is greater than the average calculated by
the subquery.

2. Subquery in the SELECT Clause

The SELECT clause subquery allows you to retrieve additional data or perform calculations for
each row selected by the outer query.

General Syntax:
SELECT column_name, (SELECT column_name FROM another_table WHERE condition) AS
alias FROM table_name;

List all employees' names along with their department names.


SELECT e.name, (SELECT d.department_name FROM departments d WHERE
d.department_id = e.department_id) AS department_name FROM employees e;

The subquery (SELECT d.department_name FROM departments d WHERE d.department_id =


e.department_id) fetches the department name for each employee by matching the
department_id.
The outer query selects the name of each employee and appends their department name as an
alias department_name.

3. Subquery in the FROM Clause

In the FROM clause, the subquery acts as a virtual table, and the outer query joins it.
General Syntax:
SELECT column_name FROM (SELECT column_name FROM table_name WHERE condition)
AS alias;

Find the average salary in each department and display the department name along with its
average salary.

SELECT dept.department_name, avg_salaries.avg_salary


FROM departments dept
JOIN (SELECT department_id, AVG(salary) AS avg_salary FROM employees GROUP BY
department_id) avg_salaries
ON dept.department_id = avg_salaries.department_id;

The subquery (SELECT department_id, AVG(salary) AS avg_salary FROM employees GROUP


BY department_id) calculates the average salary for each department.
The outer query joins this result with the departments table to display the department name and
its average salary.

4. Correlated Subquery

A correlated subquery references a column from the outer query. This means the subquery is
evaluated for each row in the outer query.
General Syntax:
SELECT column_name FROM table_name outer_alias WHERE column_name operator
(SELECT column_name FROM another_table inner_alias WHERE condition =
outer_alias.column_name);

Find the names of employees whose salary is greater than the average salary within their
respective departments.

SELECT e.name FROM employees e WHERE e.salary > (SELECT AVG(salary) FROM
employees WHERE department_id = e.department_id);

The subquery (SELECT AVG(salary) FROM employees WHERE department_id =


e.department_id) is correlated, meaning it references the department_id from the outer query.
For each employee, the inner query calculates the average salary of that employee's
department, and the outer query checks if the employee’s salary is above the department’s
average.

5. Subquery with Multiple Rows (IN Operator)


The IN operator can be used with a subquery to check if a value is in a set of values returned by
the subquery.
General Syntax:
SELECT column_name FROM table_name WHERE column_name IN (SELECT column_name
FROM another_table WHERE condition);

Find all employees who work in departments where at least one employee earns more than
70,000.

SELECT name FROM employees WHERE department_id IN (SELECT department_id FROM


employees WHERE salary > 70000);

The subquery (SELECT department_id FROM employees WHERE salary > 70000) returns the
department IDs where any employee has a salary greater than $70,000.
The outer query then selects all employees who belong to those departments.

Operators Used with Subqueries


SQL operators allow us to compare and filter data returned by subqueries.
Comparison Operators: =, >, <, >=, <=, <> (not equal)
Logical Operators: AND, OR, NOT
IN Operator: Checks if a value is within a list of values.
BETWEEN Operator: Checks if a value is between two others.
EXISTS Operator: Checks if a subquery returns any result.

Example of IN Operator with Subquery:


SELECT name FROM employees WHERE department_id IN (SELECT department_id FROM
employees WHERE salary > 70000);

Aggregate Functions Used with Subqueries


Aggregate functions are used to perform calculations on a set of values and return a single
result. Common aggregate functions include:
AVG() – Returns the average value.
COUNT() – Returns the count of rows.
MAX() – Returns the maximum value.
MIN() – Returns the minimum value.
SUM() – Returns the sum of values.

Aggregate Function in Subquery:


Find departments with employees who earn above the average salary of their respective
departments.
SELECT name FROM employees e WHERE e.salary > (SELECT AVG(salary) FROM
employees WHERE department_id = e.department_id);

You might also like