Presentation is loading. Please wait.

Presentation is loading. Please wait.

SQL ACTION QUERIES AND TRANSACTION CONTROL CS 260 Database Systems.

Similar presentations


Presentation on theme: "SQL ACTION QUERIES AND TRANSACTION CONTROL CS 260 Database Systems."— Presentation transcript:

1 SQL ACTION QUERIES AND TRANSACTION CONTROL CS 260 Database Systems

2 Overview  Inserting data  Updating/deleting data  Surrogate keys  Transaction control

3 Inserting Data  SQL INSERT statements  Used to insert new data into a database table  Used when migrating existing data from another table  Typically, users will use applications with an interface that allows data to be easily added/migrated, but programmers often need to write the INSERT statements ultimately executed by those applications  Two approaches Insert a value for every field Insert values for specific fields

4 Inserting Data  Inserting a value for every field  Syntax  Example INSERT INTO VALUES (,, …); INSERT INTO candy_product VALUES (1, ‘Celestial Cashew Crunch’, 7.45, 10);

5 Inserting Data  Inserting a value for every field  Rules You must include a value for every field You must list the values in the correct order You can use DESCRIBE to find the correct order With this syntax, the DBMS is expecting data for every field in a specific order The data types must be consistent with the specified order Otherwise an error occurs DESCRIBE ;

6 Inserting Data  Inserting a value for specific fields  Syntax  Example INSERT INTO (,,…) VALUES (,, …); INSERT INTO candy_product (prod_desc, prod_id) VALUES (‘Celestial Cashew Crunch’, 1);

7 Inserting Data  Inserting a value for specific fields  Rules The field names can be specified in any order The corresponding values must be specified in the same order as the specified field names  If you are unsure of the values for all fields, use this syntax  Allows default column values to be used (if specified for the corresponding field in the table)

8 Inserting Data  Specifying values  Characters Enclose values in single quotes (just like in SELECT query search conditions) If a single quote should be present in the value, use two single quotes  Numbers Just specify the value (just like in SELECT query search conditions)

9 Inserting Data  Specifying foreign key values  You must insert the parent record first  Otherwise, insert them just like other value Primary key Foreign key Parent record Child record

10 Inserting Data  How many parent records must be inserted and/or present in other tables before a record can be inserted into the candy_purchase table? a. 0 b. 1 c. 2 d. 3 e. None of the above

11 Inserting Data  Inserting dates  Oracle and MySQL Specify dates as strings in the expected format  Oracle Use the TO_DATE function INSERT INTO ( ) VALUES (‘25-DEC-2014’); INSERT INTO ( ) VALUES (‘2014-12-25’); INSERT INTO ( ) VALUES (TO_DATE(‘2014-12-25 19:00:00’, ‘YYYY-MM-DD HH24:MI:SS’)); Format specifies the format of the date in the first argument Oracle MySQL

12 Inserting Data  Inserting dates  MySQL Remember that MySQL DATE types lack a time component Use the DATETIME type for dates with a time component Again, specify the date as a string in the expected format INSERT INTO ( ) VALUES (‘2014-12-25 19:00:00’);

13 Overview  Inserting data  Updating/deleting data  Surrogate keys  Transaction control

14 Updating Data  Syntax  Example UPDATE SET =, =, … = WHERE ; UPDATE candy_product SET prod_price = 10.5, prod_cost = 7.50 WHERE prod_id = 1;

15 Updating Data  Records can only be updated in one table at a time  Multiple records in the same table will be updated simultaneously if they match the search condition  When using Oracle SQL Developer or MySQL Workbench, if any part of the update fails, the entire update fails  Not necessarily the case in other tools (such as JDBC in Java applications)

16 Updating Data  Syntax  Example DELETE FROM WHERE ; DELETE FROM candy_purchase WHERE purch_id = 9;

17 Deleting Data  Records can only be deleted in one table at a time  Multiple records in the same table will be deleted simultaneously if they match the search condition  If the search condition is omitted, all records in the table will be deleted  A record cannot be deleted if one of its fields is referenced as a foreign key in another table  For tables with many records, it is quicker to drop the table and recreate it than it is to delete all of its records

