4.5
Testing SQL queries: To test if a query specified in English has been correctly written in SQL, the SQL query is typically executed on multiple test databases, and a human checks if the SQL query result on each test database matches the intention of the specification in English.
a. In Section 4.1.1 we saw an example of an erroneous SQL query which was intended to find which courses had been taught by each instructor; the query computed the natural join of instructor, teaches, and course, and as a result it unintentionally equated the dept_name attribute of instructor and course. Give an example of a dataset that would help catch this particular error.
b. When creating test databases, it is important to create tuples in referenced relations that do not have any matching tuple in the referencing relation for each foreign key. Explain why, using an example query on the university database.
c. When creating test databases, it is important to create tuples with null values for foreign-key attributes, provided the attribute is nullable (SQL allows foreign-key attributes to take on null values, as long as they are not part of the primary key and have not been declared as not null). Explain why, using an example query on the university database.
Hint: Use the queries from Exercise 4.2.
- Consider the case where a professor in the Physics department teaches an Elec. Eng. course. Even though there is a valid corresponding entry in teaches, it is lost in the natural join of instructor, teaches and course, since the instructor’s department name does not match the department name of the course. An example dataset:-
instructor = {('12345','Gauss','Physics',100000)}
teaches = {('12345','EE321',1,'Spring',2017)}
course = {('EE321','Magnetism','Elec. Eng.',6)}
- The query in question 4.2 (a) is a good example for this. Instructors who have not taught a single course should have number of sections as 0 in the query result. (Many other similar examples are possible.)
- Consider the query
SELECT *
FROM teaches NATURAL JOIN instructor;
In this query, we would lose some sections if teaches.ID is allowed to be null and such tuples exist. If, just because teaches.ID Is a foreign key to instructor, we did not create such a tuple, the error in the above query would not be detected.