Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Database Management Systems Chapter 5 SQL.

Slides:



Advertisements
Similar presentations
SQL: The Query Language Part 2
Advertisements

Relational Database. Relational database: a set of relations Relation: made up of 2 parts: − Schema : specifies the name of relations, plus name and type.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Programming, Triggers Chapter 5 Modified by Donghui Zhang.
Database Management System Module 3:. Complex Constraints In this we specify complex integrity constraints included in SQL. It relates to integrity constraints.
IC and Triggers in SQL. Find age of the youngest sailor with age
Introduction to Database Systems 1 SQL: The Query Language Relation Model : Topic 4.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Relational Algebra Chapter 4, Part A Modified by Donghui Zhang.
1 Lecture 11: Basic SQL, Integrity constraints
SQL: Queries, Constraints, Triggers
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Constraints, Triggers Chapter 5.
Database Management Systems 1 Raghu Ramakrishnan SQL: Queries, Programming, Triggers Chpt 5.
SQL Constraints and Triggers
SQL: The Query Language Jianlin Feng School of Software SUN YAT-SEN UNIVERSITY courtesy of Joe Hellerstein and etc for some slides.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Programming, Triggers Chapter 5.
CS 405G: Introduction to Database Systems
Cs3431 Constraints Sections 6.1 – 6.5. cs3431 Example CREATE TABLE Student ( sNum int, sName varchar (20), prof int, CONSTRAINT pk PRIMARY KEY (snum),
CMPT 354, Simon Fraser University, Fall 2008, Martin Ester 28 Database Systems I The Relational Data Model.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Programming, Triggers Chapter 5.
SQL 2 – The Sequel R&G, Chapter 5 Lecture 10. Administrivia Homework 2 assignment now available –Due a week from Sunday Midterm exam will be evening of.
FALL 2004CENG 351 File Structures and Data Management1 SQL: Structured Query Language Chapter 5.
SPRING 2004CENG 3521 SQL: Constraints, Triggers, Embedded SQL Chapters: 5, 6.
Rutgers University SQL: Queries, Constraints, Triggers 198:541 Rutgers University.
1 Relational Model. 2 Relational Database: Definitions  Relational database: a set of relations  Relation: made up of 2 parts: – Instance : a table,
The Relational Model Lecture 3 Book Chapter 3 Relational Data Model Relational Query Language (DDL + DML) Integrity Constraints (IC) From ER to Relational.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 Relational Algebra Chapter 4, Part A.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Constraints, Triggers Chapter 5.
1 SQL: Structured Query Language (‘Sequel’) Chapter 5 (cont.)
CMPT 354, Simon Fraser University, Fall 2008, Martin Ester 157 Database Systems I SQL Constraints and Triggers.
CSC343 – Introduction to Databases - A. Vaisman1 SQL: Queries, Programming, Triggers.
The Relational Model These slides are based on the slides of your text book.
Relational Data Model, R. Ramakrishnan and J. Gehrke with Dr. Eick’s additions 1 The Relational Model Chapter 3.
The Relational Model. Review Why use a DBMS? OS provides RAM and disk.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Constraints, Triggers Chapter 5.
1 The Relational Model. 2 Why Study the Relational Model? v Most widely used model. – Vendors: IBM, Informix, Microsoft, Oracle, Sybase, etc. v “Legacy.
FALL 2004CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
1 SQL: Constraints and Triggers Chapter 5,
Unit 5/COMP3300/ SQL: Queries, Programming, Triggers Chapter 5.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Constraints, Triggers Chapter 5.
SQL: Queries, Programming, Triggers. Example Instances We will use these instances of the Sailors and Reserves relations in our examples. If the key for.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 Relational Algebra.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Constraints and Triggers Chapter 5,
Constraints, Triggers and Views COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, VEHARI.
The Relational Model Content based on Chapter 3 Database Management Systems, (Third Edition), by Raghu Ramakrishnan and Johannes Gehrke. McGraw Hill, 2003.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Database Management Systems Chapter 4 Relational Algebra.
1 SQL: Queries, Constraints, Triggers Chapter 5. 2 Example Instances R1 S1 S2  We will use these instances of the Sailors and Reserves relations in our.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Constraints, Triggers Chapter 5.
CMPT 258 Database Systems The Relationship Model (Chapter 3)
1 SQL: Queries, Constraints, Triggers Chapter 5. 2 Overview: Features of SQL  Data definition language: used to create, destroy, and modify tables and.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Database Management Systems Chapter 5 SQL.
1 SQL: Structured Query Language Chapter 5 (cont.)  Constraints  Triggers.
INLS 623– T RIGGERS Instructor: Jason Carter. F INAL E XAM Classes end on Dec. 2 nd Exam Days start on December 4 th Final Exam is on December 10 at 4pm.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Database Management Systems Chapter 5 SQL.
1 SQL: The Query Language. 2 Example Instances R1 S1 S2 v We will use these instances of the Sailors and Reserves relations in our examples. v If the.
Chapter 3 The Relational Model. Why Study the Relational Model? Most widely used model. Vendors: IBM, Informix, Microsoft, Oracle, Sybase, etc. “Legacy.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
1 CS122A: Introduction to Data Management Lecture #4 (E-R  Relational Translation) Instructor: Chen Li.
CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
SQL – Part 2.
COP Introduction to Database Structures
Instructor: Jason Carter
SQL The Query Language R & G - Chapter 5
SQL: Structured Query Language (‘Sequel’)
SQL: Queries, Programming, Triggers
SQL: Queries, Constraints, Triggers
SQL: Structured Query Language
SQL: Queries, Programming, Triggers
SQL: Structured Query Language
SQL: The Query Language (Part III)
SQL: Queries, Programming, Triggers
Presentation transcript:

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Database Management Systems Chapter 5 SQL

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke2 Date Calculation TimeStampDiff(unit, date_expr1, date_expre2) mysql> SELECT TIMESTAMPDIFF(MONTH,' ',' '); -> 3 mysql> SELECT TIMESTAMPDIFF(YEAR,' ',' '); - > -1 mysql> SELECT TIMESTAMPDIFF(DAY,' ',' '); -> 89

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke3 Data Calculations CREATE TABLE SailorsNew (sid INTEGER, sname CHAR(30) NOT NULL, rating INTEGER, DOB DATE, CONSTRAINT StudentsKey PRIMARY KEY (sid)); SELECT sname, DOB, CURDATE( ), TIMESTAMPDIFF(YEAR, DOB,CURDATE( )) AS age FROM SailorsNew; SELECT sname, DOB, CURDATE( ), TIMESTAMPDIFF(YEAR, DOB,CURDATE( )) AS age FROM SailorsNew Order By sname;

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke4 Query Results

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke5 Extract Information from Date Month(), Year(), DayOfMonth()

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke6 Null Values  Field values in a tuple are sometimes  Unknown : a rating has not been assigned or  Inapplicable : no spouse’s name for un-married person.  SQL provides a special value null for such situations.  The presence of null complicates many issues.

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke7 Comparisons Using Null Values  We need a 3-valued logic : true, false and unknown.  Is rating>8 true or false when rating is equal to null ?  The answer is unknown.  Special operators to check if value is/is not null.  IS NULL returns true is the value is null.  IS NOT NULL returns false is the valule is null.

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke8 Logical Operator AND with One Argument as Null Value pqp AND q True False TrueUnknown (null) False Unknown (null)False

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke9 Logical Operator OR with One Argument as Null Value pqp OR q True FalseTrue Unknown (null)True False Unknown (null)Unknown

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke10 Logical Operator NOT with a Null Value pNOT p TrueFalse True Unknown (null)

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke11 Null Value’s Impact on SQL Constructs  WHERE clause eliminates rows that don’t evaluate to true (false and null is eliminated).  When corresponding columns are either equal, or both contain null, two rows are regarded as duplicates.  Arithmetic operations +, -, *, and / all return null if one of their arguments is null.  COUNT (*) handles null values as other values.  Other aggregate operations ( SUM, AVG, MIN, MAX, and variations using DISTINCT) simply discard null values.  If it applies to only null values, the result is null.

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke12

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke13 Disallowing Null Values  We can disallow null values by specifying NOT NULL as part of field definition.  The fields in a primary key are not allowed as null. CREATE TABLE Students (sid CHAR(20), name CHAR(30) NOT NULL, login CHAR(20), DOB Date, gpa REAL )

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke14 More About Create Table Insert values with local data file CREATE TABLE Sailors (sid INTEGER, sname CHAR(30) NOT NULL, rating INTEGER, age REAL, CONSTRAINT StudentsKey PRIMARY KEY (sid)); Load Data Local Infile '~/Sailors.txt' Into Table Sailors; 1Tom Hanks1125 2Tom Cruise\N26 3Hello K1030 Sailors.txt Tab Key \t NULL

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke15 Clone or Copy a Table Clone a table Copy a table Copy part of a table Rename a table CREATE TABLE SailorsAnother LIKE Sailors; CREATE TABLE SailorsThird Select * FROM Sailors; CREATE TABLE SailorsFourth Select sid, sname FROM Sailors; ALTER TABLE Sailors RENAME SailorsFifth;

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke16 Integrity Constraints (Review)  An IC describes conditions that every legal instance of a relation must satisfy.  Inserts/deletes/updates that violate IC’s are disallowed.  Can be used to ensure application semantics (e.g., sid is a key), or prevent inconsistencies (e.g., sname has to be a string, age must be < 100)  Types of IC’s : Domain constraints, primary key constraints, foreign key constraints, general constraints.

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke17 Constraints over a Single Table  Table Constraints  CHECK conditional-expression CREATE TABLE Sailors (sid INTEGER, sname CHAR(30) NOT NULL, rating INTEGER, age REAL, CONSTRAINT StudentsKey PRIMARY KEY (sid), CHECK (rating >=1 AND rating<=10) ) Rating must be an integer in the range of Mysql does not support !

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke18 Constraints over a Single Table CREATE TABLE Reserves (sid INTEGER, bid INTEGER, day DATE, FOREIGN KEY (sid) REFERENCES Sailors, FOREIGN KEY (bid) REFERENCES Boats, CONSTRAINT noInterlakeRes CHECK ( ‘Interlake’ <> (SELECT B.bname FROM Boats B WHERE B.bid = Reserves.bid) ) ) Interlake boats cannot be reserved.

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke19 Triggers  Trigger: procedure that starts automatically if specified changes occur to the DBMS  Three parts:  Event (activates the trigger)  Condition (tests whether the triggers should run)  Action (what happens if the trigger runs)

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke20 Advantages of using SQL triggers Check the integrity of data. Catch errors in business logic in the database layer. Run the scheduled tasks because the triggers are invoked automatically before or after a change is made to the data in the tables. Audit the changes of data in tables.

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke21 Disadvantages of using SQL triggers It only can provide an extended validation, not all validations. Some simple validations have to be done in the application layer - JavaScript (client side) or JSP, PHP, ASP.NET, Perl, etc. (server side) SQL triggers are invoked and executed invisibly from client-applications therefore it is difficult to figure out what happen in the database layer. SQL triggers may increase the overhead of the database server.

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke22 Trigger Syntax CREATE TRIGGER trigger_name trigger_time trigger_event ON tbl_name FOR EACH ROW trigger_body trigger_time: { BEFORE | AFTER } trigger_event: { INSERT | UPDATE | DELETE }

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke23 Association Even data in tables are deleted or updated, if your statement does not use INSERT, DELETE or UPDATE statement to change data in a table, the triggers associated with the table are not invoked. TRUNCATE TABLE statement removes all data of a table but does not invoke the trigger associated with that table. Statements using the INSERT statement behind the scenes such as REPLACE statement or LOAD DATA statement will invoke the corresponding triggers associated with the table.

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke24 Trigger Example Mysql> Delimiter / Mysql> CREATE TABLE SailorThird LIKE Sailors/ Mysql> CREATE TRIGGER SailorUpdate BEFORE INSERT ON SailorThird FOR EACH ROW BEGIN IF NEW.rating IS NULL THEN SET NEW.rating = 0; ELSEIF NEW.rating <1 THEN SET NEW.rating = 1; ELSEIF NEW.rating > 10 THEN SET NEW.rating = 10; END IF; END;/ Mysql> Load Data Local Infile ‘~/SailorsNew.txt’ Into Table SailorsThird/ Mysql> Delimiter ;

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke25

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke26 To Stop an Operation with Trigger CREATE TABLE Reserves (sid INTEGER, bid INTEGER, day DATE, FOREIGN KEY (sid) REFERENCES Sailors, FOREIGN KEY (bid) REFERENCES Boats, CONSTRAINT noInterlakeRes CHECK ( ‘Interlake’ <> (SELECT B.bname FROM Boats B WHERE B.bid = Reserves.bid) ) ) ; Create Trigger ReservesUpdate Before Insert On Reserves For Each Row Begin If ‘Interlack’ = (Select B.bname From Boats B Where B.bid = New.bid) Then signal sqlstate ‘45000’; End If; End;

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke27 Organize Triggers In database Information_Schema, Table Triggers hold all information about triggers. SELECT * FROM information_schema.triggers WHERE trigger_schema = ‘DatabaseName’ AND trigger_name = ‘TriggerName’; SELECT * FROM information_schema. triggers WHERE trigger_schema = 'database_name' AND event_object_table = 'table_name'; SHOW TRIGGERS FROM classicmodels WHERE ` table ` = 'employees';