18 Deleting Data  How many total records must be deleted in order to delete the “Nuts Not Nachos” record from the candy_product table? a. 1 b. 2 c. 3 d. 4

19 Deleting Data  CASCADE DELETE  Causes all child records to be automatically deleted when a record in a parent table is deleted  Option available in both Oracle and MySQL  Applied to the foreign key constraint Don’t use unless you’re absolutely sure that this behavior is desired Example is Oracle syntax, MySQL syntax is similar, but without “CONSTRAINT ” CREATE TABLE (, CONSTRAINT FOREIGN KEY (fk_field) REFERENCES ( ) ON DELETE CASCADE );

20 Overview  Inserting data  Updating/deleting data  Surrogate keys  Transaction control

21 Surrogate Keys  A surrogate key is a field created solely for the purpose of being a unique identifier in a database

22 Surrogate Keys  Their creation depends on the DBMS  Oracle Declare a NUMBER field as a primary key Create a “sequence” to automatically generate sequential numbers This sequence is independent of the table Default sequence minimum value is 1 Use the sequence when inserting new records  MySQL Declare an integer primary key field with the AUTO_INCREMENT modifier

23 Surrogate Keys  Oracle Example  Other modifiable properties INCREMENT BY: allows sequence values to increase by more than 1 MAXVALUE: specify a maximum sequence value CACHE: determine how many sequence values are allocated when the sequence is used (allows for faster access) CREATE TABLE candy_product( prod_id NUMBER(6) CONSTRAINT candy_product_id_pk PRIMARY KEY, prod_desc VARCHAR2(30), prod_cost NUMBER(4,2), prod_price NUMBER(4,2) ); CREATE SEQUENCE candy_product_seq MINVALUE 0;

24 Surrogate Keys  MySQL Example CREATE TABLE candy_product( prod_id INT(6) PRIMARY KEY AUTO_INCREMENT, prod_desc VARCHAR(30), prod_cost DECIMAL(4,2), prod_price DECIMAL(4,2) );

25 Surrogate Keys  Using surrogate keys in Oracle  Use the sequence’s NEXTVAL to obtain the next value  Use the sequence’s CURRVAL to obtain the current value CURRVAL is useful when inserting values for foreign keys that reference primary keys inserted immediately prior It will access the most recently generated surrogate key by that sequence in the current session INSERT INTO candy_purchase (purch_id, prod_id, cust_id) VALUES(purch_id_sequence.NEXTVAL, candy_customer_seq.CURRVAL, candy_product_seq.CURRVAL); INSERT INTO candy_product (prod_id) VALUES (candy_product_seq.NEXTVAL); INSERT INTO candy_customer (cust_id) VALUES (candy_customer_seq.NEXTVAL);

26 Surrogate Keys  Using surrogate keys in MySQL  Using the “inserting values for specific fields” approach  Using the “inserting values for all fields” approach  The AUTO_INCREMENT modifier will automatically generate and apply the surrogate key value for the corresponding record Use null or 0 if specifying a value for the AUTO_INCREMENT key INSERT INTO candy_customer(cust_name, cust_type, cust_addr) VALUES (‘Bobby Bon Bons’, ‘R’, ‘12 NichiCres.’); INSERT INTO candy_product VALUES (null, ‘Celestial Cashew Crunch’, 7.45, 10);

27 Surrogate Keys  Using surrogate keys in MySQL  Use the LAST_INSERT_ID() function to retrieve the most recently AUTO_INCREMENT generated surrogate key value for any table for the current session Assumptions purch_id is an AUTO_INCREMENT field and we want to recognize a new purchase A new customer and product were just inserted (previous slide) in that order using AUTO_INCREMENT (with ascending increments) We are confident that no customers have been inserted since Bobby Bon Bons (risky) Better to programmatically store the most recently added cust_id INSERT INTO candy_purchase (prod_id, cust_id) VALUES(LAST_INSERT_ID(), (SELECT MAX(cust_id) FROM candy_customer));

