1.05k likes | 1.08k Views
CSC 453 Database Systems Lecture. Tanu Malik College of CDM DePaul University. Last time. Relational Model Relation Relation implementation Populating a table Primary Keys Foreign Keys. Enforcing Integrity Constraints. Enforcing Referential Integrity.
E N D
CSC 453 Database SystemsLecture Tanu Malik College of CDM DePaul University
Last time • Relational Model • Relation • Relation implementation • Populating a table • Primary Keys • Foreign Keys
Enforcing Referential Integrity • Can only insert or update a tuple if the value of every foreign key in the tuple appears among the values of the primary key that it references Insert (40563, 1020, ‘Fall’, `2016’): Reject such an insertion
Can only delete or update a tuple if the value of its primary key does not appear among the values of any of the foreign keys that reference it Delete from Student where SID = 90421 Reject such a deletion
We can specify actions on a parent if referential integrity of a foreign key is violated SET NULL SET DEFAULT CASCADE • Specified as the following on the childON DELETE/UPDATE SET NULL/CASCADE/DEFAULT
Forcing Deletions • CASCADE Constraints • Remove referencing tuples before referenced tuples create table enrolled ( StudentID number(5), CourseID number(4), Quarter varchar(6), Year number(4), primary key (StudentID, CourseID), foreign key (StudentID) references student(SID) on delete cascade, foreign key (CourseID) references course(CID) on delete cascade );
Referential triggered action Example (CASCADE) CREATE TABLE dependent ( ... FOREIGN KEY (essn) REFERENCES employee(ssn) ON DELETE CASCADE, ...) Example (SET NULL) CREATE TABLE studentgroup ( FOREIGN KEY (PresidentID) REFERENCES student(SID) ON DELETE SET NULL Example (SET DEFAULT) CREATE TABLE employee ( ... dno INT NOT NULL DEFAULT 1, ... FOREIGN KEY (dno) REFERENCES department(dnumber) ON DELETE SET DEFAULT ...)
Attribute-level Check create table enrolled ( StudentID number(5), CourseID number(4), Quarter varchar(6) CHECK(quarter in ('Fall','Winter','Spring')), Year number(4), …
Tuple-level CHECK create table course ( CID number(4), CourseName varchar(40), Department varchar(4), CourseNr char(3), primary key (CID), check (department <> 'CSC' OR CourseNR > 100) ); • same as attribute level check, just involves any number of attributes and different placement
Enforcing Integrity Constraints-Summary • Integrity constraints are specified when schema is defined • They must be true at all times • Must be checked when relations are modified • A DBMS must be responsible for checking them (as opposed to?) • Integrity constraints come from applications; a DB instance is never a good evidence to infer ICs
ALTER TABLE ALTER TABLE TABLE_NAME …ADD Attribute DOMAIN; or DROP COLUMN Attribute CASCADE CONSTRAINTS; • Modifies an existing table schema
Examples ALTER TABLE student ADD age integer; Exercise: Add a (named) constraint that 0 <= age <= 120 ALTER TABLE studentgroup ADD FOREIGN KEY(PresidentID) REFERENCES Student(SID); ALTER TABLE studentgroup ADD CONSTRAINT fk_sg FOREIGN KEY(PresidentID) REFERENCES Student(SID); ALTER TABLE studentgroup DROP fk_sg;
Cyclic Dependencies • Most systems do not allow references to tables that do not exist yet. • Two solutions: • if no cyclical dependencies: create tables in right order (Example: university.sql) • in case of cyclical dependencies: create tables without f.k. constraints, and use ALTER TABLE to add these later
Today • SQL • Basic SQL on single table • Basic SQL on two tables • Nested subqueries
SQL Structured Query Language (SQL) is the industry standard for relational databases Used to be known as SEQUEL (Structured English Query Language), developed at IBM All major DBMSs support some version of SQL (SQL-99 is the one you are likely to see)
Classes of SQL Commands • Data Definition Language (DDL) • Create schemas, tables, constraints, views • Data Manipulation Language (DML) • Modify and update tables, retrieve information • Data Control Language (DCL) • Grant and revoke access to parts of database • Most users will only have access to the DML – we will use both the DDL and the DML
SQL-DDL • Create a table • Insert values into it create table student ( LastName varchar(40), FirstName varchar(40), SID number(5), SSN number(9), Career varchar(4), Program varchar(10), City varchar(40), Started number(4) ); insert into student values ( 'Brennigan', 'Marcus', 90421, 987654321, 'UGRD', 'COMP-GAM', 'Evanston', 2010 );
Classes of SQL Commands • Data Definition Language (DDL) • Create schemas, tables, constraints, views • Data Manipulation Language (DML) • Modify and update tables, retrieve information • Data Control Language (DCL) • Grant and revoke access to parts of database • Most users will only have access to the DML – we will use both the DDL and the DML
SQL is declarative SQL describes WHAT to do Not HOW to do it.
Student Table Query the table: Find all students who live in Chicago
Student Table Query the table: Find all students who live in Chicago SELECT * FROM Student WHERE city = ‘Chicago’ Star means all attributes
Student Table Query the table: Find IDs of students who live in Chicago SELECT SID, City FROM Student WHERE city = ‘Chicago’ This is the WHERE clause. The WHERE clause is evaluated for each row in the table
No No No No
Yes Yes Yes No Temporary Query Result Table
Query the table: Find Ids of students who live in Chicago SELECT SID, City FROM Student WHERE city = ‘Chicago’ Find Ids of students who live in Chicago SELECT SID, City FROM Student WHERE city = ‘Chicago’
Query the table: Find Id and Last Name of students who live in Chicago SELECT SID, City FROM Student WHERE city = ‘Chicago’ Query the table: Find Id and Last Name of students who live in Chicago SELECT SID, LName FROM Student WHERE city = ‘Chicago’
SQL: WHERE WHERE condition • Each tuple is tested against the condition, and only those that satisfy it are returned by the query • Condition expression can contain: • comparisons • expressions with wildcards (for strings) • boolean operations
Comparisons • Put numerical or string value on each side • Each comparison returns true or false = is equal to != or <> is not equal to > is greater than >= is greater than or equal to < is less than <= is less than or equal to
Wildcards • Using LIKE, we can compare character strings to strings that include wildcard characters that match anything: _ matches any single character % matches any consecutive set of characters • For example: • ‘b_d’ will match ‘bad’, ‘bed’, but not ‘band’ • ‘bat%’ will match ‘bat’, ‘bath’, ‘battery’…
Practice • Select all students who started after 2010
SQL: WHERE WHERE condition • Each tuple is tested against the condition, and only those that satisfy it are returned by the query • Condition expression can contain: • comparisons • expressions with wildcards (for strings) • boolean operations
Boolean Expressions • Select students whose last initial is ‘B’ or ‘Y’ • List students who live in ‘Evanston’ and started in ‘2010’
Yes AND Yes Yes AND No No AND No No AND No
No AND Yes No AND No No And No No AND No SELECT * FROM Student WHERE City = ‘Evanston’ AND Started = 2010
Boolean Expressions Temporary Query Result Table
Boolean Expressions • List students who live in ‘Evanston’ or started in ‘2010’ SELECT * FROM Student WHERE City = ‘Evanston’ OR Started = 2010
Boolean Expressions • List students in ‘COMP-GAM’ and ‘INFO-SYS’ SELECT * FROM Student WHERE Program = ‘COMP-GAM’ OR Program = ‘INFO-SYS’
Boolean Operators • Simple conditions can be combined into more complicated conditions • X AND Y is satisfied by a tuple if and only if both X and Y are satisfied by it • X OR Y is satisfied by a tuple if and only if at least one of X and Y is satisfied by it • NOT X is satisfied by a tuple if and only if X is not satisfied by it
SQL: SELECT FROM SELECT list of attributes FROM list of tables • SELECT gives which attributes to include • give a single attribute, or a list • * for all attributes • FROM gives the table(s) to get tuples from • for now, just a single table
Extensions to SELECT: Distinct SELECT City FROM Student WHERE city = ‘Chicago’ SELECT DISTINCT City FROM Student WHERE city = ‘Chicago’
Extensions to SELECT: Distinct • SQL does not remove duplicates by default • The first query does not eliminate duplicate rows from the answer. • The second query eliminates duplicate rows. • The query writer chooses whether duplicates are eliminated.
More SELECT Extensions • The SELECT clause list can also include simple arithmetic expressions using +, -, *, and /. • We can use aggregate operators in the SELECT clause: COUNT, SUM, MIN, MAX, and AVG • If one aggregate operator appears in the SELECT clause, then ALL of the entries in the select clause must be aggregate operators • Operators can be composed together
Examples • SELECT avg(started), max(started), min(started) FROM student; • SELECT max(started), min(started) FROM student WHERE career = ‘GRD’; • SELECT count(*) AS GraduateStudents FROM student WHERE career = ‘GRD’; • SELECT count(distinct presidentID) FROM studentgroup;
Rename Columns and Tables • SQL aliases are used to give a table, or a column in a table, a temporary name. • Aliases are often used to make column names more readable. • An alias only exists for the duration of the query. • SELECT column_name AS alias_nameFROM table_name; • SELECT column_name(s)FROM table_name AS alias_name;
Order Query Result • Ordering tuples SELECT SID, Started FROM Student WHERE city = ‘Chicago’ ORDER BY Started • By default ASC order • DESC for descending order
SQL Queries • General form of a query: 1. SELECT list of attributes to report 2. FROM list of tables 3. [WHERE tuple condition]4. [ORDER BY list of ordering attributes] ; • Result is an ordered set of ordered tuples