0% found this document useful (0 votes)
6 views40 pages

pdf2&3

The document is a comprehensive SQL study guide covering nested subqueries, triggers, views, and database modifications. It explains concepts such as correlated subqueries, set comparison operators, and the use of EXISTS and NOT EXISTS clauses, along with practical examples. Additionally, it discusses the execution of correlated subqueries, the DELETE statement, and the importance of execution order in SQL operations.

Uploaded by

parentlover2004
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)
6 views40 pages

pdf2&3

The document is a comprehensive SQL study guide covering nested subqueries, triggers, views, and database modifications. It explains concepts such as correlated subqueries, set comparison operators, and the use of EXISTS and NOT EXISTS clauses, along with practical examples. Additionally, it discusses the execution of correlated subqueries, the DELETE statement, and the importance of execution order in SQL operations.

Uploaded by

parentlover2004
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

📚 Complete SQL Study Guide

Nested Subqueries, Triggers, Views & Database Modifications

🎯 TABLE OF CONTENTS
1. Nested Subqueries (Correlated Subqueries)
2. Set Comparison Operators (SOME, ALL)
3. Test for Empty Relations (EXISTS)
4. Correlation Variables & Scoping Rules
5. Computation of Correlated Subqueries
6. Database Modifications (DELETE, INSERT, UPDATE)
7. CASE Statements
8. Triggers
9. Views (Regular & Materialized)

🎯 PART 1: NESTED SUBQUERIES


1. WHAT ARE NESTED SUBQUERIES?
Definition: A nested subquery (also called correlated subquery or synchronized subquery) is a subquery
that uses values from the outer query in its WHERE clause.

Key Characteristics:

SQL provides a mechanism for nesting subqueries


A subquery is a SELECT-FROM-WHERE expression nested within another query
Common use: testing for set membership, making set comparisons, determining set cardinality

Simple vs. Nested:

Scalar Subquery:

Returns a single value (one row, one column)


Can be used wherever a single value is expected
Example: (SELECT AVG(salary) FROM instructor)

Nested/Correlated Subquery:

A query within another query


Uses correlation names from outer query
May be executed multiple times (once per outer row)

2. BASIC STRUCTURE

sql

-- OUTER QUERY (Main Query)


SELECT employee_number, name
FROM employees AS E
WHERE salary > (
-- INNER QUERY (Subquery) - uses E from outer query
SELECT AVG(salary)
FROM employees
WHERE department = [Link] -- Correlation!
);

Key Points:

Inner query references correlation variable from outer query


Inner query executes once for each row of outer query
This is called a correlated subquery

3. IMPORTANT ISSUES WITH SUBQUERIES

Issue 1: Which clause contains the subquery?

Can appear in SELECT, FROM, or WHERE clauses

Issue 2: What does the subquery return?

Single value (scalar)


Set of values (multiple rows)

Issue 3: Correlated variables?

Does subquery use variables from outer query?


If YES → called correlated subquery
Same scoping rules as programming languages

Issue 4: Returns one tuple or a single value?

Scalar subquery returns single value


Used for comparisons with =, <, >, <=, >=, <>

Issue 5: Use of keywords

IN, NOT IN
SOME, ALL
EXISTS, NOT EXISTS
UNIQUE, NOT UNIQUE
EXCEPT, ANY, etc.

Issue 6: SQL implementation support

Not all features may be supported by specific SQL implementations

4. DETAILED EXAMPLES

Example 1: Find courses offered in Fall 2009 AND Spring 2010


Using Nested Subquery:

sql

SELECT DISTINCT course_id


FROM section
WHERE semester = 'Fall' AND year = 2009
AND course_id IN (
SELECT course_id
FROM section
WHERE semester = 'Spring' AND year = 2010
);

How it works:

1. Inner query finds all course_ids from Spring 2010


2. Outer query finds Fall 2009 courses
3. Returns only courses that appear in BOTH semesters

Example 2: Find courses offered in Fall 2009 BUT NOT in Spring 2010

sql
SELECT DISTINCT course_id
FROM section
WHERE semester = 'Fall' AND year = 2009
AND course_id NOT IN (
SELECT course_id
FROM section
WHERE semester = 'Spring' AND year = 2010
);

Key Difference:

Used NOT IN instead of IN


Returns courses ONLY in Fall 2009

Example 3: Testing on Several Attributes

Find total number of DISTINCT students who have taken course sections taught by instructor with ID
10101

sql

SELECT COUNT(DISTINCT ID)


FROM takes
WHERE (course_id, sec_id, semester, year) IN (
SELECT course_id, sec_id, semester, year
FROM teaches
WHERE [Link] = '10101'
);

Key Points:

Tests multiple attributes at once


Inner query returns rows from teaches table
Outer query counts distinct students

