SQL ACTION QUERIES AND TRANSACTION CONTROL CS 260 Database Systems.

Slides:



Advertisements
Similar presentations
Manipulating Data Schedule: Timing Topic 60 minutes Lecture
Advertisements

Multiple Table Queries 2: Outer Joins, Self Joins, Nested Queries, and Views CS 320.
Action Queries CS 320. Review: SQL Command Types  Data Definition Language (DDL)  Used to create and modify database objects  Data Manipulation Language.
Guide to Oracle10G1 Introduction To Forms Builder Chapter 5.
A Guide to SQL, Seventh Edition. Objectives Create a new table from an existing table Change data using the UPDATE command Add new data using the INSERT.
Fundamentals, Design, and Implementation, 9/e Chapter 11 Managing Databases with SQL Server 2000.
Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data
Dec 15, 2003Murali Mani Transactions and Security B term 2004: lecture 17.
A Guide to MySQL 7. 2 Objectives Understand, define, and drop views Recognize the benefits of using views Use a view to update data Grant and revoke users’
Creating Database Tables CS 320. Review: Levels of data models 1. Conceptual: describes WHAT data the system contains 2. Logical: describes HOW the database.
Chapter 5 Data Manipulation and Transaction Control Oracle 10g: SQL
Using SQL Queries to Insert, Update, Delete, and View Data © Abdou Illia MIS Spring 2015 Wednesday 1/28/2015 Chapter 3A.
Database Constraints. Database constraints are restrictions on the contents of the database or on database operations Database constraints provide a way.
MySql In Action Step by step method to create your own database.
© 2002 by Prentice Hall 1 David M. Kroenke Database Processing Eighth Edition Chapter 13 Managing Databases with SQL Server 2000.
Session 5: Working with MySQL iNET Academy Open Source Web Development.
Chapter 6 Additional Database Objects
Chapter 7 Working with Databases and MySQL PHP Programming with MySQL 2 nd Edition.
CS 3630 Database Design and Implementation. Your Oracle Account UserName is the same as your UWP username Followed Not case sensitive Initial.
15/10/20151 PHP & MySQL 'Slide materials are based on W3Schools PHP tutorial, 'PHP website 'MySQL website.
Introduction to MySQL Lab no. 10 Advance Database Management System.
CSC 2720 Building Web Applications Database and SQL.
Other database objects (Sequence). What Is a Sequence? A sequence: Automatically generates sequential numbers Is a sharable object Is typically used to.
Oracle Sequences Sequences are an independent object in the database (not a data type) Sequences have a name and can be used anywhere a value is expected.
Chapter 6 Additional Database Objects Oracle 10g: SQL.
Chapter 5 Sequences.
DAY 12: DATABASE CONCEPT Tazin Afrin September 26,
INTRODUCTION TO DATABASES CS 260 Database Systems.
Single-Table Queries 1: Basics CS 320 Online. Review: SQL Command Types  Data Definition Language (DDL)  Used to create and modify database objects.
1 Creating and Modifying Database Objects. 2 An Oracle database consists of multiple user accounts Each user account owns database objects Tables Views.
ADVANCED SQL SELECT QUERIES CS 260 Database Systems.
Creating PHPs to Insert, Update, and Delete Data CS 320.
Database structure and space Management. Database Structure An ORACLE database has both a physical and logical structure. By separating physical and logical.
ITBIS373 Database Development Lecture 3a - Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data.
1 CSE 2337 Introduction to Data Management Access Book – Ch 1.
Advanced SELECT Queries CS 146. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data Note the default formats… SELECT.
Introduction to Databases Queries CS 146. Sample Database: CANDY_CUSTOMER CANDY_PURCHASE CANDY_CUST_TYPE CANDY_PRODUCT.
Chapter 9 Constraints. Chapter Objectives  Explain the purpose of constraints in a table  Distinguish among PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK,
Oracle 11g: SQL Chapter 4 Constraints.
Database Lab Lecture 1. Database Languages Data definition language ( DDL ) Data definition language –defines data types and the relationships among them.
Chapter 4 Constraints Oracle 10g: SQL. Oracle 10g: SQL 2 Objectives Explain the purpose of constraints in a table Distinguish among PRIMARY KEY, FOREIGN.
SQL: Part 1 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram. Not for commercial.
Database Programming Sections 11 & 12 –Sequences, Indexes, and Synonymns.
Multiple Table Queries 1: Inner Joins CS 320. Introduction: Join Queries Usually queries combine data from multiple tables:  List how much (pounds) of.
3 Copyright © 2004, Oracle. All rights reserved. Working in the Forms Developer Environment.
IS 380 Introduction to SQL This lectures covers material from: database textbook chapter 3 Oracle chapter: 3,14,17.
1 Chapter 2: Creating and Modifying Database Objects.
Sql DDL queries CS 260 Database Systems.
Session 1 Module 1: Introduction to Data Integrity
Chapter 12 Additional Database Objects. Chapter Objectives  Define the purpose of a sequence and state how it can be used by an organization  Explain.
A Guide to SQL, Eighth Edition Chapter Six Updating Data.
Single-Table Queries 2: Advanced Topics CS 320. Review: Retrieving Data From a Single Table Syntax: Limitation: Retrieves "raw" data SELECT field1, field2,
Database: SQL, MySQL, LINQ and Java DB © by Pearson Education, Inc. All Rights Reserved.
Relational Database Management System(RDBMS) Structured Query Language(SQL)
SCALING AND PERFORMANCE CS 260 Database Systems. Overview  Increasing capacity  Database performance  Database indexes B+ Tree Index Bitmap Index 
Database Programming Sections 12 – Sequences, Indexes, and Synonymns.
Chapter 12Introduction to Oracle9i: SQL1 Chapter 12 Additional Database Objects.
A Guide to MySQL 6. 2 Objectives Create a new table from an existing table Change data using the UPDATE command Add new data using the INSERT command.
Join Queries CS 146. Introduction: Join Queries  So far, our SELECT queries have retrieved data from a single table  Usually queries combine data from.
Introduction to Databases Queries CS 146. Sample Database: CANDY_CUSTOMER CANDY_PURCHASE CANDY_CUST_TYPE CANDY_PRODUCT.
Oracle 11g: SQL Chapter 5 Data Manipulation and Transaction Control.
LEC-8 SQL. Indexes The CREATE INDEX statement is used to create indexes in tables. Indexes allow the database application to find data fast; without reading.
Data Integrity & Indexes / Session 1/ 1 of 37 Session 1 Module 1: Introduction to Data Integrity Module 2: Introduction to Indexes.
Manipulating Data Schedule: Timing Topic 40 minutes Lecture
ORACLE SQL Developer & SQLPLUS Statements
ISC440: Web Programming 2 Server-side Scripting PHP 3
Chapter 5 Sequences.
Manipulating Data.
Contents Preface I Introduction Lesson Objectives I-2
Chapter 11 Managing Databases with SQL Server 2000
Presentation transcript:

