Database SQL Update Commands Management Peter Wood

SQL Updates SQL Update Commands SQL Views SQL Transactions I Insertion of one row: INSERT INTO R VALUES . . .

I Insertion using a query: INSERT INTO R SELECT ... I Deletion: DELETE FROM R WHERE . . .

I e.g., DELETE FROM Drinkers WHERE name=’Alice’; will all rows in which Alice appears the Drinkers I Updating: UPDATE R SET . . . WHERE . . .

I e.g., to increase all the March Hare’s prices by 5% UPDATE Sells SET price = price * 1.05 WHERE pub=’March Hare’; Database Updates and Constraints Management Peter Wood

SQL Updates SQL Update Commands SQL Views SQL Transactions Updates can cause constraints to be violated

I a row with a duplicate primary key value

I insert/update a row with a value corresponding primary key value does not exist

I delete/update a row with a primary key value referenced by a foreign key value The default behaviour is for the database system to disallow such updates. Assume name is the primary key for the Pubs relation.

create table Sells (... foreign key (pub) references Pubs on delete cascade on update set , . . . );

Database Foreign Key Constraints Management In the foreign key definition, we can specify either Peter Wood SQL Updates I ON DELETE CASCADE SQL Update Commands SQL Views I ON UPDATE CASCADE SQL Transactions for actions on the referenced relation to cascade to referencing relation, or

I ON DELETE SET NULL I ON UPDATE SET NULL for the referencing relation’s values to be set to null Database Foreign Key Constraints Management In the foreign key definition, we can specify either Peter Wood SQL Updates I ON DELETE CASCADE SQL Update Commands SQL Views I ON UPDATE CASCADE SQL Transactions for actions on the referenced relation to cascade to referencing relation, or

I ON DELETE SET NULL I ON UPDATE SET NULL for the referencing relation’s values to be set to null Assume name is the primary key for the Pubs relation.

create table Sells (... foreign key (pub) references Pubs on delete cascade on update set null, . . . ); Database Other Constraints Management Peter Wood

SQL Updates SQL Update Commands SQL Views SQL Transactions

I We have already covered primary key and foreign key constraints I Other integrity constraints on a single relation include:

I not null I unique I check(. . . )

I appear in create table statement

I e.g., check (price > 0) Database Views Management Peter Wood

SQL Updates SQL Update Commands I So far we have been operating at the logical level of SQL Views the database. SQL Transactions

I For various reasons (e.g. security) not all users should have access to the entire logical model.

I The (or external) level provides appropriate access for users.

I Views are defined using queries.

I (Virtual) views are not precomputed and their results stored.

I Instead they can be queried and the system “combines” the query and view definition.

I SQL syntax is CREATE VIEW V AS SELECT . . . pub beer price Horse and Hound Bad Habit 1.50 Horse and Hound Rampant Ram 2.00 Hound and Hare Shining Wit 2.75 Hound and Hare Rampant Ram 2.50 Sells: March Hare Bad Habit 1.75 March Hare Rampant Ram 2.50 Black Horse Bad Habit 2.50 Black Horse Shining Wit 2.25 Black Horse Rampant Ram 2.50 White Horse Rampant Ram 2.75

CREATE VIEW cheapBeers AS SELECT pub, beer FROM Sells WHERE price <= 2.00;

Database Defining a View Management Define a view for finding which pubs sell cheap beer Peter Wood (price 2.00 or less). SQL Updates SQL Update Commands SQL Views SQL Transactions CREATE VIEW cheapBeers AS SELECT pub, beer FROM Sells WHERE price <= 2.00;