5. SET COMPARISON - SOME OPERATOR

SQL supports use of 'SOME' in different forms:

sql
< SOME
<= SOME
> SOME
>= SOME
= SOME
<> SOME

Meaning of SOME:

< SOME : Less than at least one value

> SOME : Greater than at least one value

= SOME : Equal to at least one value (equivalent to IN)

Example: SOME with Different Values

Given set: {0, 5, 6}

sql

-- Test: 5 < SOME {0, 5, 6}


-- Result: FALSE (5 is not less than any value)

-- Test: 5 < SOME {6, 10}


-- Result: TRUE (5 < 6 and 5 < 10)

-- Test: 5 = SOME {0, 5}


-- Result: TRUE (5 equals 5)

-- Test: 5 <> SOME {4, 5, 6}


-- Result: TRUE (5 <> 4 and 5 <> 6)

Example Query: Find names of instructors with salary greater than at least one instructor in Biology
department

sql

SELECT name
FROM instructor
WHERE salary > SOME (
SELECT salary
FROM instructor
WHERE dept_name = 'Biology'
);

How it works:
1. Inner query generates set of salaries from Biology dept
2. For each instructor in outer query:
Test if their salary is greater than ANY Biology salary

3. If true, include that instructor's name

Visual Example:

Biology salaries: {50000, 60000, 70000}

Instructor A (salary 55000) > SOME Biology → TRUE (55000 > 50000)
Instructor B (salary 45000) > SOME Biology → FALSE

6. SET COMPARISON - ALL OPERATOR

SQL supports use of 'ALL' in different forms:

sql

< ALL
<= ALL
> ALL
>= ALL
= ALL
<> ALL

Meaning of ALL:

< ALL : Less than every value

> ALL : Greater than every value

= ALL : Equal to every value

<> ALL : Not equal to any value (equivalent to NOT IN)

Example: ALL with Different Values


Given set: {0, 5, 6}

sql
-- Test: 5 < ALL {0, 5, 6}
-- Result: FALSE (5 is NOT less than all values)

-- Test: 5 < ALL {6, 10}


-- Result: TRUE (5 < 6 AND 5 < 10)

-- Test: 5 = ALL {4, 5}


-- Result: FALSE (5 ≠ 4)

-- Test: 5 ≠ ALL {4, 6}


-- Result: TRUE (5 ≠ 4 AND 5 ≠ 6)

Example Query: Find names of instructors with salary greater than ALL instructors in Biology

sql

SELECT name
FROM instructor
WHERE salary > ALL (
SELECT salary
FROM instructor
WHERE dept_name = 'Biology'
);

How it works:

1. Inner query generates set of Biology salaries


2. For each instructor:
Check if salary > EVERY Biology salary

3. Only include if condition is TRUE for all values

Note: Instructors from Biology department with greater salaries than lowest Biology salary will also be
included!

7. TEST FOR EMPTY RELATIONS - EXISTS


The EXISTS construct returns TRUE if the argument subquery is NONEMPTY

Syntax:

sql

EXISTS (subquery)
Usage:

Returns TRUE if subquery returns at least one row


Returns FALSE if subquery is empty

Example: Using EXISTS


Find all courses taught in both Fall 2009 and Spring 2010:

sql

SELECT course_id
FROM section AS S
WHERE semester = 'Fall' AND year = 2009
AND EXISTS (
SELECT *
FROM section AS T
WHERE semester = 'Spring' AND year = 2010
AND S.course_id = T.course_id
);

How it works:

1. For each Fall 2009 course (outer query)


2. Check if there EXISTS a matching Spring 2010 course
3. Correlation: S.course_id = T.course_id
4. If EXISTS returns TRUE, include that course

Key Feature:

Uses correlation name from outer query (S) in subquery


This is a correlated subquery

8. CORRELATION VARIABLES & SCOPING

Scoping Rule for Correlation Names:

In queries that contain subqueries, a scoping rule applies:

Legal to use only correlation names defined:


Locally in the subquery itself, OR
In any query that contains the subquery

If correlation name is defined both locally and globally:


Local definition applies (like variable scoping in programming)

Example: Local and Global Variables

Find all courses taught in both Fall 2009 and Spring 2010:

sql

SELECT course_id
FROM section AS S -- Global variable (S)
WHERE semester = 'Fall' AND year = 2009
AND EXISTS (
SELECT *
FROM section AS T -- Local variable (T)
WHERE semester = 'Spring' AND year = 2010
AND S.course_id = T.course_id -- Uses global S and local T
);

Variables:

S = Global variable (in outer query)


T = Local variable (in subquery)
Subquery can access both S and T
Outer query can only access S

Memory Trick: "Variable Visibility Tower"

Outer Query Level → Can see: S only


|
└─→ Subquery Level → Can see: S, T

