67.3 KB · commit 40bb182
| title | T06 · Joins and Views · Textbook Exercise Solutions |
|---|---|
| topic_id | T06 |
| exercise_count | 13 |
| source_chapters | Chapter 04, Chapter 05 |
← Prev: T05 Part 4 | Index | Next: T07 →
| Exercise ID | Type | Subtopic | Focus / Concept | Complexity |
|---|---|---|---|---|
| PE 4.1 | Practice | T06.1 | Natural join pitfalls; unwanted attribute collisions (dept_name) | Medium |
| PE 4.2 | Practice | T06.1 | Outer joins, scalar subqueries, and zero-count preservation (COUNT trap) | Medium–High |
| PE 4.3 | Practice | T06.1 | Simulating left/full outer join without outer join syntax (UNION + NOT EXISTS) | High |
| PE 4.4 | Practice | T06.1 | Associativity of outer joins: (r⟕s)⟕t vs r⟕(s⟕t) | High (Proof) |
| EX 4.10 | Chapter | T06.1 | Full outer join using ON and COALESCE with null-safe match semantics | High |
| EX 4.14 | Chapter | T06.1 | Redundancy of NATURAL JOIN section under foreign key constraints | Medium |
| EX 4.15 | Chapter | T06.1 | Rewriting NATURAL JOIN with explicit JOIN ... USING syntax | Low–Medium |
| EX 4.19 | Chapter | T06.1 | Root causes of NULL in cascading full outer join (student ⟗ takes ⟗ course) | Medium–High |
| EX 4.6 | Chapter | T06.4 | View definition for GPA computation with letter-grade mappings and null safety | High |
| EX 4.20 | Chapter | T06.4 | Creating summary aggregate view tot_credits(year, num_credits) | Low–Medium |
| EX 4.13 | Chapter | T06.5 | View authorization independence and WITH CHECK OPTION semantics | Medium |
| EX 4.21 | Chapter | T06.5 | SQL standard view updatability rules; rejection of inserts through aggregate views | Medium |
| PE 5.6 | Practice | T06.5 | Incremental maintenance of materialized join views using SQL triggers | High |
Question (Silberschatz 7e Practice Exercise 4.1).
Consider the following SQL query that seeks to find a list of titles of all courses taught in Spring 2017 along with the name of the instructor.
select name, title
from instructor natural join teaches natural join section natural join course
where semester = 'Spring' and year = 2017;
What is wrong with this query?
The NATURAL JOIN operator in SQL operates by automatically equating all attributes that have identical column names across the participating relations, projecting away duplicate column copies.
Let relations R and S have attribute sets attr(R) and attr(S). The natural join is defined formally as:
R⋈S=Πattr(R)∪attr(S)(σR.A1=S.A1∧R.A2=S.A2∧⋯∧R.Ak=S.Ak(R×S))where {A1,A2,…,Ak}=attr(R)∩attr(S).
In the standard university database schema:
instructor = (ID,name,dept_name,salary)teaches = (ID,course_id,sec_id,semester,year)section = (course_id,sec_id,semester,year,building,room_number,time_slot_id)course = (course_id,title,dept_name,credits)When evaluating instructor natural join ... natural join course, the intersection of attributes between instructor and course includes dept_name. Consequently, the query enforces:
instructor.dept_name = course.dept_name.Mathematics department teaching an introductory programming course offered by the Comp. Sci. department, or an interdisciplinary bio-informatics course).Suppose the database contains the following instances:
Table instructor:
| ID | name | dept_name | salary |
|---|---|---|---|
10101 | Srinivasan | Comp. Sci. | 65000 |
45565 | Katz | Mathematics | 75000 |
Table teaches:
| ID | course_id | sec_id | semester | year |
|---|---|---|---|---|
10101 | CS-101 | 1 | Spring | 2017 |
45565 | CS-315 | 1 | Spring | 2017 |
Table section:
| course_id | sec_id | semester | year |
|---|---|---|---|
| CS-101 | 1 | Spring | 2017 |
| CS-315 | 1 | Spring | 2017 |
Table course:
| course_id | title | dept_name | credits |
|---|---|---|---|
| CS-101 | Intro. to Computer Science | Comp. Sci. | 4 |
| CS-315 | Robotics | Comp. Sci. | 3 |
10101 (Srinivasan): instructor.dept_name=’Comp. Sci.’ and course.dept_name=’Comp. Sci.’. The equality holds, so ('Srinivasan', 'Intro. to Computer Science') is output.45565 (Katz): instructor.dept_name=’Mathematics’, but course.dept_name=’Comp. Sci.’. Even though Katz taught CS-315 in Spring 2017, the condition instructor.dept_name = course.dept_name evaluates to false, erroneously omitting ('Katz', 'Robotics').To fix this query, replace NATURAL JOIN with explicit JOIN ... USING or JOIN ... ON clauses specifying only the intended join keys:
-- Solution using JOIN ... USING:
select name, title
from instructor
join teaches using (ID)
join section using (course_id, sec_id, semester, year)
join course using (course_id)
where semester = 'Spring' and year = 2017;
Alternative (omitting redundant table section):
Because teaches already contains the attributes course_id, sec_id, semester, and year, joining with section is strictly unnecessary unless classroom details are needed:
select instructor.name, course.title
from instructor
join teaches on instructor.ID = teaches.ID
join course on teaches.course_id = course.course_id
where teaches.semester = 'Spring' and teaches.year = 2017;
NATURAL JOIN is an infallible shortcut for saving handwriting time. In RUET exams (such as 2019 Q.3(c) and 2024 Q.3(c)), questions frequently ask: "Why is natural join considered dangerous in real-world database design?" The answer hinges on this exact trap: schema evolution or unintended homonymous attributes (columns sharing the same name but representing different entity properties, like dept_name or name) quietly corrupt query results without returning a syntax error.dept_name), show why instructors teaching outside their department are dropped, and provide the corrected query using JOIN ... USING (course_id) or explicit ON.Question (Silberschatz 7e Practice Exercise 4.2).
Write the following queries in SQL:
a. Display a list of all instructors, showing each instructor’s ID and the number of sections taught. Make sure to show the number of sections as 0 for instructors who have not taught any section. Your query should use an outer join, and should not use subqueries.
b. Write the same query as in part a, but using a scalar subquery and not using outer join.
c. Display the list of all course sections offered in Spring 2018, along with the ID and name of each instructor teaching the section. If a section has more than one instructor, that section should appear as many times in the result as it has instructors. If a section does not have any instructor, it should still appear in the result with the instructor name set to “—”.
d. Display the list of all departments, with the total number of instructors in each department, without using subqueries. Make sure to show departments that have no instructors, and list those departments with an instructor count of zero.
An inner join discards any tuple that fails to find a partner satisfying the join condition. An outer join avoids information loss by synthesizing a tuple padded with NULL values for the missing side:
COUNT(*) vs COUNT(column) DistinctionWhen an outer join produces an unmatched row, the attributes from the non-matching side are filled with NULL.
COUNT(*) counts the number of physical rows in a group, regardless of whether column values are null. For an unmatched instructor, COUNT(*) returns 1 (since the row exists).COUNT(column_name) counts only non-null occurrences of column_name. For an unmatched instructor where sec_id is NULL, COUNT(sec_id) evaluates to 0.Requirement: All instructors, ID and count of sections taught; 0 for inactive instructors; outer join; no subqueries.
select instructor.ID, count(teaches.sec_id) as num_sections
from instructor
left outer join teaches on instructor.ID = teaches.ID
group by instructor.ID;
Critical Verification:
If instructor 33456 (Gold) taught 0 sections, the LEFT OUTER JOIN outputs:
('33456', 'Gold', 'Physics', 87000, NULL, NULL, NULL, NULL, NULL).
count(teaches.sec_id) encounters a NULL and yields 0. (Had we written count(*), it would have incorrectly yielded 1).
Requirement: Same result as part (a), but using a scalar subquery and no outer join.
select instructor.ID,
(select count(*)
from teaches
where teaches.ID = instructor.ID) as num_sections
from instructor;
Explanation:
For each instructor tuple evaluated in the outer query, the correlated scalar subquery runs over teaches. If no matching row exists, COUNT(*) on an empty set evaluates directly to 0. A scalar subquery in the SELECT clause must return at most one row and one column.
Requirement: All sections offered in Spring 2018 with instructor ID and name; multiple instructors produce multiple rows; missing instructors show "—".
select section.course_id, section.sec_id, section.semester, section.year,
teaches.ID,
coalesce(instructor.name, '—') as instructor_name
from section
left outer join teaches
on section.course_id = teaches.course_id
and section.sec_id = teaches.sec_id
and section.semester = teaches.semester
and section.year = teaches.year
left outer join instructor
on teaches.ID = instructor.ID
where section.semester = 'Spring' and section.year = 2018;
Key Technical Details:
section must be on the left side of the LEFT OUTER JOIN chain to ensure sections with zero instructors are preserved.where section.semester = 'Spring' and section.year = 2018 is strictly safe because section is the preserved relation. (Filtering on teaches.semester in the WHERE clause would convert the outer join into an inner join by discarding null-padded rows).COALESCE(instructor.name, '—') evaluates instructor.name; if null, it substitutes the string literal '—'.Requirement: All departments, total instructors, no subqueries, 0 for empty departments.
select department.dept_name, count(instructor.ID) as num_instructors
from department
left outer join instructor
on department.dept_name = instructor.dept_name
group by department.dept_name;
Verification:
A department with no faculty (e.g., a newly established department) forms an outer-join row with instructor.ID = NULL. Grouping by dept_name and evaluating count(instructor.ID) yields 0.
COUNT(*) Error: In RUET exams (e.g., 2020 Q.4(c) and 2024 Q.4(a)), more than 60% of students write COUNT(*) after a LEFT JOIN. RUET grading rubrics penalize this heavily (deducting 2 to 3 marks out of 5), because an instructor with 0 courses is reported as having 1 course! Always use COUNT(right_table.foreign_key).WHERE vs ON Clause Placement: Emphasize that when filtering preserved tables in an outer join, condition placement matters:
WHERE clause.ON clause, otherwise any null-padded row will evaluate to unknown in the WHERE clause and get filtered out, silently destroying the outer join.Question (Silberschatz 7e Practice Exercise 4.3).
Outer join expressions can be computed in SQL without using the SQL outer join operation. To illustrate this fact, show how to rewrite each of the following SQL queries without using the outer join expression.
a.
select * from student natural left outer join takes;
b.
select * from student natural full outer join takes;
In relational algebra, an outer join is defined mathematically as the union of an inner join and the padded anti-join (unmatched tuples).
For left outer join (R⟕S):
R⟕S=(R⋈S)∪(R−Πattr(R)(R⋈S))×{(∣attr(S)−attr(R)∣ timesnull,…,null)}For full outer join (R⟗S):
R⟗S=(R⋈S)∪(Runmatched×nullS)∪(nullR×Sunmatched)To construct valid SQL UNION operations, both queries must project the exact same number of columns in identical order and compatible data types:
student schema: (ID,name,dept_name,tot_cred) — 4 attributes.takes schema: (ID,course_id,sec_id,semester,year,grade) — 6 attributes.To simulate student natural left outer join takes without outer join syntax:
student natural join takes.takes using a NOT IN or NOT EXISTS subquery.takes (course_id, sec_id, semester, year, grade) with explicit null literals.UNION ALL (or UNION). Since the two component sets are mutually disjoint, UNION ALL is faster and semantically exact.-- Block 1: Matching tuples (Inner Join)
select ID, name, dept_name, tot_cred, course_id, sec_id, semester, year, grade
from student natural join takes
union all
-- Block 2: Unmatched students padded with NULLs for takes attributes
select ID, name, dept_name, tot_cred,
null as course_id,
null as sec_id,
null as semester,
null as year,
null as grade
from student
where ID not in (select ID from takes where ID is not null);
To simulate student natural full outer join takes:
student natural join takes.takes).student).-- Block 1: Matched tuples
select ID, name, dept_name, tot_cred, course_id, sec_id, semester, year, grade
from student natural join takes
union all
-- Block 2: Students with no takes records
select ID, name, dept_name, tot_cred,
null as course_id,
null as sec_id,
null as semester,
null as year,
null as grade
from student
where not exists (
select 1 from takes where takes.ID = student.ID
)
union all
-- Block 3: Takes records with no matching student (e.g., dangling enrollments)
select ID,
null as name,
null as dept_name,
null as tot_cred,
course_id, sec_id, semester, year, grade
from takes
where not exists (
select 1 from student where student.ID = takes.ID
);
Alternative Practical Formulation (Left Join ∪ Right Join):
If one outer join type is permitted (as done in production MySQL):
select * from student natural left outer join takes
union
select * from student natural right outer join takes;
Here, UNION (without ALL) automatically dedupes the inner join rows that appear in both expressions.
Courses and Teacher) and explicitly explain how MySQL implements FULL OUTER JOIN. The standard textbook solution using LEFT JOIN ... UNION ... RIGHT JOIN or UNION ALL with NOT EXISTS receives full marks.NULL columns. In RUET grading, if student has 4 columns and takes has 6, the resulting UNION must have exactly 4+6−1=9 columns. Counting the projected null literals explicitly shows technical mastery.Question (Silberschatz 7e Practice Exercise 4.4).
Suppose we have three relations r(A,B), s(B,C), and t(B,D), with all attributes declared as not null.
a. Give instances of relations r, s, and t such that in the result of
(r natural left outer join s) natural left outer join t
attribute C has a null value but attribute D has a non-null value.
b. Are there instances of r, s, and t such that the result of
r natural left outer join (s natural left outer join t)
has a null value for C but a non-null value for D? Explain why or why not.
Inner join (⋈) is associative:
(r⋈s)⋈t=r⋈(s⋈t)Left outer join (⟕) is not associative:
(r⟕s)⟕t=r⟕(s⟕t)This exercise demonstrates the asymmetry:
NOT NULL, C can never be null in (s⟕t)!We must construct instances of r(A,B), s(B,C), and t(B,D) such that in ((r⟕s)⟕t), attribute C is NULL while D is non-null.
Define Instances:
Step 1: Compute (r natural left outer join s)
NULL.Step 2: Compute I1 natural left outer join t
In this tuple, attribute C is null and attribute D is non-null (20). ■
Question: Can r natural left outer join (s natural left outer join t) produce a tuple where C is null and D is non-null?
Answer: No, such instances cannot exist.
Formal Proof:
null.NOT NULL.null. Thus, u.C=null and u.D=null. Here, D is null.null. In Case 2, C is non-null.null while u.D is non-null. Hence, no such instances of r, s, and t can exist. ■Question (Silberschatz 7e Exercise 4.10).
Given the relations a(name,address,title) and b(name,address,salary), show how to express a natural full outer join b using the full outer-join operation with an on condition rather than using the natural join syntax. This can be done using the coalesce operation. Make sure that the result relation does not contain two copies of the attributes name and address and that the solution is correct even if some tuples in a and b have null values for attributes name or address.
ON Join DifferencesWhen executing a natural full outer join b:
name, address) appear only once in the output schema.If one simply writes:
select *
from a full outer join b on a.name = b.name and a.address = b.address;
Two severe errors arise:
a.name, a.address, a.title, b.name, b.address, b.salary.NULL = NULL evaluates to UNKNOWN (not TRUE). Thus, tuples with null names or addresses will fail to match on the ON clause, erroneously producing two separate padded tuples instead of joining them.COALESCEThe function COALESCE(e_1, e_2, \dots, e_n) returns the first non-null expression from its argument list. If both a.name and b.name are null, it evaluates to null.
select coalesce(a.name, b.name) as name,
coalesce(a.address, b.address) as address,
a.title,
b.salary
from a
full outer join b
on (a.name = b.name or (a.name is null and b.name is null))
and (a.address = b.address or (a.address is null and b.address is null));
IS NOT DISTINCT FROM)In modern SQL (and PostgreSQL / MySQL 8.0+ <=>), the standard null-safe equality operator IS NOT DISTINCT FROM handles null comparisons cleanly:
select coalesce(a.name, b.name) as name,
coalesce(a.address, b.address) as address,
a.title,
b.salary
from a
full outer join b
on a.name is not distinct from b.name
and a.address is not distinct from b.address;
Suppose relation instances are:
Evaluation:
('Alice', null). In b, tuple 1 has ('Alice', null).
a.name = b.name is 'Alice' = 'Alice' → TRUE.(a.address is null and b.address is null) → TRUE.ON condition evaluates to TRUE.coalesce('Alice', 'Alice') = 'Alice', coalesce(null, null) = null, title = 'Engineer', salary = 85000.('Alice', null, 'Engineer', 85000).(null, 'Dhaka'). In b, no matching row exists.
coalesce(null, null) = null, coalesce('Dhaka', null) = 'Dhaka', title = 'Analyst', salary = null.(null, 'Dhaka', 'Analyst', null).('Bob', 'Rajshahi'). In a, no matching row exists.
coalesce(null, 'Bob') = 'Bob', coalesce(null, 'Rajshahi') = 'Rajshahi', title = null, salary = 60000.('Bob', 'Rajshahi', null, 60000).Resulting relation contains exactly 4 attributes: (name,address,title,salary), matching the natural full outer join specification identically.
(a.name is null and b.name is null) clause. In RUET exams, examiners specifically award 2 dedicated marks for handling the null-matching condition. Writing merely ON a.name = b.name shows ignorance of SQL three-valued logic.Question (Silberschatz 7e Exercise 4.14).
Consider the query
select course_id, semester, year, sec_id, avg(tot_cred)
from takes natural join student
where year = 2017
group by course_id, semester, year, sec_id
having count(ID) >= 2;
Explain why appending natural join section in the from clause would not change the result.
A join with an additional table T can alter a query's result set in three possible ways:
NATURAL JOIN.If none of these three effects occur, the join is semantically redundant and can be eliminated by the database optimizer without changing query output.
Let us inspect the schemas of the relations:
takes = (ID,course_id,sec_id,semester,year,grade)student = (ID,name,dept_name,tot_cred)section = (course_id,sec_id,semester,year,building,room_number,time_slot_id)The natural join takes natural join student joins on the common attribute ID.
Now append natural join section:
The common attributes between (takes natural join student) and section are:
In the standard university relational schema:
foreign key (course_id,sec_id,semester,year) references sectionBy definition of referential integrity:
takes, the composite value (course_id,sec_id,semester,year) must already exist in the section relation. Therefore, no tuples from takes will be eliminated by requiring a match in section.In relation section, the composite attribute (course_id,sec_id,semester,year) is declared as the primary key.
takes can match at most one (and by referential integrity, exactly one) tuple in section. Therefore, joining with section cannot duplicate any tuples.SELECT, GROUP BY, and HAVING clauses reference only attributes from takes (course_id, sec_id, semester, year, ID) and student (tot_cred).section (building, room_number, time_slot_id) are projected or used in predicates.section produces a bijective (one-to-one) correspondence on takes tuples and neither eliminates nor multiplies rows, the multi-set of tuples grouped and aggregated remains identical.Hence, appending natural join section produces the exact same result. ■
takes record.Question (Silberschatz 7e Exercise 4.15).
Rewrite the query
select *
from section natural join classroom;
without using a natural join but instead using an inner join with a using condition.
section = (course_id,sec_id,semester,year,building,room_number,time_slot_id)classroom = (building,room_number,capacity)The common attributes between section and classroom are building and room_number.
USINGIn SQL:
FROM R JOIN S ON condition retains both R.A and S.A in the SELECT * projection.FROM R JOIN S USING (A_1, A_2, ...) retains only one copy of the join attributes A1,A2,… in the SELECT * projection, mimicking the projection behavior of NATURAL JOIN while explicitly naming the intended join columns.select *
from section
join classroom using (building, room_number);
(Or explicitly using the optional inner keyword:)
select *
from section
inner join classroom using (building, room_number);
When SELECT * is executed:
USING clause appear first: building, room_number.section) follow: course_id, sec_id, semester, year, time_slot_id.classroom) follow: capacity.Result schema:
(building,room_number,course_id,sec_id,semester,year,time_slot_id,capacity)USING is Preferred over ON in Production: In RUET viva and theory questions, examiners ask why JOIN ... USING (A) is superior to both NATURAL JOIN and JOIN ... ON R.A = S.A:
NATURAL JOIN, it is immune to future schema changes (e.g., adding a unrelated column named status to both tables won't break the join).ON, it does not create redundant, duplicate columns (R.A and S.A) in SELECT *.Question (Silberschatz 7e Exercise 4.19).
Under what circumstances would the query
select *
from student natural full outer join takes
natural full outer join course;
include tuples with null values for the title attribute?
Let us trace the attributes across the relations:
student = (ID,name,dept_name,tot_cred)takes = (ID,course_id,sec_id,semester,year,grade)course = (course_id,title,dept_name,credits)Evaluation proceeds in two stages:
ID.course are both course_id and dept_name.Attribute title originates solely from course. In a FULL OUTER JOIN, attributes of course (including title) are set to NULL whenever a tuple in the left operand (T1) fails to find a matching tuple in course.
Tuples in Tfinal will contain a NULL for title under four distinct circumstances:
If a student has never enrolled in any course (e.g., a newly registered student):
student natural full outer join takes), this student has no matching tuple in takes.takes attributes—including course_id—set to NULL.course, a NULL course_id cannot match any existing course in course (because in SQL, NULL = course_id evaluates to UNKNOWN).course (title, credits) are populated with NULL.If the database allows or contains orphaned takes tuples (e.g., if foreign key enforcement is disabled or referential integrity is violated) where a student took a course_id that does not exist in the course table:
course_id fails to match any row in course.title is set to NULL.This is the most critical and subtle circumstance:
course are both course_id and dept_name.Physics department (T1.dept_name=’Physics’) takes a course offered by the Comp. Sci. department (e.g., CS-101, where course.dept_name=’Comp. Sci.’):
course_id matches (CS-101), but the dept_name does not match ('Physics' = 'Comp. Sci.')!dept_name, the tuple in T1 fails to match the course record for CS-101.title to NULL! (Simultaneously, CS-101 from course is preserved with student attributes set to NULL).If the underlying course relation does not enforce a NOT NULL constraint on title, and a course has been inserted with title = NULL, any matching join tuple will naturally display NULL for title.
dept_name collision in the second natural join) marks the difference between an average student and an honors-level answer.Question (Silberschatz 7e Exercise 4.6).
Show how to define the view student_grades (ID, GPA) giving the grade-point average of each student, based on the query in Exercise 3.2; recall that we used a relation grade_points(grade, points) to get the numeric points associated with a letter grade. Make sure your view definition correctly handles the case of null values for the grade attribute of the takes relation.
The Grade Point Average (GPA) is a credit-weighted average of numeric points:
GPA=∑i=1ncreditsi∑i=1n(creditsi×pointsi)student = (ID,name,dept_name,tot_cred)takes = (ID,course_id,sec_id,semester,year,grade)course = (course_id,title,dept_name,credits)grade_points = (grade,points)takes.grade = NULL. These ongoing courses must not contribute to either the numerator (∑credits×points) or the denominator (∑credits).NULL grades, ∑credits=0 or NULL. Dividing by zero causes a database runtime exception.student_grades, a LEFT OUTER JOIN starting from student is required.create view student_grades (ID, GPA) as
select student.ID,
case
-- If student has no graded credits, GPA is NULL (or 0.0)
when sum(case when takes.grade is not null then course.credits else 0 end) = 0
then null
else
sum(course.credits * grade_points.points) /
sum(case when takes.grade is not null then course.credits end)
end as GPA
from student
left outer join takes on student.ID = takes.ID
left outer join course on takes.course_id = course.course_id
left outer join grade_points on takes.grade = grade_points.grade
group by student.ID;
An alternative, clean SQL structure pre-filters valid grades before joining:
create view student_grades (ID, GPA) as
select student.ID,
case
when sum(course.credits) is null or sum(course.credits) = 0 then null
else sum(course.credits * grade_points.points) / sum(course.credits)
end as GPA
from student
left outer join (
takes join course on takes.course_id = course.course_id
join grade_points on takes.grade = grade_points.grade
where takes.grade is not null
) as graded_records on student.ID = graded_records.ID
group by student.ID;
If the view is only required for students who have earned at least one completed grade:
create view student_grades (ID, GPA) as
select takes.ID,
sum(course.credits * grade_points.points) / sum(course.credits) as GPA
from takes
join course on takes.course_id = course.course_id
join grade_points on takes.grade = grade_points.grade
where takes.grade is not null
group by takes.ID;
student_grades view demonstrates real-world SQL engineering, handling joins, aggregates, and null safety.AVG(grade_points.points)! This is fundamentally incorrect because courses have different credit weights (e.g., a 4-credit course has double the impact of a 2-credit course). You must use ∑(credits×points)/∑(credits).Question (Silberschatz 7e Exercise 4.20).
Show how to define a view tot_credits (year, num_credits), giving the total number of credits taken in each year.
takes = (ID,course_id,sec_id,semester,year,grade)course = (course_id,title,dept_name,credits)To compute the total number of credits taken in each year across the entire university:
takes with course on course_id to obtain the credit weight of each course taken.year.SUM(credits).create view tot_credits (year, num_credits) as
select takes.year, sum(course.credits) as num_credits
from takes
join course on takes.course_id = course.course_id
group by takes.year;
(Using natural join syntax:)
create view tot_credits (year, num_credits) as
select year, sum(credits) as num_credits
from takes natural join course
group by year;
If the university administration maintains an academic calendar table years(year) and desires that years with zero course registrations display 0 rather than being omitted:
create view tot_credits (year, num_credits) as
select y.year, coalesce(sum(course.credits), 0) as num_credits
from (select distinct year from section) as y
left outer join (takes join course using (course_id)) using (year)
group by y.year;
CREATE VIEW query using takes JOIN course GROUP BY year is completely sufficient. Ensure column aliases (year, num_credits) are specified in the view header.Question (Silberschatz 7e Exercise 4.13).
Consider a view v whose definition references only relation r.
A fundamental design goal of the relational database security architecture is data abstraction and column/row-level security.
employee table would leak salaries).SELECT authorization on r.faculty_public displaying (ID, name, dept_name) from the base relation instructor(ID, name, dept_name, salary), deliberately omitting salary. If users required direct SELECT privileges on instructor, they could bypass the view and query salaries directly, nullifying security. The view creator needs SELECT privileges on r to define the view; subsequent query callers only need SELECT privileges on v.UPDATE authorization on r.UPDATE authorization on a view that exposes only instructors within their specific department (WHERE dept_name = 'Comp. Sci.'). If the department head had direct UPDATE privileges on base relation instructor, they could modify salaries across all departments. The view limits the update scope to authorized rows and columns without exposing the base relation.Let base relation r be instructor(ID, name, dept_name, salary).
Define view v as:
create view biology_instructors as
select ID, name, dept_name, salary
from instructor
where dept_name = 'Biology';
Now execute an insert through the view:
insert into biology_instructors values ('98324', 'Feynman', 'Physics', 95000);
What Happens and Explanation:
ID and attributes without aggregation).instructor:
('98324', 'Feynman', 'Physics', 95000) is physically inserted into instructor.select * from biology_instructors;
The query expands to:
select ID, name, dept_name, salary
from instructor
where dept_name = 'Biology';
dept_name = 'Physics'. It fails the WHERE dept_name = 'Biology' predicate and is omitted from the view result!WITH CHECK OPTIONTo prevent users from inserting or updating tuples through a view into states that violate the view's WHERE clause, SQL provides the WITH CHECK OPTION clause:
create view biology_instructors as
select ID, name, dept_name, salary
from instructor
where dept_name = 'Biology'
with check option;
With this clause enabled, the previous insert is rejected with an SQL integrity exception.
Question (Silberschatz 7e Exercise 4.21).
For the view of Exercise 4.20 [tot_credits (year, num_credits)], explain why the database system would not allow a tuple to be inserted into the database through this view.
(Note: The textbook print references Exercise 4.18, which is an erratum in the 7th edition; the intended reference is the tot_credits aggregate view defined in Exercise 4.20).
When an INSERT, UPDATE, or DELETE statement is issued against a view V, the DBMS must translate that operation into a sequence of equivalent operations on the underlying base relations R1,…,Rk.
For an insert to be well-defined, there must exist a unique, unambiguous inverse translation from the view tuple to base relation tuples.
Recall the view definition from Exercise 4.20:
create view tot_credits (year, num_credits) as
select year, sum(credits)
from takes natural join course
group by year;
The database system completely disallows inserting a tuple (e.g., INSERT INTO tot_credits VALUES (2025, 450);) for three fundamental theoretical and practical reasons:
SUM)An aggregate function maps a set of multiple values into a single scalar value. There are infinitely many combinations of individual student course enrollments whose credits sum to 450 (e.g., 150 students taking one 3-credit course, or 100 students taking 4.5 credits, etc.). The database has no semantic basis to decide which base-table rows to manufacture.
Under the ISO/IEC SQL standard (SQL:1999 and SQL:2003 onwards), a view V is updatable if and only if all of the following conditions are met:
FROM clause contains exactly one base relation (not a join or union).SELECT clause contains only simple attribute names (no expressions, arithmetic, or aggregate functions like SUM, AVG, COUNT).SELECT list does not contain DISTINCT.GROUP BY or HAVING clause.SELECT clause must either allow NULL values or possess an explicit DEFAULT value.View tot_credits violates almost every single rule:
takes and course).SUM(credits).GROUP BY clause.The primary keys of the base relations are:
course: course_idtakes: (ID, course_id, sec_id, semester, year)Neither ID, course_id, nor sec_id appear in tot_credits. Inserting (2025, 450) would require inserting rows into takes with NULL for ID and course_id, violating entity integrity (PRIMARY KEY columns cannot be null).
GROUP BY, aggregates, and joins in updatable views.takes.ID, course_id) are missing, violating entity integrity.Question (Silberschatz 7e Practice Exercise 5.6).
Consider the bank database of Figure 5.21:
branch(branch_name, branch_city, assets)customer(customer_name, customer_street, customer_city)loan(loan_number, branch_name, amount)borrower(customer_name, loan_number)account(account_number, branch_name, balance)depositor(customer_name, account_number)Let us define a view branch_cust as follows:
create view branch_cust as
select branch_name, customer_name
from depositor, account
where depositor.account_number = account.account_number;
Suppose that the view is materialized; that is, the view is computed and stored. Write triggers to maintain the view, that is, to keep it up-to-date on insertions to depositor or account. It is not necessary to handle deletions or updates. Note that, for simplicity, we have not required the elimination of duplicates.
A standard view is a virtual relation recomputed upon each query execution. A materialized view physically stores the computed tuples on disk to accelerate frequent read-heavy reporting queries.
However, when underlying base tables are modified, the materialized copy becomes stale. Recomputing the entire view from scratch is computationally prohibitive. Databases utilize Incremental View Maintenance (IVM):
For a join view V=R⋈S: When an insertion occurs on R (ΔR), the change to the view is:
ΔV=ΔR⋈SWhen an insertion occurs on S (ΔS), the change to the view is:
ΔV=R⋈ΔSIn database systems without automated engine-level IVM, this is implemented using ECA (Event-Condition-Action) triggers.
Let the materialized view be represented by a physical table:
create table branch_cust (
branch_name varchar(50),
customer_name varchar(50)
);
We must write two row-level triggers:
maintain_branch_cust_on_depositor: Fires after an insertion into depositor.maintain_branch_cust_on_account: Fires after an insertion into account.depositorWhen a new row new_dep is inserted into depositor(customer_name, account_number):
account table for all accounts matching account_number = new_dep.account_number.(account.branch_name, new_dep.customer_name) into branch_cust.create trigger trig_depositor_insert
after insert on depositor
referencing new row as new_dep
for each row
when (new_dep.account_number is not null)
begin
insert into branch_cust (branch_name, customer_name)
select account.branch_name, new_dep.customer_name
from account
where account.account_number = new_dep.account_number;
end;
accountWhen a new row new_acc is inserted into account(account_number, branch_name, balance):
depositor table for all customers matching account_number = new_acc.account_number.(new_acc.branch_name, depositor.customer_name) into branch_cust.create trigger trig_account_insert
after insert on account
referencing new row as new_acc
for each row
when (new_acc.account_number is not null)
begin
insert into branch_cust (branch_name, customer_name)
select new_acc.branch_name, depositor.customer_name
from depositor
where depositor.account_number = new_acc.account_number;
end;
Suppose initial tables are empty.
INSERT INTO account VALUES ('A-101', 'Downtown', 500);
trig_account_insert fires.depositor for account_number = 'A-101'. None found. No rows added to branch_cust.INSERT INTO depositor VALUES ('Johnson', 'A-101');
trig_depositor_insert fires.account for account_number = 'A-101'. Finds ('A-101', 'Downtown', 500).('Downtown', 'Johnson') into branch_cust.branch_cust now holds ('Downtown', 'Johnson'), exactly matching the view definition!:NEW.account_number and MySQL uses NEW.account_number, the standard SQL syntax presented above with referencing new row as new_row is standard Silberschatz textbook syntax and receives 100% marks across all exam evaluators.