Database Defining a View Management Define a view for finding which pubs sell cheap beer Peter Wood (price 2.00 or less). SQL Updates SQL Update Commands SQL Views pub beer price SQL Transactions Horse and Hound Bad Habit 1.50 Horse and Hound Rampant Ram 2.00 Hound and Hare Shining Wit 2.75 Hound and Hare Rampant Ram 2.50 Sells: March Hare Bad Habit 1.75 March Hare Rampant Ram 2.50 Black Horse Bad Habit 2.50 Black Horse Shining Wit 2.25 Black Horse Rampant Ram 2.50 White Horse Rampant Ram 2.75 Database Defining a View Management Define a view for finding which pubs sell cheap beer Peter Wood (price 2.00 or less). SQL Updates SQL Update Commands SQL Views pub beer price SQL Transactions Horse and Hound Bad Habit 1.50 Horse and Hound Rampant Ram 2.00 Hound and Hare Shining Wit 2.75 Hound and Hare Rampant Ram 2.50 Sells: March Hare Bad Habit 1.75 March Hare Rampant Ram 2.50 Black Horse Bad Habit 2.50 Black Horse Shining Wit 2.25 Black Horse Rampant Ram 2.50 White Horse Rampant Ram 2.75

CREATE VIEW cheapBeers AS SELECT pub, beer FROM Sells WHERE price <= 2.00; pub beer Horse and Hound Bad Habit Horse and Hound Rampant Ram March Hare Bad Habit Find pubs selling Bad Habit for 2.00 or less in Bloomsbury:

SELECT pub FROM cheapBeers, Pubs WHERE beer=’Bad Habit’ AND cheapBeers.pub=Pubs.name AND Pubs.location=’Bloomsbury’;

pub Horse and Hound March Hare

Database Querying a View Management Peter Wood SELECT * FROM cheapBeers; SQL Updates SQL Update Commands SQL Views SQL Transactions Find pubs selling Bad Habit for 2.00 or less in Bloomsbury:

SELECT pub FROM cheapBeers, Pubs WHERE beer=’Bad Habit’ AND cheapBeers.pub=Pubs.name AND Pubs.location=’Bloomsbury’;

pub Horse and Hound March Hare

Database Querying a View Management Peter Wood SELECT * FROM cheapBeers; SQL Updates SQL Update Commands pub beer SQL Views SQL Transactions Horse and Hound Bad Habit Horse and Hound Rampant Ram March Hare Bad Habit SELECT pub FROM cheapBeers, Pubs WHERE beer=’Bad Habit’ AND cheapBeers.pub=Pubs.name AND Pubs.location=’Bloomsbury’;

pub Horse and Hound March Hare

Database Querying a View Management Peter Wood SELECT * FROM cheapBeers; SQL Updates SQL Update Commands pub beer SQL Views SQL Transactions Horse and Hound Bad Habit Horse and Hound Rampant Ram March Hare Bad Habit Find pubs selling Bad Habit for 2.00 or less in Bloomsbury: pub Horse and Hound March Hare

Database Querying a View Management Peter Wood SELECT * FROM cheapBeers; SQL Updates SQL Update Commands pub beer SQL Views SQL Transactions Horse and Hound Bad Habit Horse and Hound Rampant Ram March Hare Bad Habit Find pubs selling Bad Habit for 2.00 or less in Bloomsbury:

SELECT pub FROM cheapBeers, Pubs WHERE beer=’Bad Habit’ AND cheapBeers.pub=Pubs.name AND Pubs.location=’Bloomsbury’; Database Querying a View Management Peter Wood SELECT * FROM cheapBeers; SQL Updates SQL Update Commands pub beer SQL Views SQL Transactions Horse and Hound Bad Habit Horse and Hound Rampant Ram March Hare Bad Habit Find pubs selling Bad Habit for 2.00 or less in Bloomsbury:

SELECT pub FROM cheapBeers, Pubs WHERE beer=’Bad Habit’ AND cheapBeers.pub=Pubs.name AND Pubs.location=’Bloomsbury’;

pub Horse and Hound March Hare name loc name loc Horse and Hound B Alice I Hound and Hare I Bob B Pubs: Drinkers: March Hare B Carol I Black Horse I Dave B White Horse B Eve S

CREATE VIEW coLocated(drinker,pub) AS SELECT Drinkers.name, Pubs.name FROM Pubs, Drinkers WHERE Pubs.loc=Drinkers.loc;

Note that the view defines new attribute names.

Database Defining Another View Management Peter Wood