9. NOT EXISTS

The NOT EXISTS construct returns TRUE if the subquery is EMPTY

Example: Using NOT EXISTS

Find all students who have taken ALL courses in Biology department:

sql
SELECT DISTINCT [Link], [Link]
FROM student AS S
WHERE NOT EXISTS (
-- Find courses student S has NOT taken
(SELECT course_id FROM course WHERE dept_name = 'Biology')
EXCEPT
(SELECT course_id FROM takes WHERE [Link] = [Link])
);

How it works:

1. For each student S


2. Get all Biology courses
3. Get all courses student S has taken
4. Find difference (courses NOT taken)
5. If this difference is EMPTY → student took ALL Biology courses

Logic:

NOT EXISTS checks if result is empty


If empty → student has taken all Biology courses

10. DERIVED RELATIONS

When a subquery is used in 'FROM' clause, it derives a relation

Example: Find average instructors' salaries in departments where average salary > $42,000

sql

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;

How it works:

1. Inner query (derived relation):


Computes average salary by department
Creates temporary table with columns: dept_name, avg_salary
2. Outer query:
Filters departments where avg_salary > 42000

Key Point:

Subquery in FROM clause is called derived relation


Must be given an alias ( AS dept_avg )

11. WITH CLAUSE


The WITH clause provides way to define temporary relation whose definition is available only to the
query

Syntax:

sql

WITH temp_relation(attributes) AS (
subquery
)
SELECT ...
FROM temp_relation
WHERE ...;

Example: Using WITH Clause

Same query as above using WITH:

sql

WITH dept_avg(dept_name, avg_salary) AS (


SELECT dept_name, AVG(salary)
FROM instructor
GROUP BY dept_name
)
SELECT dept_name, avg_salary
FROM dept_avg
WHERE avg_salary > 42000;

Advantages:

More readable
Can be reused in same query
Clearer structure
🎯 PART 2: COMPUTATION OF CORRELATED SUBQUERIES
12. HOW CORRELATED SUBQUERIES ARE EXECUTED
Common Computational Method:

Rewrite subquery into an equivalent flat query


A process known as flattening
Here, advantage: The developing algorithm will be less complex

General Computational Approach:

Directly execute nested loop by iterating all tuples of correlated columns from outer query block
Execute subquery as many times as number of outer tuples

Simple Approach: Has advantage of general purpose because it's not affected by:

Type of correlated operators


Structure of subquery However, it has high computational complexity

13. EXECUTION STEPS


For query:

sql

DELETE FROM instructor


WHERE salary < (
SELECT AVG(salary)
FROM instructor
);

Execution Process:

Step 1: Compute avg

Calculate average salary across all instructors

Step 2: Take one tuple from outer query and test

For each instructor:


If salary < avg(salary):
Mark for deletion
Step 3: If test is TRUE, delete the tuple

Delete all marked tuples

Important:

If tuple is deleted, resultant number of tuples in instructor relation will be less by one tuple
In next computation of avg in subquery, it will be different/affected
Therefore: Performing all tests (salary < avg(salary)) BEFORE performing any deletion is important

14. ORDER MATTERS IN DELETE

Issue: If some tuples are deleted before others are tested, the average salary may change, and therefore the final
result of DELETE will depend on the order in which tuples were processed.

Solution: SQL processes DELETE in two phases:

1. Test Phase: Test all tuples and mark those to be deleted


2. Delete Phase: Delete all marked tuples

This ensures consistent results regardless of processing order.

15. GPU ACCELERATION APPROACH


Modern Optimization: A GPU acceleration approach is used to significantly improve performance of nested
method of high algorithmic complexity by:

Exploiting massive parallelism


Device memory locality on GPU

Goal: Accomplishes both:

General-purpose SQL design


Implementation with high performance in subquery processing

16. QUERY ENGINE CAPABILITIES


Understanding Query Writing Skills:

By understanding query writing skills, query engine capabilities can be improved.

When we say "SQL implementation":


We're talking about query engine

For further understanding:

Consult chapter on Query Processing


Study Query Optimization

🎯 PART 3: DATABASE MODIFICATIONS


17. DELETE STATEMENT

Purpose: Remove tuples from a relation

Syntax:

sql

DELETE FROM relation


WHERE predicate;

Key Rules:

We can delete ONLY whole tuples


We CANNOT delete values of specific attributes
WHERE clause represents predicate
Relation r represents a relation

18. DELETE - BASIC EXAMPLES

Example 1: Delete all tuples

sql

DELETE FROM instructor;

Result: All tuples from instructor relation will be deleted (table becomes empty)

Example 2: Delete tuples from Finance department

sql
DELETE FROM instructor
WHERE dept_name = 'Finance';

Result: Only instructors in Finance department are deleted

