Think about these queries for exam

Similar documents
For the Dorm Energy Monitoring DB design, some constraints are given and some are absent. You are asked to fill in some of these absent constraints.

CREATE TABLE Observer ( NetworkID CHAR(20), DormName VARCHAR(35), PRIMARY KEY (NetworkID) );

I will not use a source other than my brain on this exam: (please sign)

Exam 1 CS x265 Spring 2018 Name: KEY. I will not use notes, other exams, or any source other than my own brain on this exam:

CS x265 Exam 3 Spring ALL questions 5 points, except question 11 I will not use a source other than my brain on this exam: (please sign)

Exam 2 CS 265 Spring 2018 Name: KEY. I will not use notes, other exams, or any source other than my own brain on this exam: (please sign)

Midterm Examination CS 265 Spring 2015 Name: KEY Total on any question cannot exceed 5 and cannot be less than 0 JPK, CK, JDK

Midterm Examination CS 265 Spring 2015 Name: I will not use notes, other exams, or any source other than my own brain on this exam: (please sign)

The SQL data-definition language (DDL) allows defining :

SQL. Chapter 5 FROM WHERE

Integrity and Security

Midterm Examination CS 265 Spring 2016 Name: I will not use notes, other exams, or any source other than my own brain on this exam: (please sign)

Lecture 3 SQL - 2. Today s topic. Recap: Lecture 2. Basic SQL Query. Conceptual Evaluation Strategy 9/3/17. Instructor: Sudeepa Roy

SQL: Queries, Programming, Triggers

Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa

SQL: Queries, Constraints, Triggers (iii)

Introduction to Data Management CSE 344

CS 4604: Introduc0on to Database Management Systems. B. Aditya Prakash Lecture #4: SQL---Part 2

SQL: Data Definition Language. csc343, Introduction to Databases Diane Horton Fall 2017

Unit Assessment Guide

Where are we? Week -4: Data definition (Creation of the schema) Week -3: Data definition (Triggers) Week -1: Transactions and concurrency in ORACLE.

SQL: Queries, Constraints, Triggers

Final Database Design Deliverables CS x265, Introduction to Database Management Systems, Spring 2018

High-Level Database Models (ii)

Lecture 2 SQL. Instructor: Sudeepa Roy. CompSci 516: Data Intensive Computing Systems

Midterm Review. Winter Lecture 13

Chapter 3: Introduction to SQL

SQL: Queries, Programming, Triggers. Basic SQL Query. Conceptual Evaluation Strategy. Example of Conceptual Evaluation. A Note on Range Variables

Chapter 3: Introduction to SQL

Relational Model. Topics. Relational Model. Why Study the Relational Model? Linda Wu (CMPT )

Basic SQL. Dr Fawaz Alarfaj. ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation

Chapter 3: Introduction to SQL. Chapter 3: Introduction to SQL

Summary Modifications. Database Construction (and Usage) Explicit attribute lists. Insertions with queries. Quiz. Default values

Databases. Jörg Endrullis. VU University Amsterdam

THE UNIVERSITY OF AUCKLAND

Today s topics. Null Values. Nulls and Views in SQL. Standard Boolean 2-valued logic 9/5/17. 2-valued logic does not work for nulls

Slides by: Ms. Shree Jaswal

SQL Interview Questions

Debapriyo Majumdar DBMS Fall 2016 Indian Statistical Institute Kolkata

Enterprise Database Systems

Lecture 3 More SQL. Instructor: Sudeepa Roy. CompSci 516: Database Systems

Principles of Data Management

SQL. The Basics Advanced Manipulation Constraints Authorization 1. 1

CHAPTER4 CONSTRAINTS

CIS 330: Applied Database Systems. ER to Relational Relational Algebra

Basic SQL. Basic SQL. Basic SQL

CS121 MIDTERM REVIEW. CS121: Relational Databases Fall 2017 Lecture 13

Where Are We? Next Few Lectures. Integrity Constraints Motivation. Constraints in E/R Diagrams. Keys in E/R Diagrams

Intermediate SQL ( )

Announcements (September 18) SQL: Part II. Solution 1. Incomplete information. Solution 3? Solution 2. Homework #1 due today (11:59pm)

SIT772 Database and Information Retrieval WEEK 6. RELATIONAL ALGEBRAS. The foundation of good database design

Integrity constraints, relationships. CS634 Lecture 2

SQL: Part II. Announcements (September 18) Incomplete information. CPS 116 Introduction to Database Systems. Homework #1 due today (11:59pm)

Midterm Exam #2 (Version A) CS 122A Winter 2017

Carnegie Mellon Univ. Dept. of Computer Science /615 - DB Applications. Today's Party. Example Database. Faloutsos/Pavlo CMU /615

Why Study the Relational Model? The Relational Model. Relational Database: Definitions. The SQL Query Language. Relational Query Languages

This course is aimed at those who need to extract information from a relational database system.

The Relational Model

An Introduction to Structured Query Language

An Introduction to Structured Query Language

