Presentation is loading. Please wait.

Presentation is loading. Please wait.

Enhanced Guide to Oracle 10g Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data.

Similar presentations


Presentation on theme: "Enhanced Guide to Oracle 10g Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data."— Presentation transcript:

1 Enhanced Guide to Oracle 10g Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data

2 Manipulating Data

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

4 SQL Scripts  Script: text file that contains a sequence of SQL commands Usually have.sql extension Usually have.sql extension To run from SQL*Plus: To run from SQL*Plus: Start full file path Start full file path SQL> START path_to_script_file; @ full file path ( SQL> @ path_to_script_file;) @ full file path ( SQL> @ path_to_script_file;) Extension can be omitted if it is.sql 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: A DML statement is executed when you: Add new rows to a table Add new rows to a table Modify existing rows in a table Modify existing rows in a table Remove existing rows from a table Remove existing rows from a table A transaction consists of a collection of DML statements that form a logical unit of work. A transaction consists of a collection of DML statements that form a logical unit of work. A DML statement is executed when you: A DML statement is executed when you: Add new rows to a table Add new rows to a table Modify existing rows in a table Modify existing rows in a table Remove existing rows from a table Remove existing rows from a table A transaction consists of a collection of DML statements that form a logical unit of work. 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 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 commit (save) changes User can roll back (discard) changes User can roll back (discard) changes Pending transaction: a transaction waiting to be committed or rolled back Pending transaction: a transaction waiting to be committed or rolled back Oracle DBMS locks records associated with pending transactions Oracle DBMS locks records associated with pending transactions Other users cannot view or modify locked records Other users cannot view or modify locked records

7 Adding a New Row to a Table DEPT DEPTNO DNAME LOC ------ ------------------ 10ACCOUNTINGNEW YORK 20RESEARCHDALLAS 30SALESCHICAGO 40OPERATIONSBOSTON New row 50 DEVELOPMENT DETROIT DEPT DEPTNO DNAME LOC ------ ------------------ 10ACCOUNTINGNEW YORK 20RESEARCHDALLAS 30SALESCHICAGO 40OPERATIONSBOSTON “…insert a new row into DEPT table…” 50 DEVELOPMENT DETROIT

8 The INSERT Statement Add new rows to a table by using 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. Only one row is inserted at a time with this syntax. Add new rows to a table by using 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. Only one row is inserted at a time with this syntax. INSERT INTOtable [(column [, column...])] VALUES(value [, value...]); INSERT INTOtable [(column [, column...])] VALUES(value [, value...]);

9 Inserting New Rows Insert a new row containing values for each column. Insert a new row containing values for each column. List values in the default order of the columns in the table. List values in the default order of the columns in the table. Optionally list the columns in the INSERT clause. Optionally list the columns in the INSERT clause. Enclose character and date values within single quotation marks. Enclose character and date values within single quotation marks. Insert a new row containing values for each column. Insert a new row containing values for each column. List values in the default order of the columns in the table. List values in the default order of the columns in the table. Optionally list the columns in the INSERT clause. Optionally list the columns in the INSERT clause. Enclose character and date values within single quotation marks. Enclose character and date values within single quotation marks. SQL> INSERT INTOdept (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. Implicit method: Omit the column from the column list. SQL> INSERT INTOdept (deptno, dname ) 2 VALUES(60, 'MIS'); 1 row created. Explicit method: Specify the NULL keyword. SQL> INSERT INTOdept 2 VALUES(70, 'FINANCE', NULL); 1 row created.

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

12 Format Masks All data is stored in the database in a standard binary format 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 Format masks are alphanumeric text strings that specify the format of input and output data Table 3-1: Number format masks Table 3-1: Number format masks Table 3-2: Date format masks Table 3-2: Date format masks

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

14  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' Inserting Text Data

15  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’) Inserting Interval Values

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

17 Inserting Specific Date Values Add a new employee. 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 Changing Data in a Table EMP “…update a row in EMP table…” EMP EMPNO ENAME JOB... DEPTNO 7839KINGPRESIDENT 10 7698BLAKEMANAGER 30 7782CLARKMANAGER 10 7566JONESMANAGER 20... 20 EMPNO ENAME JOB... DEPTNO 7839KINGPRESIDENT 10 7698BLAKEMANAGER 30 7782CLARKMANAGER 10 7566JONESMANAGER 20...

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

20  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 Search Conditions

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

22 Updating Rows in a Table Specific row or rows are modified when you specify the WHERE clause. 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. All rows in the table are modified if you omit the WHERE clause. Specific row or rows are modified when you specify the WHERE clause. 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. 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. SQL> UPDATE employee 2 SET deptno = 20; 14 rows updated.

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