28 Surrogate Keys  Oracle sequence concerns  Sequences are not explicitly connected to a table Sequences can be referenced by multiple tables  If a sequence’s NEXTVAL is called and the value obtained is not inserted, then that value is lost  If multiple users access a sequence that has a CACHE value (must be at least 2), then those sequence values are reserved and may be lost if not used  If a surrogate key value is hardcoded in an insert statement instead of using the sequence, the sequence may later produce the same value

29 Surrogate Keys  MySQL AUTO_INCREMENT concerns  Limited to one column per table  Assigned to a specific table (cannot be used across tables as in Oracle)  If a surrogate key value is hardcoded in an insert statement instead of using the AUTO_INCREMENT, AUTO_INCREMENT will recognize it  If transactions are rolled back, gaps in AUTO_INCREMENT values may be present

30 Overview  Inserting data  Updating/deleting data  Surrogate keys  Transaction control

31 Transaction Control  A transaction is a logical unit of work that might involve multiple action queries  Examples Withdrawing money from one bank account and depositing it into a different account Booking a seat on an airplane  All of the action queries in a transaction must succeed or none of them should succeed Applies to INSERT, UPDATE, and DELETE statements, but not to SELECT statements (since they don’t modify the database)

32 Transaction Control  A transaction can be explicitly started using the START TRANSACTION command  All subsequent action queries will belong to the same transaction until the transaction is committed  A transaction can be explicitly committed using the COMMIT command  Use the ROLLBACK command to “undo” all action queries in the current transaction (since the last commit) COMMIT; START TRANSACTION; ROLLBACK;

33 Transaction Control  Oracle SQL Developer  By default, implicit transaction control is used The transaction starts when you connect to the database, and commits when you tell it to (either via the commit button or the COMMIT command) Database changes wouldn’t be visible to other users until they’re committed After a commit, the next command automatically starts a new transaction You should be prompted to commit any uncommitted transactions when quitting the application

34 Transaction Control  MySQL Workbench  No implicit transaction control  Example with auto commit off -- 1 -- INSERT INTO candy_product VALUES(null, 'test1', 1, 2); -- 2 -- SELECT * FROM candy_product; Connection 1Connection 2 -- 3 –- SELECT * FROM candy_product; -- prod_id 7 not shown -- not committed by Connection 1

35 Transaction Control  MySQL Workbench with auto commit off -- 1 -- INSERT INTO candy_product VALUES(null, 'test1', 1, 2); -- 2 –- SELECT * FROM candy_product; -- prod_id 7 is shown -- 4 -- COMMIT; Connection 1 -- 3 -- SELECT * FROM candy_product; -- prod_id 7 not shown -- 5 –- SELECT * FROM candy_product; -- prod_id 7 still not shown -- 6 -- COMMIT; -- 7 -- SELECT * FROM candy_product; -- prod_id 7 now shown Connection 2 This SELECT operation started a transaction and later SELECTs won't show changes until COMMIT from connection 1 AND connection2

36 Transaction Control  Oracle SQL Developer in same scenario -- 1 -- INSERT INTO candy_product VALUES(null, 'test1', 1, 2); -- 2 –- SELECT * FROM candy_product; -- prod_id 7 is shown -- 4 -- COMMIT; Connection 1 -- 3 -- SELECT * FROM candy_product; -- prod_id 7 not shown -- 5 –- SELECT * FROM candy_product; -- prod_id 7 is shown Connection 2 Not necessary to commit from connection 2 to see committed changes from connection 1

37 Transaction Control  Implications due to transactions  Before a transaction is committed, its actions are visible on your connection but not to others  When a transaction is committed, it cannot be rolled back, and its changes may be visible to other users  By default, most applications that interact with a database will auto commit transactions


Download ppt "SQL ACTION QUERIES AND TRANSACTION CONTROL CS 260 Database Systems."

Similar presentations


Ads by Google