1 / 51

Enhanced Guide to Oracle 10g

Enhanced Guide to Oracle 10g. Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data. Manipulating Data. Objectives. After completing this lesson, you should be able to do the following: Describe each DML statement Insert rows into a table Update rows in a table

Download Presentation

Enhanced Guide to Oracle 10g

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. Enhanced Guide to Oracle 10g Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data

  2. Manipulating Data

  3. Objectives • After completing this lesson, you should be able to do the following: • Describe each DML statement • Insert rows into a table • Update rows in a table • Delete rows from a table • Control transactions

  4. SQL Scripts • Script: text file that contains a sequence of SQL commands • Usually have .sql extension • To run from SQL*Plus: • Start full file path SQL> START path_to_script_file; • @ full file path (SQL> @ path_to_script_file;) • Extension can be omitted if it is .sql • Path cannot contain any blank spaces

  5. 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.

  6. Transactions • Transaction: series of action queries that represent a logical unit of work • consisting of one or more SQL DML commands • INSERT, UPDATE, DELETE • All transaction commands must succeed or none can succeed • User can commit (save) changes • User can roll back (discard) changes • Pending transaction: a transaction waiting to be committed or rolled back • Oracle DBMS locks records associated with pending transactions • Other users cannot view or modify locked records

  7. 50 DEVELOPMENT DETROIT New row “…insert a new row into DEPT table…” 50 DEVELOPMENT DETROIT Adding a New Row to a Table DEPT DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON DEPT DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON

  8. The INSERT Statement • Add new rows to a table by using the INSERT statement. • Only one row is inserted at a time with this syntax. INSERT INTO table [(column [, column...])] VALUES (value [, value...]);

  9. Inserting New Rows • Insert a new row containing values for each column. • List values in the default order of the columns in the table. • Optionally list the columns in the INSERT clause. • Enclose character and date values within single quotation marks. SQL> INSERT INTO dept (deptno, dname, loc) 2 VALUES (50, 'DEVELOPMENT', 'DETROIT'); 1 row created.

  10. Inserting Rows with Null Values • Implicit method: Omit the column from the column list. SQL> INSERT INTO dept (deptno, dname ) 2 VALUES (60, 'MIS'); 1 row created. • Explicit method: Specify the NULL keyword. SQL> INSERT INTO dept 2 VALUES (70, 'FINANCE', NULL); 1 row created.

  11. Inserting Special Values • The SYSDATE function records the current date and time. SQL> INSERT INTO emp (empno, ename, job, 2 mgr, hiredate, sal, comm, 3 deptno) 4 VALUES (7196, 'GREEN', 'SALESMAN', 5 7782, SYSDATE, 2000, NULL, 6 10); 1 row created.

  12. Format Masks • All data is stored in the database in a standard binary format • Format masks are alphanumeric text strings that specify the format of input and output data • Table 3-1: Number format masks • Table 3-2: Date format masks

  13. Inserting Date Values • Date values must be converted from characters to dates using the TO_DATE function and a format mask • Example:

  14. Inserting Text Data • Must be enclosed in single quotes • Is case-sensitive • To insert a string with a single quote, type the single quote twice • Example: 'Mike''s Motorcycle Shop'

  15. Inserting Interval Values • Year To Month Interval: TO_YMINTERVAL(‘years-months’) e.g. TO_YMINTERVAL(‘3-2’) • Day To Second Interval: TO_DSINTERVAL(‘days HH:MI:SS.99’) e.g. TO_DSINTERVAL(‘-0 01:15:00’)

  16. Inserting LOB Column Locators • Oracle stores LOB data in separate physical location from other types of data • LOB locator • Structure containing information that identifies LOB data type • Points to alternate memory location • Create blob locator • EMPTY_BLOB()

  17. Inserting Specific Date Values • Add a new employee. SQL> INSERT INTO emp 2 VALUES (2296,'AROMANO','SALESMAN',7782, 3 TO_DATE('FEB 3, 1997', 'MON DD, YYYY'), 4 1300, NULL, 10); 1 row created. • Verify your addition. EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO ----- ------- -------- ---- --------- ---- ---- ------ 2296 AROMANO SALESMAN 7782 03-FEB-97 1300 10

  18. “…update a row in EMP table…” 20 Changing Data in a Table EMP EMPNO ENAME JOB ... DEPTNO 7839 KING PRESIDENT 10 7698 BLAKE MANAGER 30 7782 CLARK MANAGER 10 7566 JONES MANAGER 20 ... EMP EMPNO ENAME JOB ... DEPTNO 7839 KING PRESIDENT 10 7698 BLAKE MANAGER 30 7782 CLARK MANAGER 10 7566 JONES MANAGER 20 ...

  19. The UPDATE Statement • Modify existing rows with the UPDATE statement. • Update more than one row at a time, if required. UPDATE table SET column = value [, column = value, ...] [WHERE condition];

  20. Search Conditions • Format: WHERE fieldname operator expression • Operators • Equal (=) • Greater than, Less than (>, <) • Greater than or Equal to (>=) • Less than or Equal to (<=) • Not equal (< >, !=, ^=) • LIKE • BETWEEN • IN • NOT IN

  21. Search Condition Examples WHERE s_name = ‘Sarah’ WHERE s_age > 18 WHERE s_class <> ‘SR’ • Text in single quotes is case sensitive

  22. Updating Rows in a Table • Specific row or rows are modified when you specify the WHERE clause. • All rows in the table are modified if you omit the WHERE clause. SQL> UPDATE emp 2 SET deptno = 20 3 WHERE empno = 7782; 1 row updated. SQL> UPDATE employee 2 SET deptno = 20; 14 rows updated.

  23. Updating Rows: Integrity Constraint Error • Department number 55 does not exist SQL> UPDATE emp 2 SET deptno = 55 3 WHERE deptno = 10; UPDATE emp * ERROR at line 1: ORA-02291: integrity constraint (USR.EMP_DEPTNO_FK) violated - parent key not found

  24. “…delete a row from DEPT table…” DEPT DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON 60 MIS ... Removing a Row from a Table DEPT DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON 50 DEVELOPMENTDETROIT 60 MIS ...

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

  26. Deleting Rows from a Table • Specific rows are deleted when you specify the WHERE clause. • All rows in the table are deleted if you omit the WHERE clause. SQL> DELETE FROM department 2 WHERE dname = 'DEVELOPMENT'; 1 row deleted. SQL> DELETE FROM department; 4 rows deleted.

  27. Deleting Rows: Integrity Constraint Error You cannot delete a row that contains a primary key that is used as a foreign key in another table. SQL> DELETE FROM dept 2 WHERE deptno = 10; DELETE FROM dept * ERROR at line 1: ORA-02292: integrity constraint (USR.EMP_DEPTNO_FK) violated - child record found

  28. Database Transactions • Begin when the first executable SQL statement is executed • End with one of the following events: • COMMIT or ROLLBACK is issued • DDL or DCL statement executes (automatic commit) • User exits • System crashes

  29. Advantages of COMMIT and ROLLBACK Statements • Ensure data consistency • Preview data changes before making changes permanent • Group logically related operations

  30. INSERT UPDATE INSERT INSERT DELETE DELETE ROLLBACK to Savepoint B ROLLBACK to Savepoint A ROLLBACK Controlling Transactions • Transaction INSERT UPDATE COMMIT Savepoint A Savepoint B

  31. Implicit Transaction Processing • An automatic commit occurs under the following circumstances: • DDL statement is issued • DCL statement is issued • Normal exit from SQL*Plus, without explicitly issuing COMMIT or ROLLBACK • An automatic rollback occurs under an abnormal termination of SQL*Plus or a system failure.

  32. State of the Data Before COMMIT or ROLLBACK • The previous state of the data can be recovered. • The current user can review the results of the DML operations by using the SELECT statement. • Other users cannot view the results of the DML statements by the current user. • The affected rows are locked; other users cannot change the data within the affected rows.

  33. State of the Data After COMMIT • Data changes are made permanent in the database. • The previous state of the data is permanently lost. • All users can view the results. • Locks on the affected rows are released; those rows are available for other users to manipulate. • All savepoints are erased.

  34. Committing Data • Make the changes. SQL> UPDATE emp 2 SET deptno = 10 3 WHERE empno = 7782; 1 row updated. • Commit the changes. SQL> COMMIT; Commit complete.

  35. 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. SQL> DELETE FROM employee; 14 rows deleted. SQL> ROLLBACK; Rollback complete.

  36. Savepoints • Used to mark individual sections of a transaction • You can roll back a transaction to a savepoint

  37. Rolling Back Changes to a Marker • Create a marker in a current transaction by using the SAVEPOINT statement. • Roll back to that marker by using the ROLLBACK TO SAVEPOINT statement. SQL> UPDATE... SQL> SAVEPOINT update_done; Savepoint created. SQL> INSERT... SQL> ROLLBACK TO update_done; Rollback complete.

  38. Truncating Tables • Removes all table data without saving any rollback information • Advantage: fast way to delete table data • Disadvantage: can’t be undone • Syntax: TRUNCATE TABLE tablename;

  39. Summary Statement INSERT UPDATE DELETE COMMIT SAVEPOINT ROLLBACK Description Adds a new row to the table Modifies existing rows in the table Removes existing rows from the table Makes all pending changes permanent Allows a rollback to the savepoint marker Discards all pending data changes

  40. Sequences • Sequential list of numbers that is automatically generated by the database • Used to generate values for surrogate keys

  41. Creating New Sequences • CREATE SEQUENCE command • DDL command • No need to issue COMMIT command

  42. General Syntax Used to Create a New Sequence

  43. Creating Sequences • Syntax: CREATE SEQUENCE sequence_name [optional parameters]; • Example: CREATE SEQUENCE f_id_sequence START WITH 200;

  44. Viewing Sequence Information • Query the SEQUENCE Data Dictionary View:

  45. Pseudocolumns • Acts like a column in a database query • Actually a command that returns a specific values • Used to retrieve: • Current system date • Name of the current database user • Next value in a sequence

  46. Pseudocolumn Examples

  47. Using Pseudocolumns • Retrieving the current system date: SELECT SYSDATE FROM DUAL; • Retrieving the name of the current user: SELECT USER FROM DUAL; • DUAL is a system table that is used with pseudocolumns

  48. Using PseudocolumnsWith Sequences • Accessing the next value in a sequence: sequence_name.NEXTVAL • Inserting a new record using a sequence: INSERT INTO my_faculty VALUES (f_id_sequence.nextval, ‘Professor Jones’);

  49. Object Privileges • Permissions that you can grant to other users to allow them to access or modify your database objects • Granting object privileges: GRANT privilege1, privilege2, … ON object_name TO user1, user 2, …; • Revoking object privileges: REVOKE privilege1, privilege2, … ON object_name FROM user1, user 2, …;

  50. Examples of Object Privileges

More Related