Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Database Management Systems Chapter 5 SQL."— Presentation transcript:

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

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

3 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;

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

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

6 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.

7 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.

8 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

9 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

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

11 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.

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

13 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 )

14 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

15 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;

16 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.

17 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 1-10. Mysql does not support !

18 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.

19 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)

20 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.

21 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.

22 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 }

23 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.

24 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 ;

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

26 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;

27 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';


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

Similar presentations


Ads by Google