Example 3: Delete based on salary range

sql

DELETE FROM instructor


WHERE salary BETWEEN 10000 AND 15000;

Result: Deletes all instructors with salaries between 10,000 and 15,000

19. DELETE WITH NESTED SUBQUERY

Example 1: Delete all instructors from departments in building Watson

sql

DELETE FROM instructor


WHERE dept_name IN (
SELECT dept_name
FROM department
WHERE building = 'Watson'
);

How it works:

1. Inner query: Find all departments in Watson building


2. Outer query: Delete all instructors belonging to those departments

Notes:

Query can have only one relation in DELETE


If we want to delete from several relations, we must use one DELETE command for each relation

Example 2: Nested SELECT with Correlated Subquery

Delete all tuples belonging to instructors whose salaries are below average:

sql
DELETE FROM instructor
WHERE salary < (
SELECT AVG(salary)
FROM instructor
);

Important Notes:

Tuples to be deleted belong to relation instructor


Nested query to be executed on tuples of same relation instructor
Here, computation order matters!

20. DELETE - EXECUTION ORDER MATTERS


Problem Scenario: If some tuples are deleted before other tuples are tested:

Average salary may change


Final result will depend on order of tuple processing

Solution: SQL follows this process:

1. Compute avg (calculate average first)


2. Take one tuple from outer query and test salary < avg(salary)
3. If test is TRUE, delete the tuple

Critical Point: Here, if tuple is deleted, the resultant number of tuples in instructor relation will be less by one
tuple. In the next computation of avg in subquery, it will be affected.

Therefore: Performing all tests ( salary < avg(salary) ) BEFORE performing any deletion is important.

🎯 PART 4: INSERT STATEMENT


21. INSERT - BASIC SYNTAX
Purpose: Add data into a relation

Two Methods:

Method 1: Insert statement with tuple values

sql
INSERT INTO relation
VALUES (value1, value2, ..., valueN);

Method 2: Write query whose result will be set of tuples to be inserted

sql

INSERT INTO relation


SELECT ...
FROM ...
WHERE ...;

22. INSERT - EXAMPLES

Example 1: Insert single tuple

sql

INSERT INTO course


VALUES ('CS-437', 'Database', 'Comp. Sci.', 4);

Order of values: Same as order of attributes in the relation

Example 2: Specify attributes explicitly


If we forget order of attributes, SQL allows attributes to be mentioned:

sql

INSERT INTO course (course_id, title, dept_name, credits)


VALUES ('CS-437', 'Database', 'Comp. Sci.', 4);

Example 3: Insert with different attribute order

sql

INSERT INTO course (title, course_id, credits, dept_name)


VALUES ('Database', 'CS-437', 4, 'Comp. Sci.');

Here, order of values is same as order of attributes in INSERT statement


23. INSERT - USING SUBQUERY

Both INSERT statements have same effect:

Statement 1:

sql

INSERT INTO course (course_id, title, dept_name, credits)


VALUES ('CS-437', 'Database', 'Comp. Sci.', 4);

Statement 2:

sql

INSERT INTO course (title, course_id, credits, dept_name)


VALUES ('Database', 'CS-437', 4, 'Comp. Sci.');

Example: Insert using query result


Make each student in Music department who has earned > 144 credit hours an instructor with salary
$18,000

sql

INSERT INTO instructor


SELECT ID, name, dept_name, 18000
FROM student
WHERE dept_name = 'Music' AND tot_cred > 144;

How it works:

1. Subquery will be fully evaluated first


2. Then all tuples will be inserted into relation instructor
3. Important: Subquery is fully evaluated BEFORE insertion starts

24. BULK LOADER UTILITIES


Most relational database products have special 'bulk loader' utilities to insert large set of tuples into a
relation.

Features:

These utilities allow data to be read from formatted text files


Can execute much faster than equivalent sequence of INSERT statements
🎯 PART 5: UPDATE STATEMENT
25. UPDATE - BASIC SYNTAX
Purpose: Change value in a tuple without changing all values in the tuple

Syntax:

sql

UPDATE relation
SET attribute = value
WHERE condition;

Key Point:

Instead of changing all values in tuple


We can selectively update specific attributes

26. UPDATE - SIMPLE EXAMPLES

Example 1: Increase all instructors' salaries by 5%

sql

UPDATE instructor
SET salary = salary * 1.05;

Result: Every instructor's salary increases by 5%

Example 2: Conditional update

Increase salary by 5% of those instructors whose salaries are less than 70,000

sql

UPDATE instructor
SET salary = salary * 1.05
WHERE salary < 70000;
27. UPDATE - USING CASE STATEMENT

SQL provides CASE construct that can be used for multiple updates using single UPDATE statement

General Form:

sql