Define a view relating drinkers and pubs that are located SQL Updates SQL Update Commands in the same area: SQL Views SQL Transactions CREATE VIEW coLocated(drinker,pub) AS SELECT Drinkers.name, Pubs.name FROM Pubs, Drinkers WHERE Pubs.loc=Drinkers.loc;

Note that the view defines new attribute names.

Database Defining Another View Management Peter Wood

Define a view relating drinkers and pubs that are located SQL Updates SQL Update Commands in the same area: SQL Views SQL Transactions name loc name loc Horse and Hound B Alice I Hound and Hare I Bob B Pubs: Drinkers: March Hare B Carol I Black Horse I Dave B White Horse B Eve S Note that the view defines new attribute names.

Database Defining Another View Management Peter Wood

Define a view relating drinkers and pubs that are located SQL Updates SQL Update Commands in the same area: SQL Views SQL Transactions name loc name loc Horse and Hound B Alice I Hound and Hare I Bob B Pubs: Drinkers: March Hare B Carol I Black Horse I Dave B White Horse B Eve S

CREATE VIEW coLocated(drinker,pub) AS SELECT Drinkers.name, Pubs.name FROM Pubs, Drinkers WHERE Pubs.loc=Drinkers.loc; Database Defining Another View Management Peter Wood

Define a view relating drinkers and pubs that are located SQL Updates SQL Update Commands in the same area: SQL Views SQL Transactions name loc name loc Horse and Hound B Alice I Hound and Hare I Bob B Pubs: Drinkers: March Hare B Carol I Black Horse I Dave B White Horse B Eve S

CREATE VIEW coLocated(drinker,pub) AS SELECT Drinkers.name, Pubs.name FROM Pubs, Drinkers WHERE Pubs.loc=Drinkers.loc;

Note that the view defines new attribute names. I all we can do is insert (’Mad Hatter’,NULL) into Pubs and (’Fred’,NULL) into Drinkers I but now (’Fred’,’Mad Hatter’) isn’t even in the view when we query it

I if pub name is a key, we know the Black Horse is in Islington I therefore Fred must live in Islington I so insert (’Fred’,’Islington’) into Drinkers I What if instead INSERT INTO coLocated VALUES(’Fred’,’Mad Hatter’)?

Database Inserting into views Management Peter Wood

SQL Updates SQL Update Commands I Since a view is virtual, any insertion must be to the SQL Views table(s) on which the view is defined. SQL Transactions I What if INSERT INTO coLocated VALUES(’Fred’,’Black Horse’)? I all we can do is insert (’Mad Hatter’,NULL) into Pubs and (’Fred’,NULL) into Drinkers I but now (’Fred’,’Mad Hatter’) isn’t even in the view when we query it

I therefore Fred must live in Islington I so insert (’Fred’,’Islington’) into Drinkers I What if instead INSERT INTO coLocated VALUES(’Fred’,’Mad Hatter’)?

Database Inserting into views Management Peter Wood

SQL Updates SQL Update Commands I Since a view is virtual, any insertion must be to the SQL Views table(s) on which the view is defined. SQL Transactions I What if INSERT INTO coLocated VALUES(’Fred’,’Black Horse’)?

I if pub name is a key, we know the Black Horse is in Islington I all we can do is insert (’Mad Hatter’,NULL) into Pubs and (’Fred’,NULL) into Drinkers I but now (’Fred’,’Mad Hatter’) isn’t even in the view when we query it

I so insert (’Fred’,’Islington’) into Drinkers I What if instead INSERT INTO coLocated VALUES(’Fred’,’Mad Hatter’)?

Database Inserting into views Management Peter Wood

SQL Updates SQL Update Commands I Since a view is virtual, any insertion must be to the SQL Views table(s) on which the view is defined. SQL Transactions I What if INSERT INTO coLocated VALUES(’Fred’,’Black Horse’)?

I if pub name is a key, we know the Black Horse is in Islington I therefore Fred must live in Islington I all we can do is insert (’Mad Hatter’,NULL) into Pubs and (’Fred’,NULL) into Drinkers I but now (’Fred’,’Mad Hatter’) isn’t even in the view when we query it

