9.5 KB · commit 40bb182
| title | T05.06 · SQL Subqueries |
|---|
← Previous: T05.05b Weighted CGPA and Extremes Without LIMIT | 🏠 Index | Next: T05.07a Multi-Table SQL Query Sets: Covid and Company →
Topic: T05 · SQL (DDL, DML, Aggregates, Subqueries) | Priority: 🟡 | Exam Frequency: 2/7 finals (+ CT-02) (8 marks) Sources: Silberschatz 7e Ch. 3 (§3.8) · Lecture Deck 03 (Slides 35–52) · Raidah Notes (pp. 16–17) · Fahim Notes (pp. 56–58)
Subquery (Nested Query): A SELECT-FROM-WHERE query embedded inside another SQL statement. The outer query uses the intermediate result set or scalar value computed by the inner query.
Correlated Subquery: An inner query that references an attribute or table alias from the outer query. The database re-evaluates the inner query once for every candidate row examined by the outer query.
Scalar Subquery: A subquery that returns exactly one row and one column. It can appear anywhere a single value is expected, including comparison expressions and the SELECT projection list. If a scalar subquery returns multiple rows at runtime, the query engine raises an error.
The WITH Clause (Common Table Expression): A clause that defines a named temporary relation at the top of a query. The temporary relation exists only for the duration of that single query.
Subqueries can be nested in three primary clauses:
The IN operator checks whether a value belongs to the set returned by a subquery. NOT IN tests for absence of membership:
SELECT DISTINCT course_id
FROM section
WHERE semester = 'Fall' AND year = 2017
AND course_id IN (
SELECT course_id
FROM section
WHERE semester = 'Spring' AND year = 2018
);
If the inner subquery returns a set containing NULL (e.g. {10, 20, NULL}), val NOT IN (...) expands to val <> 10 AND val <> 20 AND val <> NULL. Because val <> NULL evaluates to UNKNOWN, the whole condition becomes UNKNOWN, causing the query to return zero rows. Always filter out nulls (WHERE col IS NOT NULL) in subqueries used with NOT IN.
SOME / ANY: Evaluates to TRUE if the comparison is satisfied by at least one element in the subquery result (equivalent to comparing against the minimum or maximum appropriately).
Figure: Definition and evaluation of the some clause (Source: Lecture Deck 03, Slide 41).
ALL: Evaluates to TRUE only if the comparison is satisfied by every element in the subquery result.
Figure: Definition and evaluation of the all clause (Source: Lecture Deck 03, Slide 43).
| Expression | Standard Form | Status | Reason |
|---|---|---|---|
= SOME | IN | Identical | Matches at least one value in the set |
<> SOME | NOT IN | NOT Equivalent | True if there exists any value different from the operand |
<> ALL | NOT IN | Identical | Value is distinct from every single element in the set |
= ALL | IN | NOT Equivalent | True only if every element in the set equals the operand |
TRUE if the subquery returns 1 or more tuples).TRUE if the subquery returns zero tuples).SELECT course_id
FROM section AS S
WHERE semester = 'Fall' AND year = 2017
AND EXISTS (
SELECT *
FROM section AS T
WHERE semester = 'Spring' AND year = 2018
AND S.course_id = T.course_id
);
To find students who have taken all courses in the Biology department:
Required Courses−Student’s Taken Courses=∅SELECT DISTINCT S.ID, S.name
FROM student AS S
WHERE NOT EXISTS (
(SELECT course_id FROM course WHERE dept_name = 'Biology')
EXCEPT
(SELECT T.course_id FROM takes AS T WHERE T.ID = S.ID)
);
SELECT dept_name, avg_salary
FROM (
SELECT dept_name, AVG(salary) AS avg_salary
FROM instructor
GROUP BY dept_name
) AS dept_avg
WHERE avg_salary > 42000;
Every derived table in FROM must have an explicit table alias in MySQL.
WITH max_budget (value) AS (
SELECT MAX(budget) FROM department
)
SELECT department.dept_name
FROM department, max_budget
WHERE department.budget = max_budget.value;
Section B · CO2 · Asked in: 2024, 2019 · L2 merge
Question (2024 Q.6(a)). Explain sub-queries with two suitable examples.
Question (2019 Q.8(b)). Write down two examples of using sub-queries.
Answer.
Explanation: A subquery (or nested query) is a SELECT statement embedded inside another SQL statement (the outer query). It can appear in the WHERE clause to filter tuples, in the FROM clause as a temporary derived relation, or in the SELECT clause as a scalar expression. Subqueries allow multi-step data retrieval in a single query.
Example 1: Set Membership Subquery (IN)
Find all courses offered in Fall 2017 that were also offered in Spring 2018:
SELECT DISTINCT course_id
FROM section
WHERE semester = 'Fall' AND year = 2017
AND course_id IN (
SELECT course_id
FROM section
WHERE semester = 'Spring' AND year = 2018
);
The inner subquery generates the set of courses running in Spring 2018. The outer query checks whether Fall 2017 courses belong to that generated set.
Example 2: Scalar Comparison Subquery (AVG)
Find instructors whose salary is higher than the average salary of all instructors:
SELECT name, salary
FROM instructor
WHERE salary > (
SELECT AVG(salary)
FROM instructor
);
The inner query computes a single numeric value (the overall average salary). The outer query evaluates the > predicate against this scalar value for each instructor.
Variant for 2019 Q.8(b) (4 marks): Presenting the two SQL examples with their purpose answers the question.
CO2 · Asked in: CT-02 · L1 (asked once)
Question. Given STUDENT(StudentID,Name,Department,Semester,CGPA), write SQL query:
(c) Find students whose CGPA is greater than the overall average CGPA.
Answer.
SELECT *
FROM STUDENT
WHERE CGPA > (
SELECT AVG(CGPA)
FROM STUDENT
);
Execution Logic:
AVG() cannot appear directly in the WHERE clause of the same query block (e.g. WHERE CGPA > AVG(CGPA) is invalid).WHERE salary > AVG(salary). Always write WHERE salary > (SELECT AVG(salary) FROM ...).FROM must be followed by an alias (e.g., FROM (...) AS temp).=, >, <) fail if the subquery returns more than one row.NOT IN returns zero rows if the subquery contains a single NULL.= SOME is identical to IN, but <> SOME is NOT identical to NOT IN.← Previous: T05.05b Weighted CGPA and Extremes Without LIMIT | 🏠 Index | Next: T05.07a Multi-Table SQL Query Sets: Covid and Company →