Presentation is loading. Please wait.

Presentation is loading. Please wait.

2018, Fall Pusan National University Ki-Joune Li

Similar presentations


Presentation on theme: "2018, Fall Pusan National University Ki-Joune Li"— Presentation transcript:

1 2018, Fall Pusan National University Ki-Joune Li
More about SQL 2018, Fall Pusan National University Ki-Joune Li These slides are made from the materials that Prof. Jeffrey D. Ullman distributes via his course web page (

2 Views A view is a “virtual table,” a relation that is defined in terms of the contents of other tables and views. Declare by: CREATE VIEW <name> AS <query>; In contrast, a relation whose value is really stored in the database is called a base table. Example View CanDrink(Drinker, Beer) is created CREATE VIEW CanDrink AS SELECT drinker, beer FROM Frequents, Sells WHERE Frequents.bar = Sells.bar;

3 Example: Accessing a View
You may query a view as if it were a base table. There is a limited ability to modify views if the modification makes sense as a modification of the underlying base table. Example: SELECT beer FROM CanDrink WHERE drinker = ‘Sally’; PROJbeer SELECTdrinker=‘Sally’ CanDrink PROJdrinker, beer JOIN Frequents Sells

4 DMBS Optimization It is interesting to observe that the typical DBMS will then “optimize” the query by transforming the algebraic expression to one that can be executed faster. Key optimizations: Push selections down the tree. Eliminate unnecessary projections. PROJbeer JOIN SELECTdrinker=‘Sally’ Sells Frequents Notice how most tuples are eliminated from Frequents before the expensive join.

5 Materialized View Simple View Materialized View What's the difference?
CREATE VIEW CanDrink AS SELECT drinker, beer FROM Frequents, Sells WHERE Frequents.bar = Sells.bar; Materialized View CREATE MATERIALIZED VIEW CanDrink AS What's the difference?

6 Referential Constraint and Foreign Key
Key in other table used to make a reference to tuple in other table SQL Studio(name, address, presC#) MovieExec(name, address, cert#, netWorth) CREATE TABLE Studio ( name CHAR(20) PRIMARY KEY, address VARCHAR(100), presC# INT REFERENCE MovieExec(cert#) ); Referential Constraint CREATE TABLE Studio ( name CHAR(20) PRIMARY KEY, address VARCHAR(100), presC# INT, FOREIGN KEY (presC#) REFERENCE MovieExec(cert#) );

7 Enforcing Foreign-Key Constraints
If there is a foreign-key constraint from attributes of relation R to the primary key of relation S, two violations are possible: An insert or update to R introduces values not found in S. A deletion or update to S causes some tuples of R to “dangle.”

8 Actions Taken Suppose R = Sells, S = Beers.
Insertion or update to Sells with a nonexistent beer: Rejected. Deletion or update to Beers that removes a beer value found in some tuples of Sells: Default : Reject the modification. Cascade : Make the same changes in Sells. Deleted beer: delete Sells tuple. Updated beer: change value in Sells. Set NULL : Change the beer to NULL.

9 Example: Cascade Deletion of the Bud tuple from Beers.
Then delete all tuples from Sells that have beer = ’Bud’. Update of the Bud tuple by changing ’Bud’ to ’Budweiser’. Then change all Sells tuples with beer = ’Bud’ so that beer = ’Budweiser’. Cascade deletion Bud Delete Bud Bud Cascade updates Update Beers Sells

10 Example: Set NULL Deletion of the Bud tuple from Beers.
Change all tuples of Sells that have beer = ’Bud’ to have beer = NULL. NULL NULL Bud Delete Beers Sells

11 Attribute-Based Checks
Put a constraint on the value of a particular attribute. CHECK( <condition> ) must be added to the declaration for the attribute. The condition may use the name of the attribute, but any other relation or attribute name must be in a subquery. Example CREATE TABLE Sells ( bar CHAR(20), beer CHAR(20) CHECK ( beer IN SELECT name FROM Beers)), price REAL CHECK ( price <= 5.00 ) );

12 Timing of Checks An attribute-based check is checked only when a value for that attribute is inserted or updated. Example CHECK (price <= 5.00) checks every new price and rejects it if it is more than $5. CHECK (beer IN (SELECT name FROM Beers)) not checked if a beer is deleted from Beers Can NOT be used for the Referential Constraint

13 Tuple-Based Checks CHECK ( <condition> ) may be added as another element of a schema definition. The condition may refer to any attribute of the relation, but any other attributes or relations require a subquery. Checked on insertion or update only (NOT delete). Example Only Joe’s Bar can sell beer for more than $5: CREATE TABLE Sells ( bar CHAR(20), beer CHAR(20), price REAL, CHECK (bar = ’Joe’’s Bar’ OR price <= 5.00) );

14 Assertions Assertion: database-schema elements, like relations
Defined by: CREATE ASSERTION <name> CHECK ( <condition> ); Condition may refer to any relation or attribute in the database schema. Example: In Sells(bar, beer, price), no bar may charge an average of more than $5. CREATE ASSERTION NoRipoffBars CHECK ( NOT EXISTS ( SELECT bar FROM Sells GROUP BY bar HAVING 5.00 < AVG(price) )); Bars with an average price above $5

15 Example: Assertion In Drinkers(name, addr, phone) and Bars(name, addr, license), there cannot be more bars than drinkers. CREATE ASSERTION FewBar CHECK ( (SELECT COUNT(*) FROM Bars) <= (SELECT COUNT(*) FROM Drinkers) );

16 Timing of Assertion Checks
In principle, we must check every assertion after every modification to any relation of the database. A clever system can observe that only certain changes could cause a given assertion to be violated. Example: No change to Beers can affect FewBar. Neither can an insertion to Drinkers.

17 Triggers Attribute- and tuple-based checks have limited capabilities.
Assertions sufficiently general for most constraint applications, they are hard to implement efficiently. DBMS must have real intelligence to avoid checking assertions that couldn’t possibly have been violated. Trigger: a more powerful expression on ECA (Event-Condition- Action) Only in SQL3

18 Example: Trigger Definition
CREATE TRIGGER BeerTrigger AFTER INSERT ON Sells REFERENCING NEW ROW AS NewTuple FOR EACH ROW WHEN (NewTuple.beer NOT IN (SELECT name FROM Beers)) INSERT INTO Beers(name) VALUES(NewTuple.beer); The event The condition The action

19 Transaction - Example Flights (fltNo, FltDate, seatNo, seatStatus)
SELECT seatNo FROM Flights WHERE fltNo=123 AND FltDATE=DATE ‘ ’ AND seatStatus=‘available’;  22A is found as empty seat UPDATE Flights SET seatStatus=‘occupied’ WHERE FltNo=123 AND FltDATE=DATE ‘ ’ and seatNo=‘22A’  What may happen?

20 Transaction Transaction A set of operations Atomic :
All or Nothing : Consistent State of Database Example : Flight Reservation Cf. Partially Done : Inconsistent State Partially Committed Committed ALL Activated NOTHING Failed Aborted

21 Transaction – BEGIN TRAN and COMMIT TRAN
Syntax BEGIN TRAN T1; Select/Insert/Delete/Update SQL Statements COMMIT TRAN T1; DBMS must maintain the transaction correctly ACID Atomic Concurrent Isolated Duarable

22 Serializability Problems may happen in concurrent transactions
What happens after these transactions ? Serial Schedule : Always Correct T1 T2 and T2 T1 Concurrent Schedule Serializable if Result (T1 || T2) = Result(T1 T2) or Result(T2 T1) We assume that serial executions are correct Make the results of concurrent execution as the result of one of the serial executions.

23 Referential Constraint - Deferable
Violation of Referential Constraint Reference to Non-existing Foreign Key Example Deletion (or Update) of a tuple referenced by other tuple Insertion of a tuple with a reference to non-existing tuple Should be protected by DBMS DEFERABLE vs. NON DEFERABLE CREATE TABLE Studio ( name CHAR(20) PRIMARY KEY, address VARCHAR(100), presC# INT UNIQUE , REFERENCE MovieExec(cert#) DEFERABLE INITIALLY DEFERED );

24 Index Index SQL Accelerating search speed B+-tree, Hash etc.
CREATE INDEX ScoreIndex ON Student(score); CREATE INDEX KeyIndex ON Movies(title, year);

25 Choosing a Policy When we declare a foreign key, we may choose policies SET NULL or CASCADE independently for deletions and updates. Follow the foreign-key declaration by: ON [UPDATE, DELETE][SET NULL/CASCADE] Default: reject Example CREATE TABLE Sells ( bar CHAR(20), beer CHAR(20), price REAL, FOREIGN KEY(beer) REFERENCES Beers(name) ON DELETE SET NULL ON UPDATE CASCADE );


Download ppt "2018, Fall Pusan National University Ki-Joune Li"

Similar presentations


Ads by Google