I What if instead INSERT INTO coLocated VALUES(’Fred’,’Mad Hatter’)?

Database Inserting into views Management Peter Wood

SQL Updates SQL Update Commands I Since a view is virtual, any insertion must be to the SQL Views table(s) on which the view is defined. SQL Transactions I What if INSERT INTO coLocated VALUES(’Fred’,’Black Horse’)?

I if pub name is a key, we know the Black Horse is in Islington I therefore Fred must live in Islington I so insert (’Fred’,’Islington’) into Drinkers I all we can do is insert (’Mad Hatter’,NULL) into Pubs and (’Fred’,NULL) into Drinkers I but now (’Fred’,’Mad Hatter’) isn’t even in the view when we query it

Database Inserting into views Management Peter Wood

SQL Updates SQL Update Commands I Since a view is virtual, any insertion must be to the SQL Views table(s) on which the view is defined. SQL Transactions I What if INSERT INTO coLocated VALUES(’Fred’,’Black Horse’)?

I if pub name is a key, we know the Black Horse is in Islington I therefore Fred must live in Islington I so insert (’Fred’,’Islington’) into Drinkers I What if instead INSERT INTO coLocated VALUES(’Fred’,’Mad Hatter’)? I but now (’Fred’,’Mad Hatter’) isn’t even in the view when we query it

Database Inserting into views Management Peter Wood

SQL Updates SQL Update Commands I Since a view is virtual, any insertion must be to the SQL Views table(s) on which the view is defined. SQL Transactions I What if INSERT INTO coLocated VALUES(’Fred’,’Black Horse’)?

I if pub name is a key, we know the Black Horse is in Islington I therefore Fred must live in Islington I so insert (’Fred’,’Islington’) into Drinkers I What if instead INSERT INTO coLocated VALUES(’Fred’,’Mad Hatter’)?

I all we can do is insert (’Mad Hatter’,NULL) into Pubs and (’Fred’,NULL) into Drinkers Database Inserting into views Management Peter Wood

SQL Updates SQL Update Commands I Since a view is virtual, any insertion must be to the SQL Views table(s) on which the view is defined. SQL Transactions I What if INSERT INTO coLocated VALUES(’Fred’,’Black Horse’)?

I if pub name is a key, we know the Black Horse is in Islington I therefore Fred must live in Islington I so insert (’Fred’,’Islington’) into Drinkers I What if instead INSERT INTO coLocated VALUES(’Fred’,’Mad Hatter’)?

I all we can do is insert (’Mad Hatter’,NULL) into Pubs and (’Fred’,NULL) into Drinkers I but now (’Fred’,’Mad Hatter’) isn’t even in the view when we query it Database Updatable views (SQL-92) Management Peter Wood

SQL Updates SQL Update Commands SQL Views SQL Transactions An SQL view is said to be updatable (inserts, updates or deletes can be applied) if the query defining the view satisfies the following:

I The from clause has only one database relation.

I The clause contains only attribute names of the relation (no expressions, aggregates, or distinct).

I Any attribute not listed in the select clause can be set to null.

I There is no or clause. Database Updatable views Management Peter Wood

SQL Updates SQL Update Commands SQL Views SQL Transactions I The previous definition is the SQL-92 definition.

I The SQL:1999 definition is much more complicated.

I Both SQL:1999 and MYSQL do allow some views involving joins to be updated.

I MySQL requires that there is a one-to-one correspondence between the rows in the view and those in the underlying tables.

I So our coLocated view would not be updatable because one person could be associated with many pubs in the view. Database SQL Transactions Management Peter Wood

SQL Updates SQL Update Commands SQL Views SQL Transactions I Assumptions up to now include

I only one user at a time queries or modifies the database I only single queries or updates are performed at a time I there are no hardware or software failures that might leave the database in an inconsistent state

I in reality, none of this is usually the case

I we need to be able to group database operations into transactions Database SQL Transactions Management Peter Wood

SQL Updates SQL Update Commands SQL Views SQL Transactions I When using a generic SQL interface (e.g., MySQL Workbench), each statement is its own transaction.

I However, in programs, we can group statements into a transaction.

