Upload
myron-powers
View
223
Download
0
Embed Size (px)
Citation preview
SQL ACTION QUERIES AND TRANSACTION CONTROLCS 260
Database Systems
Overview
Inserting data Updating/deleting data Surrogate keys Transaction control
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
Inserting Data
Inserting a value for every field Syntax
Example
INSERT INTO <table_name>VALUES (<value1>, <value2>, …);
INSERT INTO candy_productVALUES (1, ‘Celestial Cashew Crunch’, 7.45, 10);
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 <table_name>;
Inserting Data
Inserting a value for specific fields Syntax
Example
INSERT INTO <table_name> (<field1>, <field2>,…)VALUES (<value1>, <value2>, …);
INSERT INTO candy_product (prod_desc, prod_id)VALUES (‘Celestial Cashew Crunch’, 1);
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)
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)
Inserting Data
Specifying foreign key values You must insert the parent record first Otherwise, insert them just like other value
CUST_ID CUST_NAME CUST_TYPE_ID CUST_ADDR CUST_ZIP CUST_PHONE
1 Jones, Joe P 1234 Main St. 91212 434-1231
2 Armstrong,Inc. R 231 Globe Blvd. 91212 434-7664
3 Sw edish Burgers R 1889 20th N.E. 91213 434-9090
4 Pickled Pickles R 194 CityView 91289 324-8909
5 The Candy Kid W 2121 Main St. 91212 563-4545
6 Waterman, Al P 23 Yankee Blvd. 91234
7 Bobby Bon Bons R 12 Nichi Cres. 91212 434-9045
8 Crow sh, Elias P 7 77th Ave. 91211 434-0007
9 Montag, Susie P 981 Montview 91213 456-2091
10 Columberg Sw eets W 239 East Falls 91209 874-9092
PURCH_ID PROD_ID CUST_ID PURCH_DATEDELIVERY_DATEPOUNDS
1 1 5 28-Oct-04 28-Oct-04 3.5
2 2 6 28-Oct-04 30-Oct-04 15
3 1 9 28-Oct-04 28-Oct-04 2
4 3 9 28-Oct-04 28-Oct-04 3.7
5 3 2 28-Oct-04 2-Nov-04 3.7
6 1 7 29-Oct-04 29-Oct-04 3.7
7 2 7 29-Oct-04 29-Oct-04 1.2
8 3 7 29-Oct-04 29-Oct-04 4.4
9 2 6 29-Oct-04 30-Oct-04 3
10 2 10 29-Oct-04 31-Oct-04 14
11 5 10 29-Oct-04 2-Nov-04 4.8
12 1 4 29-Oct-04 29-Oct-04 1
13 5 4 29-Oct-04 30-Oct-04 7.6
14 5 3 29-Oct-04 29-Oct-04 3.5
Primary key Foreign key
Parentrecord
Childrecord
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. 0b. 1c. 2d. 3e. None of the above
Inserting Data
Inserting dates Oracle and MySQL
Specify dates as strings in the expected format
Oracle Use the TO_DATE function
INSERT INTO <table_name> (<date_field>)VALUES (‘25-DEC-2014’);
INSERT INTO <table_name> (<date_field>)VALUES (‘2014-12-25’);
INSERT INTO <table_name> (<date_field>)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
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 formatINSERT INTO <table_name> (<date_field>)VALUES (‘2014-12-25 19:00:00’);
Overview
Inserting data Updating/deleting data Surrogate keys Transaction control
Updating Data
Syntax
Example
UPDATE <table_name>SET <field1> = <new_value>, <field2> = <new_value>, … <fieldN> = <new_value>WHERE <search_condition>;
UPDATE candy_productSET prod_price = 10.5, prod_cost = 7.50WHERE prod_id = 1;
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)
Updating Data
Syntax
Example
DELETE FROM <table_name>WHERE <search_condition>;
DELETE FROM candy_purchaseWHERE purch_id = 9;
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
Deleting Data
How many total records must be deleted in order to delete the “Nuts Not Nachos” record from the candy_product table?
a. 1b. 2c. 3d. 4
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 <constraint_name>”
CREATE TABLE <table_name> ( <fk_field> <data_type>, CONSTRAINT <constraint_name> FOREIGN KEY (fk_field) REFERENCES <parent_table> (<parent_table_pk_field>) ON DELETE CASCADE);
Overview
Inserting data Updating/deleting data Surrogate keys Transaction control
Surrogate Keys
A surrogate key is a field created solely for the purpose of being a unique identifier in a databaseCUST_ID CUST_NAME CUST_TYPE_ID CUST_ADDR CUST_ZIP CUST_PHONE
1 Jones, Joe P 1234 Main St. 91212 434-1231
2 Armstrong,Inc. R 231 Globe Blvd. 91212 434-7664
3 Sw edish Burgers R 1889 20th N.E. 91213 434-9090
4 Pickled Pickles R 194 CityView 91289 324-8909
5 The Candy Kid W 2121 Main St. 91212 563-4545
6 Waterman, Al P 23 Yankee Blvd. 91234
7 Bobby Bon Bons R 12 Nichi Cres. 91212 434-9045
8 Crow sh, Elias P 7 77th Ave. 91211 434-0007
9 Montag, Susie P 981 Montview 91213 456-2091
10 Columberg Sw eets W 239 East Falls 91209 874-9092
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
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;
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));
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);
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_productVALUES (null, ‘Celestial Cashew Crunch’, 7.45, 10);
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));
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
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
Overview
Inserting data Updating/deleting data Surrogate keys Transaction control
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)
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;
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
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 1
Connection 2
-- 3 –-SELECT * FROM candy_product;-- prod_id 7 not shown-- not committed by Connection 1
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
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
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