Interview Questions on DBMS and SQL [Compiled by M V Kamal, Associate Professor, CSE Dept]

Sql Server Syllabus. Overview

CMP-3440 Database Systems

D B M G. SQL language: basics. Managing tables. Creating a table Modifying table structure Deleting a table The data dictionary Data integrity

SQL STRUCTURED QUERY LANGUAGE

Keys, SQL, and Views CMPSCI 645

NULL. The special value NULL could mean: Unknown Unavailable Not Applicable

SQL OVERVIEW. CS121: Relational Databases Fall 2017 Lecture 4

MySQL. A practical introduction to database design

Debapriyo Majumdar DBMS Fall 2016 Indian Statistical Institute Kolkata

CIS 330: Applied Database Systems

The Relational Model. Chapter 3. Comp 521 Files and Databases Fall

The Relational Model Constraints and SQL DDL

Carnegie Mellon University Department of Computer Science /615 - Database Applications C. Faloutsos & A. Pavlo, Spring 2014.

Midterm Exam (Version B) CS 122A Spring 2017

Oracle Database 11g: SQL and PL/SQL Fundamentals

INFSCI 2710 Database Management Solution to Final Exam

Contents Contents Introduction Basic Steps in Query Processing Introduction Transformation of Relational Expressions...

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

CS W Introduction to Databases Spring Computer Science Department Columbia University

EECS 647: Introduction to Database Systems

Table of Contents. PDF created with FinePrint pdffactory Pro trial version

618 Index. BIT data type, 108, 109 BIT_LENGTH, 595f BIT VARYING data type, 108 BLOB data type, 108 Boolean data type, 109

SQL Server 2008 Tutorial 3: Database Creation

Introduction to SQL. ECE 650 Systems Programming & Engineering Duke University, Spring 2018

Introduction to Computer Science and Business

G64DBS Database Systems. Lecture 6 More SQL Data. Creating Relations. Column Constraints. Last Lecture s Question

Creating Tables, Defining Constraints. Rose-Hulman Institute of Technology Curt Clifton

CS275 Intro to Databases

An Introduction to Structured Query Language

Introduction to Database Systems CSE 414

Implementing Table Operations Using Structured Query Language (SQL) Using Multiple Operations. SQL: Structured Query Language

Constraints. Primary Key Foreign Key General table constraints Domain constraints Assertions Triggers. John Edgar 2

Instructor: Craig Duckett. Lecture 11: Thursday, May 3 th, Set Operations, Subqueries, Views

Review. S V T Ma Mo N A S. Mo Ma T

SQL DATA DEFINITION LANGUAGE

The Relational Model. Relational Data Model Relational Query Language (DDL + DML) Integrity Constraints (IC)

CSEN 501 CSEN501 - Databases I

SQL DATA DEFINITION LANGUAGE

Database Management Systems Paper Solution

Transcription:

Think about these queries for exam Write SQL queries specified below in a manner that is consistent with the table definitions. a) Write a SQL query that lists all of the individual water readings recorded for each floor of McGill, a high res dorm, on Jan 28, 2012 (HRWReadingDate = 2012-01-28 ). Each row of the output should list dorm name (all McGill), floor number, the date (yes, the dates in each row should be the same), the time of reading, and the reading value. b) Write a SQL query that lists all of the individual water readings recorded for each floor of each high res dorm on Jan 28, 2012 (HRWReadingDate = 2012-01-28 ). Each row of the output should list dorm name, floor number, the date (yes, the dates in each row should be the same), the time of reading, and the reading value. c) Much like (b), but rather than listing all the readings for a given day, list the AVERAGE water reading values for each day, together with the date, the dorm name, and the floor number. d) Just like (c), but list only those daily averages that are computed over more than 5 values. e) Write an SQL query that lists, for each dorm (low or high res), the AVERAGE ambient (outside) temperature and the AVERAGE electricity readings on each day in which the MINIMUM ambient temperature exceeds 70 degrees. Thus, the output should list dorm name, average electrical reading (listed as AveElec), and average ambient temperature (as AveTemp), and the reading date. f) Write an SQL query that lists the average electrical readings for each floor that were viewed by an observer with FloorWebPage.ObserverNetworkID = X, for each day in which the MAX ambient temperature was greater than 80 degrees (AmbientTemp > 80). Include FloorWebPage.ObserverNetworkID = X as is. Note that X is a variable; when an unbound variable appears in a query, it is a parameter that is requested at interpretation time). Each row of the output should list network id (which should be the same across all rows), the AVERAGE ambient temperature for the day (as AveTemp), the dorm name, floor, sensor id, electrical reading date, and average value (as AveElec).

The answers on slides 3-10 assume the SQL database of slides 11-onward (which Was also posted before Exam 1) There is scoring annotabons on slides 3-10 from a prior semester, which I have decided to leave so that you can get a sense of a possible rubric later.

