Course Database Management Program BSCS
Systems -Lab
Section 3A Semester Fall 24
LAB 8
Correlated Subquery
Lab Objective:
· Understanding correlated subqueries in SQL.
· To run queries that depend on correlated subqueries to retrieve specific data.
· To determine how correlated subqueries vary from normal subqueries.
Outcome:
This lab will cover the usage of correlated subqueries in SQL, which are subqueries that rely
on the outer query for each row. Compared to independent subqueries, correlated subqueries
are reviewed for each row processed by the outer query.
Correlated Subquery:
A correlated subquery is a subquery that references columns from the outer query. This dependency
causes the subquery to be executed repeatedly, once for each row processed by the outer query.
Correlated subqueries are commonly used for queries that need to filter data based on row-by-row
comparisons.
Sample Table
CREATE TABLE departments (dept_id INT PRIMARY KEY,
dept_name VARCHAR(50));
CREATE TABLE employees ( emp_id INT PRIMARY KEY,
emp_name VARCHAR(50),
salary DECIMAL(10, 2),
dept_id INT,
FOREIGN KEY (dept_id) REFERENCES departments(dept_id));
Insert sample data into departments table
INSERT INTO departments VALUES (1, 'Sales'),
(2, 'Marketing'),
(3, 'IT');
Insert sample data into employees table
INSERT INTO employees VALUES (1, 'Alice', 60000, 1),
(2, 'Bob', 50000, 1),
(3, 'Carol', 70000, 2),
(4, 'David', 80000, 3),
(5, 'Eve', 75000, 3);
Correlated Subquery Examples
1. Write a query to find employees whose salary is above the average salary of their respective
department.
2. This query will use a correlated subquery to calculate the average salary per department.
SELECT emp_name, salary, dept_id
FROM employees e1 WHERE salary > (
SELECT AVG(salary) FROM employees e2 WHERE e1.dept_id = e2.dept_id );
Feature Correlated Subquery Uncorrelated Subquery
Independent of outer
Dependency Depends on outer query values
query
Execution
Executed once per outer query row Executed once
Frequency
May be slower (row-by-row
Performance Typically faster
execution)
Lab Task: For the following schema write query for each task
1. Write a correlated subquery to display Invoice Id, Billing city billing state and total
sales in descending order. Hint: One Sale= unitprice* quantity
2. Write a correlated subquery to display invoice information having latest date.
3. Write correlated subquery to display Customers(customer Id, full name, email address)
who placed orders greater than their average order amount.
4. Write query to list all albums with track longer than the average track length in database.