CASE
WHEN pred1 THEN result1
WHEN pred2 THEN result2
...
WHEN predn THEN resultn
ELSE result0
END

Example: Multiple conditional updates


Problem: Increase salary of instructors by:

3% who get salary > 100,000


5% of the others

Solution:

Method 1: Two UPDATE statements

sql

UPDATE instructor
SET salary = salary * 1.03
WHERE salary > 100000;

UPDATE instructor
SET salary = salary * 1.05
WHERE salary <= 100000;

Method 2: Single UPDATE with CASE

sql
UPDATE instructor
SET salary = CASE
WHEN salary <= 100000 THEN salary * 1.05
ELSE salary * 1.03
END;

Advantages of CASE:

Single statement
Cleaner code
More efficient

28. NESTED SELECT IN UPDATE

In general, WHERE clause of UPDATE statement may contain any legal construct including nested
SELECT

Example: Nested SELECT in WHERE clause


As with INSERT and DELETE, a nested SELECT within an UPDATE statement may reference the
relation that is being updated.

Example structure:

sql

UPDATE instructor
SET salary = (
SELECT AVG(salary)
FROM instructor
)
WHERE ...;

🎯 PART 6: TRIGGERS
29. WHAT ARE TRIGGERS?
Definition: A trigger is a statement that the system executes automatically as a side effect of a modification to
the database.

Purpose:

Type of action to be taken when certain events or conditions are satisfied


Active database (triggers run automatically)
Can execute before, after, etc.

Basic Structure:

sql

CREATE TRIGGER trigger_name


BEFORE/AFTER INSERT/UPDATE/DELETE OF attribute
ON table_name
FOR EACH ROW
WHEN (condition)
action;

30. TRIGGER EXAMPLE

Example: Salary violation trigger

Create trigger to inform supervisor when new salary > selected salary:

sql

CREATE TRIGGER salary_violation


BEFORE INSERT OR UPDATE OF salary, supervisor_ssn
ON Employee
FOR EACH ROW
WHEN ([Link] > (
SELECT salary
FROM Employee
WHERE SSN = NEW.supervisor_ssn
))
INFORM_SUPERVISOR(NEW.supervisor_ssn, [Link]);

How it works:

1. Trigger activates BEFORE INSERT or UPDATE on Employee


2. Checks if new employee's salary > their supervisor's salary
3. If TRUE, calls INFORM_SUPERVISOR procedure
4. FOR EACH ROW means trigger executes for every affected row

🎯 PART 7: VIEWS
31. WHAT ARE VIEWS?
Definition:
Views are NOT part of logical database schema (logical model)
A view is a virtual relation and is visible to users
A view is created using an SQL statement
Several views can be defined on top of given set of relations

32. CREATING VIEWS


Syntax:

sql

CREATE VIEW view_name AS


<query expression>;

Query expression: Any legal SQL expression

Example 1: Simple view


Suppose we want to hide salary attribute from clerk, we define view over relation instructor:

sql

CREATE VIEW faculty AS


SELECT ID, name, dept_name
FROM instructor;

Now, faculty is a view name

33. USING VIEWS

Example 2: Using view


Using view to select data:

sql

SELECT fname, lname


FROM WORKS_ON1
WHERE pname = 'ProductX';

34. DROP VIEW


Syntax:

sql

DROP VIEW view_name;

Example:

sql

DROP VIEW WORKS_ON1;

35. UPDATE VIEW


Updating views can be problematic!

Update View Syntax:

sql

UPDATE view_name
SET attribute = value
WHERE condition;

Example:

sql

UPDATE WORKS_ON1
SET pname = 'ProductY'
WHERE lname = 'Smith'
AND fname = 'John'
AND pname = 'ProductX';

Problem:

Problems may occur because of related logic


Updates to views may not always translate clearly to base tables

36. MATERIALIZED VIEWS


Definition: Certain database systems allow view relations to be stored, but they make sure that if actual
relations used in view definition change, the view is kept up-to-date.

Such views are called MATERIALIZED VIEWS


37. VIEW DEFINITIONS
Key Points:

Database system stores query expression associated with view relation, rather than result of evaluation
of query expression that defines view
Thus, view relations are created whenever needed, on demand
Once view relation is computed and stored, it becomes outdated when relations defining view are
modified
To avoid this, views are usually implemented as follows:

Implementation: When we define view, database system stores:

Definition of view itself


Rather than result of evaluation of query expression that defines view

On-Demand Creation: Whenever view relation appears in query:

It is replaced by stored query expression

38. MATERIALIZED VIEW - DETAILED


Few database systems allow view relation to be stored:

Key Feature: They make sure that if actual relations used in view definition change, the view is kept up-to-
date.

Such views are called MATERIALIZED VIEWS

Benefits:

Faster query performance (pre-computed)