a) Write a SQL query that lists all of the individual water readings recorded for each floor of McGill, a high res dorm, on Jan 28, 2012 (HRWReadingDate = 2012-01-28 ). Each row of the output should list dorm name (all McGill), floor number, the date (yes, the dates in each row should be the same), the time of reading, and the reading value. (20 points) SELECT S.DormName, S.FloorNum, R.HRWReadingDate, R.HRWReadingTime, R.HRWValue FROM HRWSensor S, HRWReading R WHERE S.DormName = McGill AND R.HRWReadingDate = 2012-01-28 AND S.HRWaterSensorID = R.HRWaterSensorID Start with a total of 18 points (and adhjust as follows): Because the HRWSensor table lists DormName and FloorNum, other tables like Floor and HighResDorm are not needed. -2 points for each extra table. Check that each of the two RA selection conditions are given (i.e., S.DormName = McGill AND R.HRWReadingDate = 2012-01-28 ) and -3 points for each, if missing, and the join condition is given S.HRWaterSensorID = R.HRWaterSensorID (-5 points if missing)). There should be no other conditions, unless there are extra tables (in which case, you would have already been penalized no additional points off unless an answer with extra tables does NOT appropriately join them with other tables, then use discretion based on how bad the failure to join is (but at least -1 per failure to join an extra table). -1 for each missing attribute in the SELECT clause, and -1 for any attribute that is listed which is not given above If the query is nicely indented, as above, and there are no typos (e.g., misspelled table names), and otherwise easy to read, then add 2 points (for max of 20) Poorly formatted example SELECT S.DormName, S.FloorNum, R.HRWReadingDate, R.HRWReadingTime, R.HRWValue FROM HRWSensor S, HRWReading R WHERE S.DormName = McGill AND R.HRWReadingDate = 2012-01-28 AND S.HRWaterSensorID = R.HRWaterSensorID)

b) Write a SQL query that lists all of the individual water readings recorded for each floor of each high res dorm on Jan 28, 2012 (HRWReadingDate = 2012-01-28 ). Each row of the output should list dorm name, floor number, the date (yes, the dates in each row should be the same), the time of reading, and the reading value. (15 points) SELECT S.DormName, S.FloorNum, R.HRWReadingDate, R.HRWReadingTime, R.HRWValue FROM HRWSensor S, HRWReading R WHERE R.HRWReadingDate = 2012-01-28 AND S.HRWaterSensorID = R.HRWaterSensorID Much like (a), but missing one of the selection conditions. Start at 14/15 and use same point decrements for (a) and 1 point increment (rather than 2) for style c) Much like (b), but rather than listing all the readings for a given day, list the AVERAGE water reading values for each day, together with the date, the dorm name, and the floor number. (15 points) SELECT R.HRWReadingDate, S.DormName, S.FloorNum, AVG(R.HRWValue) AS AverageValue FROM HRWSensor S, HRWReading R WHERE S.HRWaterSensorID = R.HRWaterSensorID GROUP BY R.HRWReadingDate, S.DormName, S.FloorNum Start at 14/15 and use same decrementsand increments as (b), and additionally -2 for each missing attribute in the GROUP BY clause (or -6 if there is no GROUP BY clause at all), and -3 for no of AVG aggregate operator (or -2 for improperly formatted operator)

d) Just like (c), but list only those daily averages that are computed over more than 5 values. (15 points) SELECT R.HRWReadingDate, S.DormName, S.FloorNum, AVG(R.HRWValue) AS AverageValue FROM HRWSensor S, HRWReading R WHERE S.HRWaterSensorID = R.HRWaterSensorID GROUP BY R.HRWReadingDate, S.DormName, S.FloorNum HAVING COUNT(*) > 5 Start at 14/15 and use same decrements and increments as (c), and additionally -4 for no HAVING clause (including an incorrect placement of teh HAVING condition in another clause, like WHERE)

e) Write an SQL query that lists, for each dorm (low or high res), the AVERAGE ambient (outside) temperature and the AVERAGE electricity readings on each day in which the MINIMUM ambient temperature exceeds 70 degrees. Thus, the output should list dorm name, average electrical reading (listed as AveElec), and average ambient temperature (as AveTemp), and the reading date. (20 points) The following returns results for High Res Dorms only SELECT S.DormName, AVG(R.HREValue) AS AveElec, QualDays.AveTemp, R.HREReadingDate FROM HRElecSensor S, HREReading R, (SELECT AV.AmbientReadingsDate, AVG(AV.AmbientTemp) AS AveTemp FROM AmbientValues AV GROUP BY AV.AmbientReadingsDate HAVING MIN(AV.AmbientTemp) > 70) AS QualDays WHERE QualDays.AmbientReadingsDate = R.HREReadingDate AND R.HRElecSensorID = S.HRElecSensorID GROUP BY S.DormName, R.HREReadingDate, QualDays.AveTemp One can picture the join in the OUTER query as FOR each HREElecSensor, Si, FOR each HREReading, Rij (from sensor Si) FOR each Qual Day with suitable ambient temp (MIN > 70), QDATk, on same date as Rijs join Si + Rj + QDATk Si Rij1 Rij2 Rij3 QDATk Because there is only one QualDay.AveTemp per ReadingDate some might have left QualDays.AveTemp from GROUP BY (-1 if so), but shouldn t if its to be used in SELECT clause Rij4 Rij5 Give max of 14 points for one half of complete answer, using either high res or low res dorm as the basis. Adapt grading guidelines from previous problems (e.g., extra tables, etc) to this one.