I START TRANSACTION is used to mark the beginning of a transaction.

I COMMIT causes the transaction to end successfully. All changes to the database are made permanent.

I ROLLBACK cause the transaction to abort. All changes to the database are undone. Database Transaction properties Management Peter Wood

SQL Updates SQL Update Commands SQL Views SQL Transactions Transactions are designed to meet the “ACID” test:

I “A” stands for “atomicity” — transactions should execute completely or appear not to have run at all

I “C” stands for “consistency” — the constraints specified in the database must be preserved

I “I” stands for “isolation” — each transaction should appear to execute as if there are no others

I “D” stands for “durability” — once a transaction completes, it effect should never be lost Database Transaction example Management Consider a flight booking transaction on the relation Peter Wood SQL Updates SQL Update Commands Flights(FltNo, fltDate, seatNo, seatStatus) SQL Views SQL Transactions consisting of the query

SELECT seatNo FROM Flights WHERE fltNo=123 AND fltDate=’2010-12-25’ AND seatStatus=’available’;

which returns available seats from which the user selects seat 22A, and the following update

UPDATE Flights SET seatStatus=’occupied’ WHERE fltNo=123 AND fltDate=’2010-12-25’ AND seatNo=’22A’; User 2 finds seat 22A empty User 1 sets seat 22A occupied User 2 sets seat 22A occupied

Both customers believe they have booked seat 22A.

Database Interleaved execution Management Peter Wood

SQL Updates SQL Update Commands SQL Views Say two users are doing flight bookings simultaneously: SQL Transactions

User 1 finds seat 22A empty time ↓ User 1 sets seat 22A occupied User 2 sets seat 22A occupied

Both customers believe they have booked seat 22A.

Database Interleaved execution Management Peter Wood

SQL Updates SQL Update Commands SQL Views Say two users are doing flight bookings simultaneously: SQL Transactions

User 1 finds seat 22A empty time User 2 finds ↓ seat 22A empty User 2 sets seat 22A occupied

Both customers believe they have booked seat 22A.

Database Interleaved execution Management Peter Wood

SQL Updates SQL Update Commands SQL Views Say two users are doing flight bookings simultaneously: SQL Transactions

User 1 finds seat 22A empty time User 2 finds ↓ seat 22A empty User 1 sets seat 22A occupied Both customers believe they have booked seat 22A.

Database Interleaved execution Management Peter Wood

SQL Updates SQL Update Commands SQL Views Say two users are doing flight bookings simultaneously: SQL Transactions

User 1 finds seat 22A empty time User 2 finds ↓ seat 22A empty User 1 sets seat 22A occupied User 2 sets seat 22A occupied Database Interleaved execution Management Peter Wood

SQL Updates SQL Update Commands SQL Views Say two users are doing flight bookings simultaneously: SQL Transactions

User 1 finds seat 22A empty time User 2 finds ↓ seat 22A empty User 1 sets seat 22A occupied User 2 sets seat 22A occupied

Both customers believe they have booked seat 22A. Database Serializability Management Peter Wood

SQL Updates SQL Update Commands SQL Views The solution to the above problem is as follows: SQL Transactions

I Database operations can be grouped into a transaction

I The programmer can specify that the transaction must be serializable

I This means that transactions must behave as if they had been run serially — one after the other, with no overlap

I The two invocations of the flight booking operations could not book the same seat if run serially 1. Ensure there is at least £100 in account 123. 2. Add £100 to account 456: UPDATE Accounts SET balance = balance + 100 WHERE acctNo = 456; 3. Subtract £100 from account 123: UPDATE Accounts SET balance = balance - 100 WHERE acctNo = 123; What if there is a failure after Step (2)? We need the transaction to execute atomically — either all steps are executed or none are.

Database Atomicity Management Consider banking application on relation Peter Wood SQL Updates SQL Update Commands Accounts(acctNo, balance) SQL Views SQL Transactions transferring £100 from account 123 to account 456. 2. Add £100 to account 456: UPDATE Accounts SET balance = balance + 100 WHERE acctNo = 456; 3. Subtract £100 from account 123: UPDATE Accounts SET balance = balance - 100 WHERE acctNo = 123; What if there is a failure after Step (2)? We need the transaction to execute atomically — either all steps are executed or none are.