No need to recompute on every access

Drawback:

Takes up storage space


Needs to be refreshed when base tables change

🎯 PART 8: MEMORY TRICKS & MNEMONICS


39. MASTER MEMORY TECHNIQUES
1. "SEND" for Subqueries

Scalar (single value)


Exists (test for existence)
Nested (correlated)
Derived (in FROM clause)

2. "SAW" for Set Operators

SOME (at least one)


ALL (every value)
WHERE (test location)

3. "DIU" for Data Modifications

DELETE (remove tuples)


INSERT (add tuples)
UPDATE (modify tuples)

4. EXISTS vs. NOT EXISTS


Memory Trick: "EXIT Sign"

EXISTS → Is there an EXIT? (Is set non-empty?)


NOT EXISTS → No EXIT? (Is set empty?)

5. SOME vs. ALL


Memory Trick: "SOME Friends vs. ALL Friends"

SOME → At least ONE friend agrees


ALL → EVERY friend must agree

Visual:

SOME: Need 1 person ✓


ALL: Need everyone ✓✓✓✓
6. Trigger Timing
Memory Trick: "BAD Actions"

BEFORE (check before change)


AFTER (respond after change)
During not allowed!

7. View Types
Memory Trick: "REAL vs. VIRTUAL"

Regular View → Virtual (computed on demand)


Materialized View → Real (stored physically)

8. Correlated Subquery Execution


Memory Trick: "Nested Loops"

For each OUTER row:


Execute INNER query
Test condition
Include/Exclude row

9. CASE Statement
Memory Trick: "Switch Cases" Like switch statement in programming:

CASE = SWITCH
WHEN = IF/ELSE IF
ELSE = DEFAULT

🎯 PART 9: PRACTICE QUESTIONS


40. CONCEPTUAL QUESTIONS

Q1: What is the difference between a scalar subquery and a correlated subquery?

Answer:
Scalar subquery: Returns single value (1 row, 1 column), can be used anywhere a value is expected
Correlated subquery: References columns from outer query, executed once per outer row

Q2: Explain the scoping rule for correlation variables in nested queries.

Answer: Correlation names can be used if defined:

1. Locally in the subquery itself, OR


2. In any query that contains the subquery If defined both locally and globally, local definition takes
precedence (like variable scoping in programming)

Q3: Why is order important when executing DELETE statements with subqueries?

Answer: If some tuples are deleted before others are tested, aggregate values (like AVG) in the subquery may
change, causing inconsistent results. SQL solves this by testing all tuples first, then deleting marked tuples.

Q4: What is the difference between EXISTS and IN?

Answer:

IN: Checks if value matches any value in a list/subquery result


EXISTS: Checks if subquery returns at least one row (tests for non-empty set)
EXISTS is typically more efficient for large datasets

Q5: What are materialized views and why use them?

Answer: Materialized views store the query result physically (unlike regular views which compute on demand).
Benefits: faster query performance. Drawback: requires storage and must be refreshed when base tables change.

41. TECHNICAL QUESTIONS

Q6: Write a query using EXISTS to find students who have taken at least one course.

Answer:

sql
SELECT [Link], [Link]
FROM student S
WHERE EXISTS (
SELECT *
FROM takes T
WHERE [Link] = [Link]
);

Q7: Write a query using NOT EXISTS to find students who have NOT taken any courses.

Answer:

sql

SELECT [Link], [Link]


FROM student S
WHERE NOT EXISTS (
SELECT *
FROM takes T
WHERE [Link] = [Link]
);

Q8: What is the difference between these two queries?

sql

-- Query 1
SELECT name FROM instructor
WHERE salary > SOME (SELECT salary FROM instructor WHERE dept_name = 'CS');

-- Query 2
SELECT name FROM instructor
WHERE salary > ALL (SELECT salary FROM instructor WHERE dept_name = 'CS');

Answer:

Query 1 (SOME): Returns instructors whose salary is greater than AT LEAST ONE CS instructor
Query 2 (ALL): Returns instructors whose salary is greater than EVERY CS instructor (i.e., greater than
the maximum CS salary)
Q9: Write UPDATE statement using CASE to give 10% raise to instructors with salary < 50000, and 5% raise
to others.

Answer:

sql

UPDATE instructor
SET salary = CASE
WHEN salary < 50000 THEN salary * 1.10
ELSE salary * 1.05
END;

Q10: Create a view that shows course_id and total number of students enrolled in each course.

Answer:

sql

CREATE VIEW course_enrollment AS


SELECT course_id, COUNT(DISTINCT ID) AS total_students
FROM takes
GROUP BY course_id;

42. SCENARIO-BASED QUESTIONS


Q11: You need to delete all employees whose salary is below the department average. Write the query.

Answer:

sql