e) Write an SQL query that lists, for each dorm (low or high res), the AVERAGE ambient (outside) temperature and the AVERAGE electricity readings on each day in which the MINIMUM ambient temperature exceeds 70 degrees. Thus, the output should list dorm name, average electrical reading (listed as AveElec), and average ambient temperature (as AveTemp), and the reading date. (20 points) This would work for Low Res dorms only if it were just a matter of changing all H to L, BUT ITS NOT! SELECT S.DormName, AVG(R.LREValue) AS AveElec, QualDays.AveTemp, R.LREReadingDate FROM LRElecSensor S, LREReading R, (SELECT AV.AmbientReadingsDate, AVG(AV.AmbientTemp) AS AveTemp FROM AmbientValues AV GROUP BY AV.AmbientReadingsDate HAVING MIN(AV.AmbientTemp) > 70) AS QualDays WHERE QualDays.AmbientReadingsDate = R.LREReadingDate AND R.LRElecSensorID = S.LRElecSensorID GROUP BY S.DormName, R.LREReadingDate, QualDays.AveTemp CREATE TABLE LowResDorm ( DormName VARCHAR(35), /* Corresponds to a DormName in Dorm */ StartDate DATE, /* Date at which it became a LowResDorm */ LRElecSensorID INTEGER NOT NULL, UNIQUE(LRElecSensorID), /* UNIQUE indicates a key; typically implies NOT NULL */ LRElecSensorOnLineDate DATE, LRWaterSensorOnLineDate DATE, LRWaterSensorID INTEGER, PRIMARY KEY (DormName) Just change [LRElecSensor S] to [LowResDorm S] in query at top?

e) Write an SQL query that lists, for each dorm (low or high res), the AVERAGE ambient (outside) temperature and the AVERAGE electricity readings on each day in which the MINIMUM ambient temperature exceeds 70 degrees. Thus, the output should list dorm name, average electrical reading (listed as AveElec), and average ambient temperature (as AveTemp), and the reading date. (20 points) The Low Res result after minor change SELECT S.DormName, AVG(R.LREValue) AS AveElec, QualDays.AveTemp, R.LREReadingDate FROM LowResDorm S, LREReading R, (SELECT AV.AmbientReadingsDate, AVG(AV.AmbientTemp) AS AveTemp FROM AmbientValues AV GROUP BY AV.AmbientReadingsDate HAVING MIN(AV.AmbientTemp) > 70) AS QualDays WHERE QualDays.AmbientReadingsDate = R.LREReadingDate AND R.LRElecSensorID = S.LRElecSensorID GROUP BY S.DormName, R.LREReadingDate, QualDays.AveTemp /* which can be unioned with High Res Dorm results for full results required by question */ UNION SELECT S.DormName, AVG(R.HREValue) AS AveElec, QualDays.AveTemp, R.HREReadingDate FROM HRElecSensor S, HREReading R, (SELECT AV.AmbientReadingsDate, AVG(AV.AmbientTemp) AS AveTemp FROM AmbientValues AV GROUP BY AV.AmbientReadingsDate HAVING MIN(AV.AmbientTemp) > 70) AS QualDays WHERE QualDays.AmbientReadingsDate = R.HREReadingDate AND R.HRElecSensorID = S.HRElecSensorID GROUP BY S.DormName, R.HREReadingDate, QualDays.AveTemp Give max of 18 points for answer that approximates this one. Adapt grading guidelines from previous problems (e.g., extra tables, etc) to this one.

e) Write an SQL query that lists, for each dorm (low or high res), the AVERAGE ambient (outside) temperature and the AVERAGE electricity readings on each day in which the MINIMUM ambient temperature exceeds 70 degrees. Thus, the output should list dorm name, average electrical reading (listed as AveElec), and average ambient temperature (as AveTemp), and the reading date. (20 points) The previous query computes QualDays twice. The following does it once by unioning at finer granularity SELECT S.DormName, AVG(R.Value) AS AveElec, QualDays.AveTemp, R.ReadingDate FROM (SELECT DormName, LRElecSensorID AS ID FROM LowResDorm UNION SELECT DormName, HRElecSensorID AS ID FROM HRElecSensor) AS S, (SELECT LRElecSensorID AS ID, LREReadingDate AS ReadingDate, LREValue AS Value FROM LREReading UNION SELECT HRElecSensorID AS ID, HREReadingDate AS ReadingDate, HREValue AS Value FROM HREReading) AS R, Give max of 20 points for answer that approximates this one. Adapt grading guidelines from previous problems (e.g., extra tables, etc) to this one. (SELECT AV.AmbientReadingsDate, AVG(AV.AmbientTemp) AS AveTemp FROM AmbientValues AV GROUP BY AV.AmbientReadingsDate HAVING MIN(AV.AmbientTemp) > 70) AS QualDays WHERE QualDays.AmbientReadingsDate = R.ReadingDate AND R.ID = S.ID GROUP BY S.DormName, R.ReadingDate, QualDays.AveTemp What hidden assumptions underlie this query? The previous version? Does this query assume that sensor ids are unique ACROSS HRElecSensorID and LowResDorm, for example?

