CS122 Using Relational Databases and SQL 10/22/17 10/16/17 CS122 Using Relational Databases and SQL 8. Data Manipulation and Definition Randy Moss Department of Computer Science California State University, Los Angeles 1
Outline Data manipulation Data definition INSERT DELETE UPDATE 10/22/17 10/16/17 Outline Data manipulation INSERT DELETE UPDATE Data definition CREATE a table MODIFY a table DELETE a table 8. Data Manipulation & Definition CS122_W2014 8-2 2
Insert Adds new records to a table Two general forms of the syntax 10/22/17 Insert Adds new records to a table Two general forms of the syntax One adds a single new record using specific values The other is for inserting one or more records using the results of a query Two parts to statement First part lists table and the fields that will receive the data Second part specifies values to be inserted into the table
Insert one record Two general forms of the syntax 10/22/17 10/16/17 Insert one record Two general forms of the syntax INSERT INTO table VALUES ( value1, value2, … ) INSERT INTO table (field [, …] ) VALUES ( value [, …] ); Make sure the order of the values matches the order of the field 8. Data Manipulation & Definition CS122_W2014 8-4 4
Example 1 Add 'Hip-Hop' as a new genre in the Genre table 10/22/17 10/16/17 Example 1 Add 'Hip-Hop' as a new genre in the Genre table INSERT INTO Genre VALUES ('hip-hop') INSERT INTO Genre (genre) 8. Data Manipulation & Definition CS122_W2014 8-5 5
10/22/17 10/16/17 Example 2 Add new title as TitleID 8 recorded by Word (ArtistID 3) called 'Word Live', recorded in StudioID 2 in the genre 'pop‘. Insert into Titles Values(8,3,'Word Live',2, ' ','pop') Insert into Titles(TitleID,ArtistID,Title,StudioID,Upc,Genre) Values(8,3,'Word Live',2, ' ','pop') The upc of the new record is ‘ ‘ Commas separating fields 8. Data Manipulation & Definition CS122_W2014 8-6 6
The upc of the new record is NULL 10/22/17 10/16/17 Example 2 (Cont.) Insert into Titles Values(8,3,'Word Live',2, NULL ,'pop') The upc of the new record is NULL Insert into Titles(TitleID,ArtistID,Title,StudioID,Genre) Values(8,3,'Word Live',2,'pop') 8. Data Manipulation & Definition CS122_W2014 8-7 7
Insert Rules Must supply values to all fields except: 10/22/17 10/16/17 Insert Rules Must supply values to all fields except: Those that can have null values Those that auto-generate Those with default values To explicitly insert a Null value, use the word Null without quotes Cannot use two commas together with nothing between them 8. Data Manipulation & Definition CS122_W2014 8-8 8
INSERT using a query Two general forms of the syntax 10/22/17 10/16/17 INSERT using a query Two general forms of the syntax INSERT INTO table select_query; INSERT INTO table ( field [, …] ) select_query Can insert multiple records Follow field list with valid SQL SELECT that produces data for field list 8. Data Manipulation & Definition CS122_W2014 8-9 9
10/22/17 10/16/17 Example 1 Populate the AudioFiles table with all the MP3s from the Tracks table Insert into Audiofiles(TitleID, Tracknum, AudioFormat) Select TitleID, Tracknum, 'mp3' From Tracks Where MP3 = 1 8. Data Manipulation & Definition CS122_W2014 8-10 10
10/22/17 10/16/17 Example 2 Add a new salesperson as SalesID 6, named ‘Courtney Mulligan’ with initials of ‘cgm’, a base salary of 200, and supervised by ‘Bob Bentley’ INSERT INTO SalesPeople (SalesID, Firstname, Lastname, Initials, Base, Supervisor) SELECT 6, 'Courtney','Mulligan','cgm',200, SalesID FROM SalesPeople WHERE Firstname = 'Bob' And Lastname='Bentley' 8. Data Manipulation & Definition CS122_W2014 8-11 11
Comments Just follow the field list with a SELECT statement. 10/22/17 10/16/17 Comments Just follow the field list with a SELECT statement. The SELECT clause must produce the same number of columns In the same order With the same datatype If the field list is omitted, select all the fields of the table 8. Data Manipulation & Definition CS122_W2014 8-12 12
DELETE Syntax DELETE FROM table WHERE condition(s); 10/22/17 10/16/17 DELETE Syntax DELETE FROM table WHERE condition(s); Delete one or more rows 8. Data Manipulation & Definition CS122_W2014 8-13 13
Generally delete on primary key 10/22/17 10/16/17 Example 1 Delete the salesperson with SalesID 6. Delete From SalesPeople Where SalesID=6 Generally delete on primary key 8. Data Manipulation & Definition CS122_W2014 8-14 14
Cannot use Join in delete 10/22/17 10/16/17 Example 2 Delete all records in the Audiofiles table related to the CD ‘Time Flies’ Delete From Audiofiles Where TitleID IN (Select TitleID From Titles Where Title='Time Flies') Cannot use Join in delete 8. Data Manipulation & Definition CS122_W2014 8-15 15
Update 10/22/17 Syntax in simplest form is to specify the table to be updated followed by SET and field=value If setting multiple values, use SET only once and separate each field=value pair with a comma The value that you set the field(s) to can be: A specific value The old value with new information added The result of a mathematical calculation Value from another field Use WHERE clause to specify which records to change
UPDATE (Single table) Syntax UPDATE table 10/22/17 10/16/17 UPDATE (Single table) Syntax UPDATE table SET field1=value1, field2=value2 WHERE condition(s); 8. Data Manipulation & Definition CS122_W2014 8-17 17
Example 1 Give salesperson Bob Bentley a $50 raise in Base 10/22/17 10/16/17 Example 1 Give salesperson Bob Bentley a $50 raise in Base Update SalesPeople Set Base=Base+50 Where Firstname='Bob' And Lastname = 'Bentley' 8. Data Manipulation & Definition CS122_W2014 8-18 18
10/22/17 10/16/17 Example 2 Member Frank Payne works from his home. Set his workphone number to the value of his homephone number. Update Members Set Workphone=Homephone Where Firstname='Frank' And Lastname='Payne' 8. Data Manipulation & Definition CS122_W2014 8-19 19
10/22/17 10/16/17 Example 3 Change the record for the title ‘Time Flies’ to set the UPC to 1828344222 and the Genre to 'pop‘ Update Titles Set UPC='1828344222', Genre='pop' Where Title='Time Flies' 8. Data Manipulation & Definition CS122_W2014 8-20 20
UPDATE (Multiple table) 10/22/17 10/16/17 UPDATE (Multiple table) Update Table1, Table2 Set Field = Value, field = value Where Table1.field=Table2.field AND Condition 8. Data Manipulation & Definition CS122_W2014 8-21 21
10/22/17 10/16/17 Example 1 All the members of the group Confused now have e- mail addresses that are the member's firstname followed by an @confused.com. Update the members. Update Members M, XrefArtistsMembers X, Artists A Set Email = Concat(M.firstname ,' @confused.com') Where M.MemberID = X.MemberID AND A.ArtistID = X.ArtistID AND Artistname = 'Confused' 8. Data Manipulation & Definition CS122_W2014 8-22 22
10/22/17 10/16/17 Example 2 All members in Virginia who have previously been handled by Scott Bull will now be handled by Clint Sanchez, whose salesID is 3. Update Members M, SalesPeople S Set M.SalesID=1 Where M.SalesID=S.SalesID AND Region='VA' AND S.Firstname='Clint' AND S.Lastname='Sanchez' 8. Data Manipulation & Definition CS122_W2014 8-23 23
Transactions Suppose you want to add a new CD title and its tracks 10/22/17 Transactions Suppose you want to add a new CD title and its tracks Need to insert a record to titles Need to insert multiple records to tracks What if we did part of those inserts and not all of them? Result would be an incomplete data Transactions let you group individual commands and require that they are all completed or not completed as a group 8. Data Manipulation & Definition CS122_W2014 8-24
Formal Definition of Transaction 10/22/17 Formal Definition of Transaction A logical unit of work made up of a series of statements: Selects, inserts, updates, or deletes No errors = ALL modifications are accepted Errors = NO modifications are accepted 8. Data Manipulation & Definition CS122_W2014 8-25
ACID Properties of Transactions 10/22/17 ACID Properties of Transactions Atomicity Consistency Isolation Durability 8. Data Manipulation & Definition CS122_W2014 8-26
10/22/17 ACID continued Atomicity guarantees that a transaction must either be completely done, or not at all. Consistency: The details and totals match No orphan data exists Isolation means that no other user sees any part of the transaction until it is all completed Durability says that when the transaction is finished, the data will persist and be saved. 8. Data Manipulation & Definition CS122_W2014 8-27
ACID example Bank Transaction: 10/22/17 ACID example Bank Transaction: Atomicity: if you cancel your transaction in the middle of doing it, it will be fully cancelled Consistency: Depositing to two accounts should subtract from main account twice, not once. Isolation: Bank transactions should happen one after the other to avoid consistency issue above. Durability: My money stays in my account after I leave. 8. Data Manipulation & Definition CS122_W2014 8-28
Transaction Syntax BEGIN TRANSACTION; 10/22/17 Transaction Syntax BEGIN TRANSACTION; DELETE FROM Tracks WHERE TitleID = 44; DELETE FROM Titles WHERE TitleID = 44; COMMIT; #Or rollback if there are any errors 8. Data Manipulation & Definition CS122_W2014 8-29
Concurrency Issues Dirty reads (Uncommitted dependency) 10/22/17 Concurrency Issues Dirty reads (Uncommitted dependency) One user reads a record that is part of another user's incomplete transaction Unrepeatable reads (Inconsistent Analysis) A record is read twice during a transaction, and the second read is affected by a separate transaction 8. Data Manipulation & Definition CS122_W2014 8-30
Concurrency Issues Continued 10/22/17 Concurrency Issues Continued Phantoms One user may be updating all the records in a table at the same time another user is inserting a new record to the table Lost updates Two transaction try to update the same record 8. Data Manipulation & Definition CS122_W2014 8-31
Locks to the Rescue! Automatic locking by database Record locking 10/22/17 Locks to the Rescue! Automatic locking by database Record locking Page locking Table locking 8. Data Manipulation & Definition CS122_W2014 8-32
Even Locks Have Problems… 10/22/17 Even Locks Have Problems… Deadlock: Two transactions each waiting for each other to complete 8. Data Manipulation & Definition CS122_W2014 8-33
Preventing Deadlocks Always update table in the same order 10/22/17 Preventing Deadlocks Always update table in the same order Keep transactions as short as possible Do not place user interaction in the middle of transaction 8. Data Manipulation & Definition CS122_W2014 8-34