24 “…delete a row from DEPT table…” Removing a Row from a Table DEPT DEPTNO DNAME LOC ------ ------------------ 10ACCOUNTINGNEW YORK 20RESEARCHDALLAS 30SALESCHICAGO 40OPERATIONSBOSTON 50 DEVELOPMENT DETROIT 60MIS... DEPT DEPTNO DNAME LOC ------ ------------------ 10ACCOUNTINGNEW YORK 20RESEARCHDALLAS 30SALESCHICAGO 40OPERATIONSBOSTON 60MIS...

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

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

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

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

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

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

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

32 State of the Data Before COMMIT or ROLLBACK The previous state of the data can be recovered. 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. 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. 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. The affected rows are locked; other users cannot change the data within the affected rows. The previous state of the data can be recovered. 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. 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. 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. 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. Data changes are made permanent in the database. The previous state of the data is permanently lost. The previous state of the data is permanently lost. All users can view the results. All users can view the results. Locks on the affected rows are released; those rows are available for other users to manipulate. Locks on the affected rows are released; those rows are available for other users to manipulate. All savepoints are erased. All savepoints are erased. Data changes are made permanent in the database. Data changes are made permanent in the database. The previous state of the data is permanently lost. The previous state of the data is permanently lost. All users can view the results. All users can view the results. Locks on the affected rows are released; those rows are available for other users to manipulate. Locks on the affected rows are released; those rows are available for other users to manipulate. All savepoints are erased. All savepoints are erased.

34 Committing Data SQL> UPDATEemp 2 SET deptno = 10 3 WHEREempno = 7782; 1 row updated. SQL> UPDATEemp 2 SET deptno = 10 3 WHEREempno = 7782; 1 row updated. Make the changes. Make the changes. Commit the changes. SQL> COMMIT; Commit complete.

35 State of the Data After ROLLBACK Discard all pending changes by using the ROLLBACK statement. Discard all pending changes by using the ROLLBACK statement. Data changes are undone. Data changes are undone. Previous state of the data is restored. Previous state of the data is restored. Locks on the affected rows are released. Locks on the affected rows are released. Discard all pending changes by using the ROLLBACK statement. Discard all pending changes by using the ROLLBACK statement. Data changes are undone. Data changes are undone. Previous state of the data is restored. Previous state of the data is restored. Locks on the affected rows are released. Locks on the affected rows are released. SQL> DELETE FROMemployee; 14 rows deleted. SQL> ROLLBACK; Rollback complete.

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

37 Rolling Back Changes to a Marker Create a marker in a current transaction by using the SAVEPOINT statement. Create a marker in a current transaction by using the SAVEPOINT statement. Roll back to that marker by using the ROLLBACK TO SAVEPOINT statement. Roll back to that marker by using the ROLLBACK TO SAVEPOINT statement. Create a marker in a current transaction by using the SAVEPOINT statement. Create a marker in a current transaction by using the SAVEPOINT statement. Roll back to that marker by using the ROLLBACK TO 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 Removes all table data without saving any rollback information Advantage: fast way to delete table data Advantage: fast way to delete table data Disadvantage: can’t be undone Disadvantage: can’t be undone Syntax: Syntax: TRUNCATE TABLE tablename; Removes all table data without saving any rollback information Removes all table data without saving any rollback information Advantage: fast way to delete table data Advantage: fast way to delete table data Disadvantage: can’t be undone Disadvantage: can’t be undone Syntax: Syntax: TRUNCATE TABLE tablename;

39 SummarySummary 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 Statement INSERT UPDATE DELETE COMMIT SAVEPOINT ROLLBACK

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

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

42 General Syntax Used to Create a New Sequence

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

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

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

46 Pseudocolumn Examples PseudocolumnNameOutput CURRVAL Most recently retrieved sequence value NEXTVAL Next value in a sequence SYSDATE Current system date from database server USER Username of current user

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

48  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’); Using Pseudocolumns With Sequences

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

50 Examples of Object Privileges Object Type PrivilegeDescription Table, Sequence ALTER Allows user to change object’s structure using the ALTER command Table, Sequence DROP Allows user to drop object Table, Sequence SELECT Allows user to view object Table INSERT, UPDATE, DELETE Allows user to insert, update, delete table data Any database object ALL Allows user to perform any operation on object

51 Granting and Revoking Object Privileges


Download ppt "Enhanced Guide to Oracle 10g Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data."

Similar presentations


Ads by Google