f) Write an SQL query that lists the average electrical readings for each floor that were viewed by an observer with FloorWebPage.ObserverNetworkID = X, for each day in which the MAX ambient temperature was greater than 80 degrees (AmbientTemp > 80). Include FloorWebPage.ObserverNetworkID = X as is. Note that X is a variable; when an unbound variable appears in a query, it is a parameter that is requested at interpretation time). Each row of the output should list network id (which should be the same across all rows), the AVERAGE ambient temperature for the day (as AveTemp), the dorm name, floor, sensor id, electrical reading date, and average value (as AveElec). (15 points) SELECT FWP.ObserverNetworkID, AVG(AV.AmbientTemp) AS AveTemp, FWP.DormName, FWP.FloorNum, S.HRElecSensorID, R.HREReadingDate, AVG(R.HREValue) AS AveElec FROM FloorWebPage FWP, AmbientValues AV, HRElecSensor S, HREReading R WHERE FWP.ObserverNetworkID = X AND AV.AmbientReadingsDate = R.HREReadingDate AND R.HRElecSensorID = S.HRElecSensorID AND S.FloorNum = FWP.FloorNum AND FWP.DormName = S.DormName GROUP BY R.HREReadingDate, FWP.ObserverNetworkID, FWP.DormName, FWP.FloorNum, S.HRElecSensorID HAVING MAX(AV.AmbientTemp) > 80 All the attributes listed in the Group By should be given

Assignment A-w4 KEY Spring 2018 Name: For the Dorm Energy Monitoring DB design, some constraints are given and some are absent. You are asked to fill in some of these absent constraints. 1. Fill Foreign Key constraints (FKs) for selected tables. 2. Fill in in-table CHECK statements for selected tables, which will typically use nested queries. Nested queries are allowed in in-table CHECK statements in the SQL standard, but they are not supported on any platform (nonetheless, you might implement them one day). If these were supported, then they would be evaluated when an insertion or update is made to the table. 3. Fill in general assertions that are (in theory) evaluated whenever any change (insertion, deletion, update) is made to any table named in the assertion. Again, part of SQL standard, though not implemented on any platform. 4. Fill in trigger definitions, using SQLite syntax. Instructions on where you are to fill in FKs, in-table CHECKs, general assertions, and triggers, are shown in red. There are other constraints that you are not required to fill in, but you are welcome to and you can compare them later on the key. The addibons in blue are all that is required

