1 / 48

Data Manipulation Language (DML) and Transaction Control

Data Manipulation Language (DML) and Transaction Control. Database Management Systems 1. Objectives. Define terms Describe each data manipulation language (DML) statement Insert, update, and delete data Write single table queries using SQL SELECT command

hhavel
Download Presentation

Data Manipulation Language (DML) and Transaction Control

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Data Manipulation Language (DML) and Transaction Control Database Management Systems 1

  2. Objectives • Define terms • Describe each data manipulation language (DML) statement • Insert, update, and delete data • Write single table queries using SQL SELECT command • Understand the function of transaction control statements

  3. Data Manipulation Language • A DML statement is executed when you: • Add new rows to a table • Modify existing rows in a table • Remove existing rows from a table • A transaction consists of a collection of DML statements that form a logical unit of work.

  4. Adding a New Row to a Table New row DEPARTMENTS Insert new rowinto theDEPARTMENTStable.

  5. INSERT Statement Syntax • Add new rows to a table by using the INSERT statement: • With this syntax, only one row is inserted at a time. INSERT INTO table [(column [, column...])] VALUES (value [, value...]);

  6. Insert Statement • Adds one or more rows to a table • Inserting into a table • Inserting a record that has some null attributes requires identifying the fields that actually get data • Inserting from another table

  7. Creating Tables with Identity Columns Introduced with SQL:2008 • Inserting into a table does not require explicit customer ID entry or field list • INSERT INTO CUSTOMER_T VALUES ( ‘Contemporary Casuals’, ‘1355 S. Himes Blvd.’, ‘Gainesville’, ‘FL’, 32601);

  8. Creating a Script • Use & substitution in a SQL statement to prompt for values. • & is a placeholder for the variable value. INSERT INTO departments (department_id, department_name, location_id) VALUES (&department_id, '&department_name',&location);

  9. Changing Data in a Table EMPLOYEES Update rows in the EMPLOYEES table:

  10. UPDATE Statement Syntax • Modify existing values in a table with the UPDATE statement: • Update more than one row at a time (if required). UPDATE table SET column = value [, column = value, ...] [WHERE condition];

  11. Update Statement • Modifies data in existing rows

  12. Removing a Row from a Table DEPARTMENTS Delete a row from the DEPARTMENTS table:

  13. DELETE Statement • You can remove existing rows from a table by using the DELETE statement: DELETE [FROM] table [WHERE condition];

  14. Delete Statement • Removes rows from a table • Delete certain rows • DELETE FROM CUSTOMER_T WHERE CUSTOMERSTATE = ‘HI’; • Delete all rows • DELETE FROM CUSTOMER_T;

  15. Merge Statement Makes it easier to update a table…allows combination of Insert and Update in one statement Useful for updating master tables with new data

  16. Database Transactions • A database transaction consists of one of the following: • DML statements that constitute one consistent change to the data • One DDL statement • One data control language (DCL) statement

  17. Explicit Transaction Control Statements Time COMMIT Transaction DELETE SAVEPOINTA INSERT UPDATE SAVEPOINTB INSERT ROLLBACK to SAVEPOINT B ROLLBACK to SAVEPOINT A ROLLBACK

  18. Rolling Back Changes to a Marker • Create a marker in the current transaction by using the SAVEPOINT statement. • Roll back to that marker by using the ROLLBACKTOSAVEPOINT statement. UPDATE... SAVEPOINT update_done; INSERT... ROLLBACK TO update_done;

  19. Committing Data • Make the changes: • Commit the changes: DELETE FROM employees WHERE employee_id = 99999; INSERT INTO departments VALUES (290, 'Corporate Tax', NULL, 1700); COMMIT;

  20. State of the Data After ROLLBACK • Discard all pending changes by using the ROLLBACK statement: • Data changes are undone. • Previous state of the data is restored. • Locks on the affected rows are released. DELETE FROM copy_emp; ROLLBACK ;

  21. State of the Data After ROLLBACK: Example DELETE FROM test; 25,000 rows deleted. ROLLBACK; Rollback complete. DELETE FROM test WHERE id = 100; 1 row deleted. SELECT * FROM test WHERE id = 100; No rows selected. COMMIT; Commit complete.

  22. Read Consistency • Read consistency guarantees a consistent view of the data at all times. • Changes made by one user do not conflict with the changes made by another user. • Read consistency ensures that, on the same data: • Readers do not wait for writers • Writers do not wait for readers • Writers wait for writers

  23. Implementing Read Consistency User A Datablocks UPDATE employeesSET salary = 7000 WHERE last_name = 'Grant'; Undosegments Changedandunchanged data SELECT *FROM userA.employees; Read-consistentimage Before change(“old” data) User B

  24. FORUPDATE Clause in a SELECT Statement • Locks the rows in the EMPLOYEES table where job_id is SA_REP. • Lock is released only when you issue a ROLLBACK or a COMMIT. • If the SELECT statement attempts to lock a row that is locked by another user, then the database waits until the row is available, and then returns the results of the SELECT statement. SELECT employee_id, salary, commission_pct, job_id FROM employees WHERE job_id = 'SA_REP' FOR UPDATE ORDER BY employee_id;

  25. FORUPDATE Clause: Examples • You can use the FORUPDATE clause in a SELECT statement against multiple tables. • Rows from both the EMPLOYEES and DEPARTMENTS tables are locked. • Use FORUPDATEOFcolumn_name to qualify the column you intend to change, then only the rows from that specific table are locked. SELECT e.employee_id, e.salary, e.commission_pct FROM employees e JOIN departments d USING (department_id) WHERE job_id = 'ST_CLERK‘ AND location_id = 1500 FOR UPDATE ORDER BY e.employee_id;

  26. Capabilities of SQL SELECT Statements Projection Selection Table 1 Table 1 Join Table 2 Table 1

  27. SELECT Statement • Used for queries on single or multiple tables • Clauses of the SELECT statement: • SELECT • List the columns (and expressions) to be returned from the query • FROM • Indicate the table(s) or view(s) from which data will be obtained • WHERE • Indicate the conditions under which a row will be included in the result • GROUP BY • Indicate categorization of results • HAVING • Indicate the conditions under which a category (group) will be included • ORDER BY • Sorts the result according to specified criteria

  28. SELECT Statement Syntax SELECT column, group_function FROM table [WHERE condition] [GROUP BY group_by_expression] [HAVING group_condition] [ORDER BY column];

  29. Figure 6-10 • SQL statement processing order (based on van der Lans, 2006 p.100) 29

  30. SELECT Example • Find products with standard price less than $275 Table 6-3: Comparison Operators in SQL

  31. SELECT Example Using Alias • Alias is an alternative column or table name SELECT CUST.CUSTOMERNAME AS NAME, CUST.CUSTOMERADDRESS FROM CUSTOMER_V CUST WHERE NAME = ‘Home Furnishings’;

  32. SELECT Example Using a Function • Using the COUNT aggregate function to find totals SELECT COUNT(*) FROM ORDERLINE_T WHERE ORDERID = 1004; Note: With aggregate functions you can’t have single-valued columns included in the SELECT clause, unless they are included in the GROUP BY clause.

  33. SELECT Example–Boolean Operators • AND, OR, and NOT Operators for customizing conditions in WHERE clause Note: The LIKE operator allows you to compare strings using wildcards. For example, the % wildcard in ‘%Desk’ indicates that all strings that have any number of characters preceding the word “Desk” will be allowed.

  34. Figure 6-8 Boolean query A without use of parentheses By default, processing order of Boolean operators is NOT, then AND, then OR

  35. SELECT Example–Boolean Operators • With parentheses…these override the normal precedence of Boolean operators With parentheses, you can override normal precedence rules. In this case parentheses make the OR take place before the AND.

  36. Figure 6-9 Boolean query B with use of parentheses

  37. Sorting Results with ORDER BY Clause • Sort the results first by STATE, and within a state by the CUSTOMER NAME Note: The IN operator in this example allows you to include rows whose CustomerState value is either FL, TX, CA, or HI. It is more efficient than separate OR conditions.

  38. Categorizing Results Using GROUP BY Clause • For use with aggregate functions • Scalar aggregate: single value returned from SQL query with aggregate function • Vector aggregate: multiple values returned from SQL query with aggregate function (via GROUP BY) • You can use single-value fields with aggregate functions if they are included in the GROUP BY clause

  39. Qualifying Results by Categories Using the HAVING Clause • For use with GROUP BY • Like a WHERE clause, but it operates on groups (categories), not on individual rows. Here, only those groups with total numbers greater than 1 will be included in final result.

  40. What Is a View? EMPLOYEES table

  41. Simple Views and Complex Views Feature Simple Views Complex Views Number of tables One One or more Contain functions No Yes Contain groups of data No Yes DML operations through a view Yes Not always

  42. Using and Defining Views • Views provide users controlled access to tables • Base Table–table containing the raw data • Dynamic View • A “virtual table” created dynamically upon request by a user • No data actually stored; instead data from base table made available to user • Based on SQL SELECT statement on base tables or other views • Materialized View • Copy or replication of data • Data actually stored • Must be refreshed periodically to match corresponding base tables

  43. Creating a View • You embed a subquery in the CREATEVIEW statement: • The subquery can contain complex SELECT syntax. CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view [(alias[, alias]...)] AS subquery [WITH CHECK OPTION [CONSTRAINT constraint]] [WITH READ ONLY [CONSTRAINT constraint]];

  44. Sample CREATE VIEW • View has a name. • View is based on a SELECT statement. • CHECK_OPTION works only for updateable views and prevents updates that would create rows not included in the view.

  45. Advantages of Views • Simplify query commands • Assist with data security (but don't rely on views for security, there are more important security measures) • Enhance programming productivity • Contain most current base table data • Use little storage space • Provide customized view for user • Establish physical data independence

  46. Disadvantages of Views • Use processing time each time view is referenced • May or may not be directly updateable

  47. Summary • In this lesson, you should have learned how to use the following statements: Function Description INSERT Adds a new row to the table UPDATE Modifies existing rows in the table DELETE Removes existing rows from the table MERGE Combines of Insert and Update in one statement COMMIT Makes all pending changes permanent SAVEPOINT Is used to roll back to the savepoint marker ROLLBACK Discards all pending data changes FORUPDATE clause in SELECT Locks rows identified by the SELECT query

  48. References • Hoffer, J., Ramesh, V., Topi, H. (2013). Modern Database Management 11th Edition, Prentice Hall. • Singh, P., Pottle, B. (2009). Oracle Database 11g: SQL Fundamentals I, Oracle.

More Related