23.7 KB · commit 40bb182
← Previous: T05.5b: Weighted CGPA and Extremes Without LIMIT | 🏠 Index | Next: T05.7a: Multi-Table SQL Query Sets →
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)
RUET tests subquery fundamentals in both conceptual and computational formats. Semester finals in 2019 Q.8(b) and 2024 Q.6(a) explicitly ask students to explain subqueries with two distinct examples for 4 marks each. CT-02 Q.01(c) tests scalar comparison against table-wide aggregates. Mastering subquery syntax in WHERE, FROM, and SELECT clauses is essential to solve the 44 marks of multi-table business schema problems in T05.7.
Subquery: A subquery is a
SELECT-FROM-WHEREquery nested inside an outer SQL query. It can appear in theWHERE,FROM,HAVING, orSELECTclause to feed intermediate results directly to the outer query.
Correlated Subquery: A correlated subquery is an inner query that uses a table alias from the outer query to filter its rows. Because its result depends on the outer row being inspected, the database re-evaluates the inner query for each row of the outer query.
Scalar Subquery: A scalar subquery is a subquery that returns a single value consisting of one row and one column. You can place it wherever SQL allows a single value expression, such as in the
SELECTlist or next to basic comparison operators like=,<, or>. If it returns more than one row at runtime, the database raises an error.
The WITH Clause (Common Table Expression): The
WITHclause defines a named temporary relation at the top of a query. That temporary table is visible only to the query immediately following it, making complex nested aggregations much easier to read and reuse.
A subquery (also called an inner query or nested query) passes its output directly to an enclosing outer query. SQL allows nesting in three primary clauses:
SELECT A1, A2, ..., An
FROM r1, r2, ..., rm
WHERE P;
The IN operator tests whether a given value belongs to a set of values produced by a subquery or an explicit list. The NOT IN operator 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 query returns a set containing even a single NULL value, NOT IN behaves counterintuitively:
val NOT IN (10, 20, NULL) expands to val <> 10 AND val <> 20 AND val <> NULL.val <> NULL evaluates to UNKNOWN.TRUE AND UNKNOWN yields UNKNOWN, the entire WHERE clause evaluates to UNKNOWN.WHERE attribute IS NOT NULL) in the inner query when using NOT IN.When a subquery returns a whole list of numbers instead of a single value, you cannot compare a column to it using a plain > or < sign alone. Instead, SQL gives you two modifiers (SOME and ALL) that let you compare a single value against every number in a subquery's output list.
Think of > SOME (or its exact synonym > ANY) as meaning "greater than at least one value in the list" (in other words, greater than the minimum value of the set):
Figure 1: Definition and evaluation of the 'some' clause (Source: Lecture Deck 03, Slide 41).
Think of > ALL as meaning "greater than every single value in the list" (in other words, strictly greater than the maximum value of the set):
Figure 2: Definition and evaluation of the 'all' clause (Source: Lecture Deck 03, Slide 43).
Exam questions often test how = SOME, <> SOME, = ALL, and <> ALL relate to IN and NOT IN:
| Comparison Expression | Equivalent Standard Form | Status | Reason / Counterexample |
|---|---|---|---|
= SOME | IN | Identical | True if the value matches at least one element in the list. |
<> SOME | NOT IN | NOT Equivalent | Suppose the list is {0,5}. Then 5=some {0,5} is true because 5=0, whereas 5 NOT IN {0,5} is false! |
<> ALL | NOT IN | Identical | True only if the value is different from every single element in the list. |
= ALL | IN | NOT Equivalent | True only if every single element in the list equals that value. |
Rather than comparing column values, EXISTS simply checks whether a subquery produces at least one row:
TRUE as soon as the inner query finds 1 or more matching rows).TRUE only when the inner query returns zero rows).Most ordinary subqueries are uncorrelated, meaning the inner query runs once on its own and hands its result to the outer query. In contrast, a correlated subquery refers to a table alias from the outer query inside its own WHERE clause. Because its filter depends on the current outer row, you can think of a correlated subquery like a nested for-loop: for each row the outer query visits, the inner query re-runs using that row's values.
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
);
Given section relation:
course_id values {101,102,103}.course_id values {101,103,105}.S.course_id = 101:
T.course_id = 101 in Spring 2018.EXISTS evaluates to TRUE, so course 101 is kept in the output.S.course_id = 102:
T.course_id = 102 in Spring 2018.EXISTS evaluates to FALSE, so course 102 is discarded.S.course_id = 103:
EXISTS evaluates to TRUE, so course 103 is kept in the output.How do we write a query for "Find all students who have taken every Biology course" when SQL has no built-in FOR ALL keyword? We use a clever everyday equivalence called double negation: "A student has taken every Biology course if there is NO Biology course that the student has NOT taken."
In set notation, set X (all Biology courses) is completely contained inside set Y (courses taken by student S) if subtracting Y from X leaves nothing behind:
X⊆Y⟺X−Y=∅In SQL, we subtract the student's taken courses from the required Biology courses using EXCEPT, and wrap that inside NOT EXISTS to check that no missing course remains:
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)
);
NOT EXISTS returns TRUE and Rahim is selected.{B_2} is not empty, NOT EXISTS returns FALSE and Karim is excluded.Any SELECT statement produces a relation. Therefore, a subquery can appear in the FROM clause as a derived relation.
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;
The WITH clause defines temporary relations available only within the executing statement. It clarifies multi-step calculations:
WITH max_budget (value) AS (
SELECT MAX(budget)
FROM department
)
SELECT department.dept_name
FROM department, max_budget
WHERE department.budget = max_budget.value;
A subquery that returns a single row and a single column is a scalar subquery. It can appear anywhere a single value is expected, including comparison expressions and the SELECT list.
SELECT dept_name,
(SELECT COUNT(*)
FROM instructor
WHERE department.dept_name = instructor.dept_name) AS num_instructors
FROM department;
Problem: Find the names and salaries of all employees whose salary is greater than the average salary of their own department. (Adapted from 2023 Q.3(a)(iii)).
Schema: employee(ssn, fname, lname, salary, dept_no)
dept_no), not the entire company.SELECT AVG(e2.salary)
FROM employee e2
WHERE e2.dept_no = e1.dept_no
e1.salary > that computed department average:SELECT e1.fname, e1.lname, e1.salary
FROM employee e1
WHERE e1.salary > (
SELECT AVG(e2.salary)
FROM employee e2
WHERE e2.dept_no = e1.dept_no
);
| Year & Question | Marks | Scenario / Data Given | Key Result / Answer Summary |
|---|---|---|---|
| 2019 Q.8(b) | 4 | Open / conceptual subquery prompt | Two distinct subquery examples (IN set membership + AVG scalar comparison) |
| 2024 Q.6(a) | 4 | Conceptual subquery prompt (CO2) | Formal definition + two distinct examples with inner/outer execution trace |
| CT-02 Q.01(c) | 3 | Student schema (StudentID, Name, Department, Semester, CGPA) | Uncorrelated scalar subquery: WHERE CGPA > (SELECT AVG(CGPA) FROM STUDENT) |
Appeared: 2024 Q.6(a) — (4 marks)
Question:
Explain sub-queries with two suitable examples.
Full Answer:
A subquery (or nested query) is a SELECT query embedded within another SQL statement (the outer query). Subqueries enable multi-step data retrieval within a single declarative statement. The outer query uses the intermediate result set or scalar value computed by the inner query.
Subqueries can be placed in:
WHERE clause (filtering rows via IN, EXISTS, or comparison operators).FROM clause (serving as a temporary derived table).SELECT clause (generating dynamic scalar column values).INTask: Find all courses offered in the Fall 2017 semester that were also offered in the Spring 2018 semester.
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
);
Task: Find the names and salaries of all instructors whose salary is strictly greater than the university-wide average instructor salary.
SELECT name, salary
FROM instructor
WHERE salary > (
SELECT AVG(salary)
FROM instructor
);
salary > 68000 for every tuple in the instructor table.Appeared: 2019 Q.8(b) — (4 marks)
Question:
Write down two examples of using sub-queries.
Full Answer:
IN)Find student IDs of all students enrolled in the 'ECE' department who have taken course 'ECE-2215':
SELECT StudentID, Name
FROM STUDENT
WHERE Department = 'ECE'
AND StudentID IN (
SELECT StudentID
FROM ENROLLMENT
WHERE CourseCode = 'ECE-2215'
);
ECE-2215. The outer query filters students belonging to the ECE department against this candidate list.WHERE ClauseFind the roll numbers and names of all students whose marks exceed the class average marks:
SELECT rollno, name, marks
FROM student
WHERE marks > (
SELECT AVG(marks)
FROM student
);
WHERE predicate. The nested subquery computes AVG(marks) as a scalar value, allowing the outer query to filter records against it.Appeared: CT-02 Q.01(c) — (3 marks)
Question:
Given STUDENT(StudentID,Name,Department,Semester,CGPA), write SQL query:
(c) Find students whose CGPA is greater than the overall average CGPA.
Full Answer:
SELECT *
FROM STUDENT
WHERE CGPA > (
SELECT AVG(CGPA)
FROM STUDENT
);
AVG() cannot appear directly in the WHERE clause of the same query block (e.g., WHERE CGPA > AVG(CGPA) causes a SQL syntax error).(SELECT AVG(CGPA) FROM STUDENT) computes the table-wide mean across all student records.WHERE CGPA > 3.625, returning the records with 3.75 and 4.00.<> ALL and NOT IN & The NULL TrapSource: Silberschatz 7e · Chapter 3 (Exercise 3.20)
Exam Relevance: Prime Overdue Advanced Theory Drill
Key Tested Concept: Mathematical equivalence of<> ALLandNOT IN, and the three-valued logic (UNKNOWN) trap.
Problem Statement:
- Prove that the predicate
val <> ALL (SELECT ...)is logically equivalent toval NOT IN (SELECT ...).- Explain the catastrophic
NULLtrap: What doesval NOT IN (SELECT ...)evaluate to if the subquery returns at least oneNULLvalue?- Provide an example showing how
NOT EXISTSprovides a safer alternative toNOT INwhen dealing with nullable columns.
Model Exam-Style Solution:
Proof of Logical Equivalence:
val NOT IN S:
val NOT IN S⟺¬(val=s1∨val=s2∨⋯∨val=sn)
val <> ALL S:
By definition, val <> ALL S evaluates to TRUE if and only if val <> s_i is TRUE for every element si∈S:
val <> ALL S⟺i=1⋀n(val=si)
<> ALL is strictly equivalent to NOT IN. ■The NULL Trap in Three-Valued Logic:
val = 5. Evaluate 5 NOT IN (10, NULL):
5=10∧5=NULL
TRUE∧UNKNOWN⟹UNKNOWN
WHERE clauses, only rows evaluating to TRUE are returned. Rows evaluating to UNKNOWN or FALSE are filtered out!NULL value, val NOT IN (...) evaluates to UNKNOWN for every single row, and the query returns ZERO ROWS (an empty result set)!Safe Alternative using NOT EXISTS:
SELECT name FROM student WHERE ID NOT IN (SELECT ID FROM takes);
NOT EXISTS clause:SELECT s.name
FROM student s
WHERE NOT EXISTS (
SELECT 1 FROM takes t WHERE t.ID = s.ID
);
NOT EXISTS checks for tuple existence and is unaffected by NULL values in non-correlated columns. ■💡 RUET Exam Takeaway:
Remember: NOT IN with nulls in the subquery returns NOTHING! Always mention the 3-valued logic truth table (TRUE∧UNKNOWN=UNKNOWN).
Source: Silberschatz 7e · Chapter 3 (Exercise 3.31)
Exam Relevance: High-Probability Subquery Exam Drill
Key Tested Concept: Set-difference queries usingNOT INand correlatedNOT EXISTS.
Problem Statement:
Using the university database relations:
- instructor(ID,name,dept_name,salary)
- teaches(ID,course_id,sec_id,semester,year) Write an SQL query to find the names of all instructors who taught in Spring 2018, but did NOT teach in Spring 2017:
- Formulate the query using the
NOT INsubquery construct.- Formulate the query using the correlated
NOT EXISTSconstruct.
Model Exam-Style Solution:
NOT IN:SELECT DISTINCT i.name
FROM instructor i
JOIN teaches t ON i.ID = t.ID
WHERE t.semester = 'Spring' AND t.year = 2018
AND i.ID NOT IN (
SELECT ID
FROM teaches
WHERE semester = 'Spring' AND year = 2017
);
NOT EXISTS:SELECT DISTINCT i.name
FROM instructor i
JOIN teaches t ON i.ID = t.ID
WHERE t.semester = 'Spring' AND t.year = 2018
AND NOT EXISTS (
SELECT 1
FROM teaches t2
WHERE t2.ID = i.ID
AND t2.semester = 'Spring'
AND t2.year = 2017
);
Step-by-Step Logic:
NOT IN (or NOT EXISTS) filters out any instructor present in the 2017 subquery, leaving only those instructors whose 2018 teaching activity was disjoint from 2017. ■💡 RUET Exam Takeaway:
Correlated NOT EXISTS is preferred by database optimizers because it can short-circuit as soon as the first matching tuple is encountered.
WHERE salary > AVG(salary) causes a syntax error. Always wrap the aggregate in a scalar subquery: WHERE salary > (SELECT AVG(salary) FROM ...).IN or EXISTS) and one scalar aggregate subquery (AVG). Providing two identical IN queries loses marks.FROM clause must have an alias (e.g., FROM (...) AS t1), otherwise MySQL rejects the query.NULL, NOT IN returns no rows for the entire query. Add WHERE col IS NOT NULL to the inner query.NOT IN / NOT EXISTS)← Previous: T05.5b: Weighted CGPA and Extremes Without LIMIT | 🏠 Index | Next: T05.7a: Multi-Table SQL Query Sets →