Dorm Energy Monitoring Application (standard tables and assertions) /* Observer records information about those who are observing campus enery and water usage. These may be on-campus or off-campus observers. Observer associates computer network identifiers (e.g., IP addresses) with campus dormitories. DormName can be NULL, thus allowing easy recording of off-campus (or otherwise nondorm) network identifiers of virtual visitors to dorm web-based electricity and water usage summaries. */ 2 pts for this (all or nothing), or 2 points for placing FK phrase after DormName declaration (using syntax found here by following column-def, then column-constraint, then foreign-key-clause) CREATE TABLE Observer ( NetworkID CHAR(20), DormName VARCHAR(35), /* Corresponds to a DormName in Dorm */ PRIMARY KEY (NetworkID), FOREIGN KEY (DormName) REFERENCES Dorm ON DELETE CASCADE ON UPDATE CASCADE /* Add a FOREIGN KEY constraint that will cause a DELETE or UPDATE in Dorm (of a row with a matching DormName) to CASCADE to Observer. */ /* A record of visits to a Dorm s (often assembled, on demand) Webpage, which displays statistics on electricity and water usage */ CREATE TABLE DormWebPage ( DWPageID INTEGER, CreateDate DATE NOT NULL, /* NOT NULL indicates field cannot be NULL in any record */ CreateTime TIME NOT NULL, ObserverNetworkID CHAR(20) NOT NULL, /* Corresponds to a NetworkID in Observer */ DormName VARCHAR(35) NOT NULL, /* Corresponds to a DormName in Dorm */ PRIMARY KEY (DWPageID), FOREIGN KEY (ObserverNetworkID) REFERENCES Observer (NetworkID) ON DELETE NO ACTION ON UPDATE CASCADE, FOREIGN KEY (DormName) REFERENCES Dorm 2 pts for this (all or nothing), 1 of which is for NO ACTION or RESTRICT ON DELETE NO ACTION ON UPDATE CASCADE /* Add a FOREIGN KEY constraint that will block (i.e., prevent) a Dorm from being deleted if there is a tuple in DormWebPage with a matching DormName. Define the same FK to cascade an update in Dorm to DormWebPage. */

/* Dorms can be high res and low res, and tables for each subtype have an FK reference to Dorm, which contains the common information that is inherited for each type of dorm. Dorms are also FK referenced by a number of other tables. */ CREATE TABLE Dorm ( DormName VARCHAR(35), MaxOccupancy SMALLINT, PRIMARY KEY (DormName) CHECK ((DormName IN (SELECT DormName FROM HighResDorm) UNION (SELECT DormName FROM LowResDorm)) /* A table of time-stamped outdoor temperatures (required) and light conditions (optional) */ CREATE TABLE AmbientValues ( AmbientReadingsDate DATE, AmbientReadingsTime TIME, AmbientTemp TINYINT NOT NULL, AmbientLight CHAR(2), PRIMARY KEY (AmbientReadingsDate, AmbientReadingsTime) /* Every high res dorm is also a dorm */ 2 pts for in-table CHECK as written; other answers may be possible CREATE TABLE HighResDorm ( This duplicates, in part, the affect of a DormName VARCHAR(35), /* Corresponds to a DormName in Dorm */ FK constraint (which I ve shown in green, StartDate DATE, /* Date at which it became a HighResDorm */ and would also be an acceptable answer, PRIMARY KEY (DormName), even without delete/update actions given FOREIGN KEY (DormName) REFERENCES Dorm explicitly in this case, the FK ON DELETE CASCADE ON UPDATE CASCADE constraint would be preferred) CHECK (DormName IN (SELECT DormName FROM Dorm)) /* Add an in-table CHECK that ensures a DormName found in HighResDorm is also found in Dorm */

/* A LowRes dorm is assumed to have a unique (NOT NULL) electricity sensor, but the definition allows water sensors to be shared across dorms (not unique) and none at all (allowed NULL) */ CREATE TABLE LowResDorm ( DormName VARCHAR(35), /* Corresponds to a DormName in Dorm */ StartDate DATE, /* Date at which it became a LowResDorm */ LRElecSensorID INTEGER NOT NULL, UNIQUE(LRElecSensorID), /* UNIQUE indicates a key; typically implies NOT NULL */ LRElecSensorOnLineDate DATE, LRWaterSensorOnLineDate DATE, LRWaterSensorID INTEGER, PRIMARY KEY (DormName), FOREIGN KEY (DormName) REFERENCES Dorm ON DELETE CASCADE ON UPDATE CASCADE CHECK (DormName NOT IN (SELECT DormName FROM HighResDorm)) Since DormName is also the PK of this table, it must be NOT NULL, so an acbon of SET NULL would cause an error.

/* For example, FloorNum = 3 and DormName = McGill is 3 rd floor of McGill */ CREATE TABLE Floor ( DormName VARCHAR(35), /* Corresponds to a DormName in HighResDorm */ FloorNum TINYINT, MaxOccupancy SMALLINT, PRIMARY KEY (DormName, FloorNum), FOREIGN KEY (DormName) REFERENCES HighResDorm ON DELETE CASCADE ON UPDATE CASCADE /* Similar meanings as DormWebPage, but for high res case */ CREATE TABLE FloorWebPage ( DormName VARCHAR(35), /* Corresponds to DormName in Floor */ FloorNum TINYINT, /* Corresponds to FloorNum in Floor */ FWPageID INTEGER, CreateDate DATE NOT NULL, CreateTime TIME NOT NULL, ObserverNetworkID CHAR(20) NOT NULL, /* Corresponds to NetworkID in Observer */ PRIMARY KEY (FWPageID), FOREIGN KEY (ObserverNetworkID) REFERENCES Observer (NetworkID), ON DELETE NO ATION ON UPDATE CASCADE, /* block deletes if Network ID has observation records */ FOREIGN KEY (DormName, FloorNum) REFERENCES Floor ON DELETE NO ACTION ON UPDATE CASCADE /* block deletes if floor has observation records */

/* Definition allows multiple sensors per floor (thus, DormName,Floor not required UNIQUE) */ CREATE TABLE HRElecSensor ( DormName VARCHAR(35) NOT NULL, /* Corresponds to DormName in Floor */ FloorNum TINYINT NOT NULL, /* Corresponds to FloorNum in Floor */ HRElecSensorID INTEGER, HRElecSensorOnLineDate DATE, PRIMARY KEY (HRElecSensorID), FOREIGN KEY (DormName, FloorNum) REFERENCES Floor ON DELETE CASCADE ON UPDATE CASCADE /* If you bother to record a reading, the value should be NOT NULL (perhaps coupled special value(e.g., -999) indicating not read because not functional sensor */ CREATE TABLE HREReading ( HRElecSensorID INTEGER, /* Corresponds to HRElecSensorID in HRElecSensor */ HREReadingDate DATE, HREReadingTime TIME, HREValue INTEGER NOT NULL, PRIMARY KEY (HRElecSensorID, HREReadingDate, HREReadingTime), FOREIGN KEY (HRElecSensorID) REFERENCES HRElecSensor ON DELETE NO ACTION /* if readings associated with a sensor, then block delete */ ON UPDATE CASCADE

/* As with elect sensors in high res case, definition allows multiple sensors per floor (thus, DormName,Floor not required UNIQUE) */ CREATE TABLE HRWSensor ( DormName VARCHAR(35) NOT NULL, /* Corresponds to DormName in Floor */ FloorNum TINYINT NOT NULL, /* Corresponds to FloorNum in Floor */ HRWaterSensorID INTEGER, HRWaterSensorOnLineDate DATE, PRIMARY KEY (HRWaterSensorID), FOREIGN KEY (DormName, FloorNum) REFERENCES Floor ON DELETE CASCADE ON UPDATE CASCADE 2 pts all or nothing; 0 points for two separate FKs for DormName and FloorNum individually /* Write a Foreign Key constraint ensures that every (DormName, FloorNum) pair in HRWSensor is associated with exactly one tuple of Floor. Cascade on both deletes and updates. */ /* Time-stamped readings are associated with sensors*/ CREATE TABLE HRWReading ( HRWaterSensorID INTEGER, /* Corresponds to HRWaterSensorID in HRWaterSensor */ HRWReadingDate DATE, HRWReadingTime TIME, HRWValue INTEGER NOT NULL, PRIMARY KEY (HRWaterSensorID, HRWReadingDate, HRWReadingTime), FOREIGN KEY (HRWaterSensorID) REFERENCES HRWaterSensor ON DELETE NO ACTION /* if readings associated with a sensor, then block delete */ ON UPDATE CASCADE

/* The earlier definition of LowResDorm indicates exactly one sensor per low res dorm */ CREATE TABLE LREReading ( DormName VARCHAR(35), /* Corresponds to DormName in LowResDorm */ LREReadingDate DATE, LREReadingTime TIME, LREValue INTEGER NOT NULL, PRIMARY KEY (DormName, LREReadingDate, LREReadingTime), FOREIGN KEY (DormName) REFERENCES LowResDorm ON DELETE NO ACTION /* if readings associated with a low res dorm, then block delete */ ON UPDATE CASCADE /* The earlier definition of LowResDorm indicates at most one water sensor per low res dorm */ CREATE TABLE LRWReading ( DormName VARCHAR(35), /* Corresponds to DormName in LowResDorm */ LRWReadingDate DATE, LRWReadingTime TIME, LRWValue INTEGER NOT NULL, PRIMARY KEY (DormName, LRWReadingDate, LRWReadingTime) FOREIGN KEY (DormName) REFERENCES LowResDorm ON DELETE NO ACTION /* if readings associated with a sensor, then block delete */ ON UPDATE CASCADE

/* Write a general assertion that ensures that all Dorms are Low Res or High Res */ CREATE ASSERTION CompleteCoverOverLowAndHighRes ( CHECK (NOT EXISTS (SELECT D.DormName FROM Dorm D EXCEPT SELECT LRD.DormName FROM LowResDorm LRD) EXCEPT SELECT HRD.DormName FROM HighResDorm HRD )) /* OR PERHAPS */ CREATE ASSERTION CompleteCoverOverLowAndHighRes ( CHECK (NOT EXISTS (SELECT D.DormName FROM Dorm D EXCEPT (SELECT LRD.DormName FROM LowResDorm LRD) UNION SELECT HRD.DormName FROM HighResDorm HRD) )) /* OR PERHAPS */ CREATE ASSERTION CompleteCoverOverLowAndHighRes ( CHECK (NOT EXISTS (SELECT D.DormName FROM Dorm D WHERE D.DormName NOT IN (SELECT LRD.DormName FROM LowResDorm LRD) UNION SELECT HRD.DormName FROM HighResDorm HRD) )) /* OR PERHAPS */ CREATE ASSERTION CompleteCoverOverLowAndHighRes ( CHECK (NOT EXISTS (SELECT D.DormName FROM Dorm D WHERE D.DormName NOT IN (SELECT LRD.DormName FROM LowResDorm LRD) AND D.DormName NOT IN (SELECT HRD.DormName FROM HighResDorm HRD) )) 3 pts for any of these; others may be possible

/* Write a general assertion that ensures that there is no Dorm in LowResDorm that is also in HighResDorm, and vice versa.*/ CREATE ASSERTION NoOverlapBetweenHighAndLowRes ( CHECK (NOT EXISTS (SELECT * FROM LowResDorm L, HighResDorm H WHERE L.DormName=H.DormName) /* OR */ CREATE ASSERTION NoOverlapBetweenHighAndLowRes CHECK (NOT EXISTS (SELECT DormName FROM LowResDorm INTERSECT SELECT DormName FROM HighResDorm) 3 pts for any of these; others may be possible

/* Write a general assertion that ensures that each Floor of a high res dorm is associated with at least one high res electricity sensor */ CREATE ASSERTION FloorParticipatesHRElecSensor ( CHECK (NOT EXISTS (SELECT * FROM Floor F WHERE (F.DormName, F.FloorNum) NOT IN (SELECT HRES.DormName, HRES.FloorNum FROM HRElecSensor HRES))) 3 pts for any of these; others may be possible CREATE ASSERTION FloorParticipatesHRElecSensor CHECK (NOT EXISTS (SELECT F.DormName, F.FloorNum FROM Floor F EXCEPT SELECT HRES.DormName, HRES.FloorNum FROM HRElecSensor HRES) CREATE ASSERTION FloorParticipatesHRElecSensor ( /* A complicated version of first solution */ CHECK (NOT EXISTS (SELECT * FROM Floor F WHERE F.DormName NOT IN (SELECT HRES.DormName FROM HRElecSensor HRES WHERE HRES.FloorNum = F.FloorNum) OR F.FloorNum NOT IN (SELECT HRES.FloorNum FROM HRElecSensor HRES WHERE HRES.DormName = F.DormName)

/* Ensure that each Floor of a high res dorm is associated with at least one electricity sensor */ Why don t these work? CREATE ASSERTION FloorParticipatesHRElecSensor ( CHECK (EXISTS (SELECT F.DormName, F.FloorNum FROM HRElecSensor HRES, Floor F WHERE HRES.DormName = F.DormName AND HRES.FloorNum = F.FloorNum) CREATE ASSERTION FloorParticipatesHRElecSensor ( CHECK (EXISTS (SELECT * FROM Floor F WHERE (F.DormName, F.FloorNum) IN (SELECT HRES.DormName, HRES.FloorNum FROM HRElecSensor HRES)))

/* Write a trigger in SQLite that mimics the DELETE CASCADE action of a Foreign Key constraint in HRElecSensor that references Floor. That is, when a DELETE is made to Floor, all HRElecSensors associated with that floor are deleted */ CREATE TRIGGER DeleteHRElecSensorsWhenFloorDeleted AFTER DELETE ON Floor 3 pts for this; forgive minor syntactic errors (this time) like parens, missing ;, FOR EACH ROW /* FOR EACH ROW optional */ etc BEGIN DELETE FROM HRElecSensors WHERE FloorNum = OLD.FloorNum AND DormName = OLD.DormName; END; /* Write a trigger in SQLite that implements part of the constraint that each Floor participate in HRElecSensor. In particular, when the only representative of a floor is deleted from HRElecSensors, then that floor is also deleted from Floor */ CREATE TRIGGER DeleteFloorWhenOnlyHRElecSensorDeleted AFTER DELETE ON HRElecSensor FOR EACH ROW /* FOR EACH ROW optional */ WHEN NOT EXISTS (SELECT * FROM HRElecSensor 3 pts for this; forgive minor syntactic errors (this time) like parens, missing ;, etc WHERE FloorNum = OLD.FloorNum AND DormName = OLD.DormName) BEGIN DELETE FROM Floor WHERE FloorNum = OLD.FloorNum AND DormName = OLD.DormName; END; The last representative was just deleted

/* Extra Credit: Write a trigger in SQLite that implements part of the constraint that each Floor participate in HRElecSensor. In particular, when a floor is inserted into Floor, an initial entry into HRElecSensors for that inserted floor */ CREATE TRIGGER InsertHRElecSensorWhenFloorInserted AFTER INSERT INTO Floor FOR EACH ROW /* FOR EACH ROW optional */ WHEN NOT EXISTS (SELECT * FROM HRElecSensor /* WHEN clause optional */ WHERE FloorNum = NEW.FloorNum AND DormName = NEW.DormName) BEGIN INSERT INTO HRElecSensor VALUES (NEW.DormName, NEW.FloorNum, -1, NULL END; 2 pts HRElecSensorID is the PK of HRElecSensor (look at the table declaration), and so cannot be NULL. If your answer made reference to some special default value, like -1 (as shown), or an autoincrement variable for HRElecSensorID then you should receive credit. HRElecSensorOnlineDate is allowed to be NULL in HRElecSensor (again, look at the table declaration). If it had been declared as NOT NULL, then we could not put NULL here, though we could (again) use a special default (dummy, initial) value, or the CurrentDate (any reference to current date should receive full credit).

Reflect on these questions. You do NOT need to answer and submit them in writing, but they will be topics of discussion. a) If you try to delete a row in Observer that has one or more associated entries in DormWebPage, what will happen? b) If you try to delete a Dorm, for which no one has ever looked at (Observed) a DormWebPage for it, what will happen? c) If you try to delete a Dorm, for which there have been one or more recorded views of DormWebPages for it, what will happen? d) How many electricity sensors are associated with a low res dorm (so far as the DB encodes)? And vice versa? e) How many electricity sensors are associated with a high res dorm (so far as the DB encodes)? f) Could the current database design (tables and assertions) support the situation of a low res dorm becoming a high res dorm WITHOUT losing past data from its low res days? If so, explain, and if not, explain what changes to the DB design you might make to support this (high likelihood eventuality) PRIOR to DB implementation. g) How could the DB design be changed to support records of room and plug level measurements of electricity (and perhaps faucet level water readings)?