1 / 30

Advanced SQL

Advanced SQL. -Software School of Hunan University- 2006.09. Advanced SQL Overview. The SQL standard has evolved in recent years to define a language that is computationally complete and supports features required by a modern object-relational DBMS.

yosef
Download Presentation

Advanced SQL

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Advanced SQL -Software School of Hunan University- 2006.09

  2. Advanced SQL Overview • The SQL standard has evolved in recent years to define a language that is computationally complete and supports features required by a modern object-relational DBMS. • An object-relational DBMSis a relational DBMS extended to support object-oriented features such as inheritance, user defined types, and polymorphism.

  3. Problems with the Relational Model • Object-relational DBMSs have been proposed to handle some of the problems with the relational model: • Poor representation of real-world entities • Homogenous data structure • All tuples of a relation must have the same number and types of attributes. • Impedance mismatch between program code and SQL. • SQL is declarative and set based -- Java is procedural and object based. • Difficult to extend database to support new types and operations. • Required for many application areas like CAD and GIS.

  4. Common Features of anObject-Relational DBMS • An object-relational DBMS (ORDBMS) has features such as: • Abstract (user) defined data types • Support for inheritance and polymorphism • Active constraints such as triggers • Ability to define procedures

  5. SQL:1999 and SQL:2003 We now will discuss some advanced features of the SQL92 standard and the two recent revisions to the SQL standard that have added object-relational features to SQL. SQL2: • Transactions - SQL isolation levels SQL:1999/2003: • User-defined types • support for linear recursion • Triggers (later) • Persistent Stored Modules (PSM) (not covered) • Allows user to write code in 3GL language and execute it within DBMS. • Many databases have support for this as stored procedures.

  6. Transaction Management Overview The database system must ensure that the data stored in the database is always consistent. There are two challenges in preserving database consistency: 1) The database system must handlefailuresof various kinds such as hardware failures and system crashes. 2) The database system must support concurrent executionof multiple transactions and guarantee that this concurrency does not lead to inconsistency. A transactionis an atomicprogram that executes on the database and preserves the consistency of the database. The input to a transaction is a consistent database AND the output of the transaction must also be a consistent database. A transaction must execute completely or not at all.

  7. Transaction ManagementMotivating Example Consider a person who wants to transfer $50 from a savings account with balance $1000 to a checking account with current balance = $250. 1) At the ATM, the person starts the process by telling the bank to remove $50 from the savings account. 2) The $50 is removed from the savings account by the bank. 3) Before the customer can tell the ATM to deposit the $50 in the checking account, the ATM “crashes.” Where has the $50 gone? It is lost if the ATM did not support transactions! The customer wanted the withdraw and deposit to both happen in one step, or neither action to happen.

  8. ACID Properties To preserve integrity, transactions have the following properties: Atomicity(原子性)- Either all operations of the transaction are properly reflected in the database or none are. Consistency(一致性)- Execution of a transaction in isolation preserves the consistency of the database. Isolation(隔离性)- Although multiple transactions may execute concurrently, each transaction must be unaware of other concurrently executing transactions. Durability(持续性)- After a transaction successfully completes, the changes it has made to the database persist, even if there are system failures.

  9. Transaction Definition in SQL • In SQL, a transaction begins implicitly. • A transaction in SQL ends by: • Commitaccepts updates of current transaction. • Rollbackaborts current transaction and discards its updates. Failures may also cause a transaction to be aborted. • By default transactions are executed according to the ACID properties. It is possible to specify a weaker isolation level to improve performance. • This is only really useful for read-only transactions. • An isolation level applies only to your perspective of the database, not other transactions/users.

  10. Example Transactions 1) Transaction to transfer $50 between two bank accounts: BEGIN TRANSACTION; UPDATE Account WHERE num = 'S1' SET balance=balance-50; UPDATE Account WHERE num = 'C1' SET balance=balance+50; COMMIT; 2) Transaction to calculate totals for all saving and checking accounts: BEGIN TRANSACTION; SELECT SUM(balance) WHERE accType = 'Savings'; SELECT SUM(balance) WHERE accType = 'Checking'; COMMIT;

  11. User-Defined Types in SQL:2003 General form (simple version): CREATE TYPEtypeName ASbuiltInType [FINAL]; Final means that cannot create subtypes of the new type. Example: Create SSN type: CREATE TYPESSN AS VARCHAR(10) FINAL; User-defined types may either extend base types as shown here or define a structure similar to a class with attributes, routines, and operators.

  12. User-Defined Types Example CREATE TYPE PersonType AS ( dateOfBirth DATE, fName VARCHAR(15), lName VARCHAR(15), sex CHAR ) INSTANTIABLE NOT FINAL REF IS SYSTEM GENERATED INSTANCE METHOD age() RETURNS INTEGER; CREATE INSTANCE METHOD age() RETURNS INTEGER FOR PersonType BEGIN RETURN /* Code to find age from Self.dateOfBirth */ END; Can create objects Can create subtypes DB creates references Define method

  13. Subtypes in SQL:2003 General form: CREATE TYPEtypeName UNDERinheritType AS ... Example: CREATE TYPEStaffType UNDERPersonType AS ( staffNo VARCHAR(5), salary DECIMAL(7,2) ) INSTANTIABLE NOT FINAL; A subtype inherits all methods and attributes from its supertype. It may override any inherited methods/attributes.

  14. Recursive Queries in SQL2003 General form: WITH RECURSIVEtableName(attr1,attr2,..attrN) AS <SELECT query that defines recursive relation> <SELECT query that uses recursive relation> Example: Return all employees supervised by 'J. Jones'. WITH RECURSIVEsupervises(supId,empId) AS (SELECT supereno, eno FROM emp) UNION (SELECT S1.supId, S2.empId FROM supervises S1, supervises S2 WHERE S1.empId = S2.supId) SELECT E1.ename FROM supervises, emp AS E, emp AS E2 WHERE supervises.supId = E2.eno and E2.ename = 'J. Jones' and supervises.empId = E1.ename;

  15. Conclusion Object-relational DBMSs often support the SQL:1999/2003 standards allowing for the use of user defined datatypeS, active consistency checks (triggers), inheritance, and recursive queries.

  16. Enterprise Constraints General enterprise constraints are often too complicated to be enforced using foreign keys and CHECK. We have already seen how general constraints can be enforced by creating and checking assertions: CREATE ASSERTIONassertionName CHECK(condition) However, assertions are not very efficient to implement, so most database vendors use another mechanism for enforcing constraints called triggers.

  17. Triggers One of the problems with assertions is that they may have to be checked on every database modification unless the DBMS is intelligent enough to know when they should be checked. A solution to this problem is to explicitly tell the DBMS what events are of interest and provide an action that should be performed when that event occurs. Triggersare used to perform actions when a defined event occurs. They are newly standardized in SQL3 but have been present in various DBMSs for some time.

  18. Event-Condition-Action Rules Triggers are also called event-condition-action (ECA) rules. When an eventoccurs (such as inserting a tuple) that satisfies a given condition(any SQL boolean-valued expression) an actionis performed (which is any sequence of SQL statements). Thus, triggers provide a very general way for detecting events and responding to them.

  19. Triggers Example Consider this situation where triggers are useful. The WorksOn relation has a foreign key to Emp (eno). If a user inserts a record in WorksOn and the employee does not exist, the insert fails. However with triggers, we can accept the insertion into WorksOn and then create a new record in Emp so that the foreign key constraint is not violated.

  20. Example Trigger CREATE TRIGGER insertWorksOn AFTER INSERT ON WorksOn REFERENCING NEW ROW AS NewWO FOR EACH ROW WHEN (NewWO.eno NOT IN (SELECT eno FROM emp)) INSERT INTO Emp (eno) VALUES (NewWO.eno); Event Condition Action

  21. Triggers Syntax CREATE TRIGGER <name> BEFORE | AFTER | INSTEAD OF <events> [<referencing clause>] [FOR EACH ROW] [WHEN (<condition>)] <action> Notes: BEFORE, AFTER, INSTEAD OF indicate when a trigger is executed. <events> is the events that the trigger will be executed for. It will be one of these events: INSERT ON R DELETE ON R UPDATE [OF A1,A2,..,An] on R

  22. Triggers Syntax - FOR EACH ROW There are two types of triggers: row-level triggers that are executed for each row that is updated, deleted, or inserted. Statement-level triggers that are only executed once per statement regardless of how many tuples are affected. Inserting the clause FOR EACH ROW indicates a row-level trigger (the default is a statement-level trigger).

  23. Triggers Syntax - Referencing • The referencing clause allows you to assign names to the row or table being affected by the triggered event: • INSERT statements imply a new tuple (for row-level) or new set of tuples (for statement-level). • DELETE implies an old tuple or table. • UPDATE implies both. These tuples or tables can be referred to using the syntax: [NEW OLD] [TUPLE TABLE] AS <name> Example: Statement-level trigger on an update: REFERENCES OLD TABLE AS oldTbl NEW TABLE as newTbl

  24. Triggers Syntax - Condition The condition is used to filter out when the trigger action is performed. For example, even though an insert event may occur, you may only want to execute the trigger if a certain condition holds. • Any SQL boolean-valued condition can be used. The condition clause is evaluated before or after the triggering event, depending on whether BEFORE or AFTER is used in the event.

  25. Triggers Syntax - Action • The action is performed when the event occurs and the condition is satisfied. • The action is one or more SQL statements. • If more than one SQL statement is executed, they should be in a BEGIN .. END block.

  26. Creating the Example Database CREATE TRIGGER cheatingEmployee AFTER UPDATE OF salary on Emp REFERENCING OLD ROW AS old NEW ROW AS new FOR EACH ROW WHEN (new.salary > old.salary*1.1) INSERT INTO auditEmp VALUES (new.eno,new.salary,old.salary);

  27. Triggers and Views One interesting use of triggers is to allow updates on views that are not normally updatable. This is done by using the INSTEAD OF clause. When an update is executed, instead of executing the update command given by the user, the trigger executes its own SQL statements. For instance, this may allow it to perform inserts on many tables that were combined to form a single view.

  28. Constraints Practice Questions Write the assertions to check the following conditions: 1) No employee with title 'EE' can make more money than an employee with title 'SA'. 2) A manager of a department must be recorded as being in that department in the Emp relation. Write triggers for these cases: 3) When an employee is added to the Emp table in epartment 'D1' with no supervisor, make their supervisor 'E8'. 4) Write the same trigger as a statement-level trigger. 5) Write a trigger that deletes all tuples in the WorksOn relation for an employee when the employee is deleted from the Emp relation.

  29. Conclusion More complicated constraints can be enforced in the database using assertions or triggers. Assertions specify general constraints but may be inefficient to enforce. Triggers allow for efficient enforcement of general constraints by specifying specific events to trap and actions to take.

  30. Objectives Create assertions and triggers from high-level descriptions. Compare and contrast assertions and triggers

More Related