1 SQL Constraints and Programming. 2 Agenda Constraints in SQL Systems aspects of SQL.

Slides:



Advertisements
Similar presentations
Data Definition and Integrity Constraints
Advertisements

Transactions - Concurrent access & System failures - Properties of Transactions - Isolation Levels 4/13/2015Databases21.
1 Constraints, Triggers and Active Databases Chapter 9.
CSE 544 Constraints Lecture #3 Friday, January 13, 2011 Dan Suciu , Winter
SQL Lecture 10 Inst: Haya Sammaneh. Example Instance of Students Relation  Cardinality = 3, degree = 5, all rows distinct.
Fall 2005 ICS184/EECS116 – Notes 08 1 ICS 184/EECS116: Introduction to Data Management Lecture Note 8 SQL: Structured Query Language -- DDL.
Cs3431 Constraints Sections 6.1 – 6.5. cs3431 Example CREATE TABLE Student ( sNum int, sName varchar (20), prof int, CONSTRAINT pk PRIMARY KEY (snum),
Transaction Processing Lecture ACID 2 phase commit.
1 Lecture 04 Entity/Relationship Modelling. 2 Outline E/R model (Chapter 5) From E/R diagrams to relational schemas (Chapter 5) Constraints in SQL (Chapter.
1 Introduction to Database Systems CSE 444 Lecture 05: Views, Constraints April 9, 2008.
1 Lecture 06: SQL Friday, January 14, Outline Indexes Defining Views (6.7) Constraints (Chapter 7) We begin E/R diagrams (Chapter 2)
End of SQL: Triggers, Impedance Mismatch and Transactions February 6 th, 2004.
Winter 2002Arthur Keller – CS 1809–1 Schedule Today: Jan. 31 (TH) u Constraints. u Read Sections , Project Part 3 due. Feb. 5 (T) u Triggers,
1 Lecture 05: SQL Wednesday, October 8, Outline Outer joins (6.3.8) Database Modifications (6.5) Defining Relation Schema in SQL (6.6) Indexes.
1 INTERSECT and EXCEPT: (may no be in MySQL) (SELECT R.A, R.B FROM R) INTERSECT (SELECT S.A, S.B FROM S) (SELECT R.A, R.B FROM R) INTERSECT (SELECT S.A,
Dec 15, 2003Murali Mani Transactions and Security B term 2004: lecture 17.
Cs3431 Transactions, Logging and Security. cs3431 Transactions: What and Why? A set of operations on a database must appear as one “unit”. Example: Consider.
SQL Keys and Constraints Justin Maksim. Key Declaration Key constraint defined within the CREATE TABLE command Key can be declared using either the PRIMARY.
M.P. Johnson, DBMS, Stern/NYU, Spring C : Database Management Systems Lecture #15 M.P. Johnson Stern School of Business, NYU Spring, 2005.
Chapter 7 Constraints and Triggers Spring 2011 Instructor: Hassan Khosravi.
SQL: Constraints and Triggers Chapter 6 Ullman and Widom Certain properties we’d like our database to hold Modification of the database may break these.
SQL Constraints & Triggers May 10 th, Agenda Big picture –what are constraints & triggers? –where do they appear? –why are they important? In SQL.
SCUHolliday - coen 1789–1 Schedule Today: u Constraints, assertions, triggers u Read Sections , 7.4. Next u Triggers, PL/SQL, embedded SQL, JDBC.
Relational Database Management Systems. A set of programs to manage one or more databases Provides means for: Accessing the data Inserting, updating and.
1 Lecture 04: SQL Wednesday, January 11, Outline Two Examples Nulls (6.1.6) Outer joins (6.3.8) Database Modifications (6.5)
BIS Database Systems School of Management, Business Information Systems, Assumption University A.Thanop Somprasong Chapter # 10 Transaction Management.
Transactions1 Unit of work on a database. Transactions2 Transactions, concept Logical unit of work on the database –Examples Transfer money from bank.
Winter 2006Keller, Ullman, Cushing9–1 Constraints Commercial relational systems allow much more “fine-tuning” of constraints than do the modeling languages.
1 Lecture 6: Views Friday, January 17th, Updating Views How can I insert a tuple into a table that doesn’t exist? Employee(ssn, name, department,
Phase 2, Answering queries using views. February 2 nd, 2004.
1 SQL Constraints and Programming. 2 Agenda Constraints in SQL Systems aspects of SQL.
Dec 8, 2003Murali Mani Constraints B term 2004: lecture 15.
7 1 Constraints & Triggers Chapter Constraints and triggers? Constraints: Certain properties that the DBMS is required to enforce –E.g. primary.
Constraints and Triggers. What’s IC? Integrity Constraints define the valid states of SQL-data by constraining the values in the base tables. –Restrictions.
1 CS 430 Database Theory Winter 2005 Lecture 4: Relational Model.
Different Constraint Types Type Where Declared When activated Guaranteed to hold? Attribute with attribute on insertion not if CHECK or update subquery.
CS34311 The Relational Model. cs34312 Why Relational Model? Currently the most widely used Vendors: Oracle, Microsoft, IBM Older models still used IBM’s.
Constraining Attribute Values Constrain invalid values –NOT NULL –gender CHAR(1) CHECK (gender IN (‘F’, ‘M’)) –MovieName CHAR(30) CHECK (MovieName IN (SELECT.
1 Advanced Database Concepts Transaction Management and Concurrency Control.
1 Introduction to Database Systems CSE 444 Lecture 04: SQL April 7, 2008.
1 Lecture 5: Outerjoins, Schema Creation and Views Wednesday, January 15th, 2003.
10 1 Chapter 10 - A Transaction Management Database Systems: Design, Implementation, and Management, Rob and Coronel.
1 Lecture 8: SQL Programming and Transactions Friday, January 24, 2003.
1 Lecture 14: Transactions in SQL Wednesday, February 8, 2006.
1 Lecture 06 Data Modeling: E/R Diagrams Wednesday, January 18, 2006.
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
1 Lecture 05: SQL Wednesday, October 8, Outline Database Modifications (6.5) Defining Relation Schema in SQL (6.6) Indexes Defining Views (6.7)
SCUHolliday - coen 1789–1 Schedule Today: u Constraints, assertions, triggers u Read Sections , 7.4. Next u Embedded SQL, JDBC. u Read Sections.
Murali Mani Constraints. Murali Mani Keys: Primary keys and unique CREATE TABLE Student ( sNum int, sName varchar (20), dept char (2), CONSTRAINT key.
1 Constraints and Triggers in SQL. 2 Constraints are conditions that must hold on all valid relation instances SQL2 provides a variety of techniques for.
Constraints and Triggers
Cse 344 March 2nd – E/r diagrams.
SQL: Constraints and Triggers
Cse 344 May 14th – Entities.
2018, Fall Pusan National University Ki-Joune Li
Transactions Properties.
Lecture 06: SQL Systems Aspects
Lecture 05 Views, Constraints
Lecture 17: Systems Aspects of SQL
Lecture 13: Transactions in SQL
Lecture 15: Transactions
Lecture 20: Intro to Transactions & Logging II
Lecture 06: SQL Monday, October 11, 2004.
CSE544 SQL Monday, April 5, 2004.
Lecture 05: SQL Wednesday, October 9, 2002.
Lecture 05: SQL Systems Aspects
-Transactions in SQL -Constraints and Triggers
Advanced Topics: Indexes & Transactions
Lecture 11: Transactions in SQL
Presentation transcript:

1 SQL Constraints and Programming

2 Agenda Constraints in SQL Systems aspects of SQL.

3 Constraints in SQL A constraint = a property that we’d like our database to hold The system will enforce the constraint by taking some actions: –forbid an update –or perform compensating updates

4 Constraints in SQL Constraints in SQL: Keys, foreign keys Attribute-level constraints Tuple-level constraints Global constraints: assertions The more complex the constraint, the harder it is to check and to enforce simplest Most complex

5 Keys OR: CREATE TABLE Product ( name CHAR(30) PRIMARY KEY, category VARCHAR(20)) CREATE TABLE Product ( name CHAR(30) PRIMARY KEY, category VARCHAR(20)) CREATE TABLE Product ( name CHAR(30), category VARCHAR(20) PRIMARY KEY (name)) CREATE TABLE Product ( name CHAR(30), category VARCHAR(20) PRIMARY KEY (name))

6 Keys with Multiple Attributes CREATE TABLE Product ( name CHAR(30), category VARCHAR(20), price INT, PRIMARY KEY (name, category)) CREATE TABLE Product ( name CHAR(30), category VARCHAR(20), price INT, PRIMARY KEY (name, category))

7 Other Keys CREATE TABLE Product ( productID CHAR(10), name CHAR(30), category VARCHAR(20), price INT, PRIMARY KEY (productID), UNIQUE (name, category)) CREATE TABLE Product ( productID CHAR(10), name CHAR(30), category VARCHAR(20), price INT, PRIMARY KEY (productID), UNIQUE (name, category)) There is at most one PRIMARY KEY; there can be many UNIQUE

8 Foreign Key Constraints CREATE TABLE Purchase ( prodName CHAR(30) REFERENCES Product(name), date DATETIME) CREATE TABLE Purchase ( prodName CHAR(30) REFERENCES Product(name), date DATETIME) prodName is a foreign key to Product(name) name must be a key in Product Referential integrity constraints

9 NameCategory Gizmogadget CameraPhoto OneClickPhoto ProdNameStore GizmoWiz CameraRitz CameraWiz ProductPurchase

10 Foreign Key Constraints OR (name, category) must be a PRIMARY KEY CREATE TABLE Purchase ( prodName CHAR(30), category VARCHAR(20), date DATETIME, FOREIGN KEY (prodName, category) REFERENCES Product(name, category) CREATE TABLE Purchase ( prodName CHAR(30), category VARCHAR(20), date DATETIME, FOREIGN KEY (prodName, category) REFERENCES Product(name, category)

11 NameCategory Gizmogadget CameraPhoto OneClickPhoto ProdNameStore GizmoWiz CameraRitz CameraWiz ProductPurchase What happens during updates ? Types of updates: In Purchase: insert/update In Product: delete/update

12 What happens during updates ? SQL has three policies for maintaining referential integrity: Reject violating modifications (default) Cascade: after a delete/update do a delete/update Set-null set foreign-key field to NULL READING ASSIGNEMNT: 7.1.5, 7.1.6

13 Constraints on Attributes and Tuples Constraints on attributes: NOT NULL-- obvious meaning... CHECK condition-- any condition ! Constraints on tuples CHECK condition

14 CREATE TABLE Purchase ( prodName CHAR(30) CHECK (prodName IN SELECT Product.name FROM Product), date DATETIME NOT NULL) CREATE TABLE Purchase ( prodName CHAR(30) CHECK (prodName IN SELECT Product.name FROM Product), date DATETIME NOT NULL) What is the difference from Foreign-Key ?

15 General Assertions CREATE ASSERTION myAssert CHECK NOT EXISTS( SELECT Product.name FROM Product, Purchase WHERE Product.name = Purchase.prodName GROUP BY Product.name HAVING count(*) > 200) CREATE ASSERTION myAssert CHECK NOT EXISTS( SELECT Product.name FROM Product, Purchase WHERE Product.name = Purchase.prodName GROUP BY Product.name HAVING count(*) > 200)

16 Final Comments on Constraints Can give them names, and alter later –Read in the book !!! We need to understand exactly when they are checked We need to understand exactly what actions are taken if they fail

17 Triggers in SQL A trigger contains an event, a condition, an action. Event = INSERT, DELETE, UPDATE Condition = any WHERE condition (may refer to the old and the new values) Action = more inserts, deletes, updates Many, many more bells and whistles... Read in the book (it only scratches the surface...)

18 Programming SQL Embedded SQL direct SQL (= ad-hoc SQL) * Stored Procedures

19 Programs with Embedded SQL Host language + Embedded SQL Preprocessor Host Language + function calls Host language compiler Host language program Preprocessor Host language compiler Call-level interface (CLI): ODBC,JDBC, ADO

20 Embedded SQL SQL code within C (more languages are supported, but not all) Impedance mismatch = incompatible types (types variables) Not so popular / recommended..

21 Direct SQL Use specific interfaces (ODBC..) to call the DB Execute “Strings” or use “smarter” drivers We use it.. More details on the following programming lectures

22 Stored Procedures Different for each DBMS “Enhanced” programming language (variables, loops..) better Security / better Abstraction (too bad this is just a basic course..)

23 Transactions Address two issues: Access by multiple users –Remember the “client-server” architecture: one server with many clients Protection against crashes

24 Multiple users: single statements Client 1: UPDATE Product SET Price = Price – 1.99 WHERE pname = ‘Gizmo’ Client 2: UPDATE Product SET Price = Price*0.5 WHERE pname=‘Gizmo’ Client 1: UPDATE Product SET Price = Price – 1.99 WHERE pname = ‘Gizmo’ Client 2: UPDATE Product SET Price = Price*0.5 WHERE pname=‘Gizmo’ Two managers attempt to do a discount. Will it work ?

25 Multiple users: multiple statements Client 1:INSERT INTO SmallProduct(name, price) SELECT pname, price FROM Product WHERE price <= 0.99 DELETE Product WHERE price <=0.99 Client 2:SELECT count(*) FROM Product SELECT count(*) FROM SmallProduct Client 1:INSERT INTO SmallProduct(name, price) SELECT pname, price FROM Product WHERE price <= 0.99 DELETE Product WHERE price <=0.99 Client 2:SELECT count(*) FROM Product SELECT count(*) FROM SmallProduct What’s wrong ?

26 Protection against crashes Client 1: INSERT INTO SmallProduct(name, price) SELECT pname, price FROM Product WHERE price <= 0.99 DELETE Product WHERE price <=0.99 Client 1: INSERT INTO SmallProduct(name, price) SELECT pname, price FROM Product WHERE price <= 0.99 DELETE Product WHERE price <=0.99 What’s wrong ? Crash !

27 Transactions Transaction = group of statements that must be executed atomically Transaction properties: ACID –ATOMICITY = all or nothing –CONSISTENCY = leave database in consistent state –ISOLATION = as if it were the only transaction in the system –DURABILITY = store on disk !

28 Transactions: Serializability Serializability = the technical term for isolation An execution is serial if it is completely before or completely after any other function’s execution An execution is serializable if it equivalent to one that is serial DBMS can offer serializability guarantees

29 Example T1: R(x) R(y) W(x) W(y) T2: R(x) R(z) R(y) W(x) W(y) R(x) R(y) W(x) R(x) R(z) W(y) R(y) W(x) W(y) R(x) R(y) W(x) R(x) R(z) R(y) W(y) W(y) W(x) R(x) R(z) R(y) R(x) R(y) W(x) W(y) W(y) W(x)

30 Serializability Enforced with locks, like in Operating Systems ! But this is not enough: LOCK A [write A=1] UNLOCK A LOCK B [write B=2] UNLOCK B LOCK A [write A=1] UNLOCK A LOCK B [write B=2] UNLOCK B LOCK A [write A=3] UNLOCK A LOCK B [write B=4] UNLOCK B LOCK A [write A=3] UNLOCK A LOCK B [write B=4] UNLOCK B User 1 User 2 What is wrong ? time

31 Serializability Solution: two-phase locking –Lock everything at the beginning –Unlock everything at the end Read locks: many simultaneous read locks allowed Write locks (update/delete): only one write lock allowed Insert locks: one per table

32 Isolation Levels in SQL 1.“Dirty reads” SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED 2.“Committed reads” SET TRANSACTION ISOLATION LEVEL READ COMMITTED 3.“Repeatable reads” SET TRANSACTION ISOLATION LEVEL REPEATABLE READ 4.Serializable transactions (default): SET TRANSACTION ISOLATION LEVEL SERIALIZABLE Recommended Reading: chapter 8.6

“Dirty” 33

“Committed” VS “Repeatable” 34

“Repeatable” VS “Serializable” 35