SQL ACTION QUERIES AND TRANSACTION CONTROL CS 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 VALUES (,, …); INSERT INTO candy_product VALUES (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 ;

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);

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 Primary key Foreign key Parent record Child record

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

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 (‘ ’); INSERT INTO ( ) VALUES (TO_DATE(‘ :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 format INSERT INTO ( ) VALUES (‘ :00:00’);

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

Updating Data  Syntax  Example UPDATE SET =, =, … = WHERE ; UPDATE candy_product SET prod_price = 10.5, prod_cost = 7.50 WHERE 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 WHERE ; DELETE FROM candy_purchase WHERE 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. 1 b. 2 c. 3 d. 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 ” CREATE TABLE (, CONSTRAINT FOREIGN KEY (fk_field) REFERENCES ( ) 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 database

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_product VALUES (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 INSERT INTO candy_product VALUES(null, 'test1', 1, 2); SELECT * FROM candy_product; Connection 1Connection –- SELECT * FROM candy_product; -- prod_id 7 not shown -- not committed by Connection 1

Transaction Control  MySQL Workbench with auto commit off INSERT INTO candy_product VALUES(null, 'test1', 1, 2); -- 2 –- SELECT * FROM candy_product; -- prod_id 7 is shown COMMIT; Connection SELECT * FROM candy_product; -- prod_id 7 not shown -- 5 –- SELECT * FROM candy_product; -- prod_id 7 still not shown COMMIT; 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 INSERT INTO candy_product VALUES(null, 'test1', 1, 2); -- 2 –- SELECT * FROM candy_product; -- prod_id 7 is shown COMMIT; Connection 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