DELETE FROM employee E


WHERE salary < (
SELECT AVG(salary)
FROM employee
WHERE dept_id = E.dept_id
);

Q12: Create a trigger that prevents insertion of student records with tot_cred < 0.

Answer:

sql
CREATE TRIGGER check_credits
BEFORE INSERT ON student
FOR EACH ROW
WHEN (NEW.tot_cred < 0)
BEGIN
RAISE_APPLICATION_ERROR(-20001, 'Credits cannot be negative');
END;

Q13: Find departments where all instructors earn more than 50000. Use NOT EXISTS.

Answer:

sql

SELECT DISTINCT D.dept_name


FROM department D
WHERE NOT EXISTS (
SELECT *
FROM instructor I
WHERE I.dept_name = D.dept_name
AND [Link] <= 50000
);

Q14: Insert all students with tot_cred > 100 into a new table called "senior_students".

Answer:

sql

INSERT INTO senior_students


SELECT *
FROM student
WHERE tot_cred > 100;

Q15: Create view showing instructor names with their department building names.

Answer:

sql
CREATE VIEW instructor_location AS
SELECT [Link], I.dept_name, [Link]
FROM instructor I
JOIN department D ON I.dept_name = D.dept_name;

43. COMPARISON QUESTIONS


Q16: Compare: = SOME vs IN

Answer: They are equivalent!

sql

-- These are the same:


WHERE x = SOME (subquery)
WHERE x IN (subquery)

Q17: Compare: <> ALL vs NOT IN

Answer: They are equivalent!

sql

-- These are the same:


WHERE x <> ALL (subquery)
WHERE x NOT IN (subquery)

Q18: Compare regular views vs. materialized views.

Answer:

Feature Regular View Materialized View

Storage Definition only Definition + Data

Computation On every access Pre-computed

Speed Slower Faster

Up-to-date Always current Needs refresh

Space Minimal Requires storage


Q19: When should you use correlated subquery vs. join?

Answer:

Correlated Subquery: Use when testing existence, comparing with aggregates, or when logic is clearer
JOIN: Usually more efficient for retrieving data from multiple tables, especially for large datasets
Modern query optimizers often convert between them anyway

Q20: What's the difference between BEFORE and AFTER triggers?

Answer:

BEFORE trigger: Executes before the modification, can prevent/modify the change
AFTER trigger: Executes after the modification, used for logging or cascading actions
BEFORE triggers can access NEW values and modify them; AFTER triggers cannot

44. ADVANCED QUESTIONS


Q21: Write query to find students who have taken ALL courses offered by CS department.

Answer:

sql

SELECT [Link], [Link]


FROM student S
WHERE NOT EXISTS (
(SELECT course_id FROM course WHERE dept_name = 'CS')
EXCEPT
(SELECT course_id FROM takes WHERE [Link] = [Link])
);

Logic: If (CS courses EXCEPT courses taken by student) is empty, student has taken all CS courses.

Q22: Explain why this DELETE might give unexpected results:

sql

DELETE FROM instructor


WHERE salary < (SELECT AVG(salary) FROM instructor);

Answer: Without proper handling, as tuples are deleted, the AVG changes. SQL handles this by:
1. Computing AVG first
2. Testing all tuples
3. Then deleting marked tuples This ensures consistent behavior regardless of processing order.

Q23: Create a view that cannot be updated and explain why.

Answer:

sql

CREATE VIEW high_salary_count AS


SELECT dept_name, COUNT(*) AS num_high_salary
FROM instructor
WHERE salary > 80000
GROUP BY dept_name;

Why not updatable:

Contains aggregate function (COUNT)


Contains GROUP BY
No direct mapping to base table rows

Q24: Write trigger to log all salary changes in an audit table.

Answer:

sql

CREATE TRIGGER audit_salary_changes


AFTER UPDATE OF salary ON instructor
FOR EACH ROW
BEGIN
INSERT INTO salary_audit (instructor_id, old_salary, new_salary, change_date)
VALUES ([Link], [Link], [Link], CURRENT_DATE);
END;

Q25: Find instructors who earn more than the average salary of instructors in their own department.

Answer:

sql
SELECT [Link], I.dept_name, [Link]
FROM instructor I
WHERE [Link] > (
SELECT AVG(salary)
FROM instructor
WHERE dept_name = I.dept_name
);

🎯 PART 10: COMPREHENSIVE SUMMARY


45. QUICK REFERENCE TABLE

Concept Syntax Use Case

Scalar Subquery (SELECT AVG(...)) Single value comparison

IN / NOT IN WHERE x IN (subquery) Set membership testing

EXISTS WHERE EXISTS (subquery) Test for non-empty set

NOT EXISTS WHERE NOT EXISTS (...) Test for empty set