Database Atomicity Management Consider banking application on relation Peter Wood SQL Updates SQL Update Commands Accounts(acctNo, balance) SQL Views SQL Transactions transferring £100 from account 123 to account 456. 1. Ensure there is at least £100 in account 123. 3. Subtract £100 from account 123: UPDATE Accounts SET balance = balance - 100 WHERE acctNo = 123; What if there is a failure after Step (2)? We need the transaction to execute atomically — either all steps are executed or none are.

Database Atomicity Management Consider banking application on relation Peter Wood SQL Updates SQL Update Commands Accounts(acctNo, balance) SQL Views SQL Transactions transferring £100 from account 123 to account 456. 1. Ensure there is at least £100 in account 123. 2. Add £100 to account 456: UPDATE Accounts SET balance = balance + 100 WHERE acctNo = 456; What if there is a failure after Step (2)? We need the transaction to execute atomically — either all steps are executed or none are.

Database Atomicity Management Consider banking application on relation Peter Wood SQL Updates SQL Update Commands Accounts(acctNo, balance) SQL Views SQL Transactions transferring £100 from account 123 to account 456. 1. Ensure there is at least £100 in account 123. 2. Add £100 to account 456: UPDATE Accounts SET balance = balance + 100 WHERE acctNo = 456; 3. Subtract £100 from account 123: UPDATE Accounts SET balance = balance - 100 WHERE acctNo = 123; We need the transaction to execute atomically — either all steps are executed or none are.

Database Atomicity Management Consider banking application on relation Peter Wood SQL Updates SQL Update Commands Accounts(acctNo, balance) SQL Views SQL Transactions transferring £100 from account 123 to account 456. 1. Ensure there is at least £100 in account 123. 2. Add £100 to account 456: UPDATE Accounts SET balance = balance + 100 WHERE acctNo = 456; 3. Subtract £100 from account 123: UPDATE Accounts SET balance = balance - 100 WHERE acctNo = 123; What if there is a failure after Step (2)? Database Atomicity Management Consider banking application on relation Peter Wood SQL Updates SQL Update Commands Accounts(acctNo, balance) SQL Views SQL Transactions transferring £100 from account 123 to account 456. 1. Ensure there is at least £100 in account 123. 2. Add £100 to account 456: UPDATE Accounts SET balance = balance + 100 WHERE acctNo = 456; 3. Subtract £100 from account 123: UPDATE Accounts SET balance = balance - 100 WHERE acctNo = 123; What if there is a failure after Step (2)? We need the transaction to execute atomically — either all steps are executed or none are. Database Types of Transactions Management Peter Wood

SQL Updates SQL Update Commands SQL Views SQL Transactions I The transactions we have seen both read from and write to the database.

I SQL assumes that this is the default situation: SET TRANSACTION READ WRITE.

I But transactions that only read data cannot cause permanent harm to the database.

I This can be specified using SET TRANSACTION READ ONLY.

I Read-only transactions can be executed concurrently by the system. Database Dirty Reads Management Peter Wood

SQL Updates SQL Update Commands SQL Views SQL Transactions I Dirty data means data written by a transaction that has not yet committed.

I A dirty read is a read of dirty data written by another transaction.

I The risk is that the transaction that wrote the data may abort.

I This results in non-serializable behaviour.

I This may or may not be a problem for the reading transaction. Database Isolation Levels Management Peter Wood

SQL Updates SQL Update Commands SQL provides various isolation levels using SET SQL Views SQL Transactions TRANSACTION ISOLATION LEVEL . . .

I READ UNCOMMITTED: allowed to read dirty data.

I READ COMMITTED: not allowed to read dirty data (but can still issue the same query a number of times and get different answers).

I REPEATABLE READ: ensures that tuples read by a query don’t “disappear” if the query is repeated, but can still retrieve phantom tuples if insertions have been made.

I SERIALIZABLE: the default (and strongest).