SOME WHERE x > SOME (...) Compare with at least one

ALL WHERE x > ALL (...) Compare with every value

DELETE DELETE FROM r WHERE ... Remove tuples

INSERT INSERT INTO r VALUES (...) Add tuples

UPDATE UPDATE r SET ... WHERE ... Modify tuples

CASE CASE WHEN ... THEN ... END Conditional values

CREATE VIEW CREATE VIEW v AS SELECT ... Define virtual table

TRIGGER CREATE TRIGGER ... BEFORE/AFTER ... Automatic actions

46. OPERATOR EQUIVALENCES

sql
-- These pairs are equivalent:
x = SOME (subquery) ≡ x IN (subquery)
x <> ALL (subquery) ≡ x NOT IN (subquery)

-- Negations:
NOT (x > SOME y) ≡ x <= ALL y
NOT (x > ALL y) ≡ x <= SOME y

47. EXECUTION ORDER RULES


For DELETE/UPDATE with subqueries:

1. Evaluate subquery (compute aggregates, get result set)


2. Test all tuples (mark tuples that satisfy condition)
3. Execute modification (delete/update marked tuples)

This ensures:

Consistent results
No dependency on processing order
Aggregate values don't change mid-operation

48. VIEW UPDATE RULES


Views are updatable if:

Defined on single base table


SELECT clause contains only attribute names (no expressions)
No aggregate functions
No GROUP BY or HAVING
No DISTINCT

Views are NOT updatable if:

Join of multiple tables


Contains aggregates
Contains GROUP BY
Contains calculated columns
49. BEST PRACTICES
Subqueries:

1. Use EXISTS instead of IN for better performance with large datasets


2. Avoid correlated subqueries when simple joins work
3. Use WITH clause for complex queries (better readability)

Modifications:

1. Always test DELETE/UPDATE with SELECT first


2. Use transactions for multi-step modifications
3. Be aware of execution order in correlated queries

Views:

1. Use views for security (hide columns)


2. Use views for simplification (complex joins)
3. Consider materialized views for frequently accessed complex queries

Triggers:

1. Keep trigger logic simple


2. Avoid recursive triggers
3. Use triggers sparingly (they can hide business logic)

50. COMMON PITFALLS & SOLUTIONS


Pitfall 1: Forgetting NOT EXISTS logic

sql
-- WRONG: Find students who took all CS courses
SELECT [Link] FROM student S
WHERE [Link] IN (SELECT ID FROM takes WHERE course_id IN
(SELECT course_id FROM course WHERE dept_name = 'CS'));

-- CORRECT:
SELECT [Link] FROM student S
WHERE NOT EXISTS (
(SELECT course_id FROM course WHERE dept_name = 'CS')
EXCEPT
(SELECT course_id FROM takes WHERE [Link] = [Link])
);

Pitfall 2: Incorrect SOME/ALL usage

sql

-- WRONG: Greater than all CS salaries


SELECT name FROM instructor
WHERE salary > SOME (SELECT salary FROM instructor WHERE dept_name = 'CS');

-- CORRECT:
SELECT name FROM instructor
WHERE salary > ALL (SELECT salary FROM instructor WHERE dept_name = 'CS');

Pitfall 3: View update problems

sql

-- This view CANNOT be updated:


CREATE VIEW dept_stats AS
SELECT dept_name, AVG(salary) AS avg_sal
FROM instructor
GROUP BY dept_name;

-- This will fail:


UPDATE dept_stats SET avg_sal = 90000 WHERE dept_name = 'CS';
-- Error: Cannot update aggregate

Pitfall 4: Trigger recursion


sql

-- DANGER: Recursive trigger


CREATE TRIGGER update_salary
AFTER UPDATE OF salary ON instructor
FOR EACH ROW
BEGIN
UPDATE instructor SET salary = salary * 1.1 WHERE ID = [Link];
-- This triggers itself again!
END;

🎯 CONCLUSION
This comprehensive guide covers:

Nested & Correlated Subqueries


Set Comparison Operators (SOME, ALL, EXISTS)
Database Modifications (DELETE, INSERT, UPDATE)
CASE Statements
Triggers
Views (Regular & Materialized)

Study Tips:

1. Practice writing queries step-by-step


2. Draw execution diagrams for complex queries
3. Test queries with small datasets first
4. Understand execution order (especially for correlated subqueries)
5. Use memory tricks to remember operators
6. Compare equivalent forms (e.g., EXISTS vs IN)

Most Important Concepts:

1. Correlated subqueries and scoping rules


2. Difference between SOME and ALL
3. EXISTS vs NOT EXISTS logic
4. Execution order for DELETE/UPDATE
5. When views are updatable
6. Trigger timing (BEFORE vs AFTER)
Good luck with your studies! 📚🎓

You might also like