Sei sulla pagina 1di 51

Enhanced Guide to Oracle

Using SQL Queries to Insert,


Update, Delete, and View Data

By: Deepak Malusare


Manipulating Data

By: Deepak Malusare


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

By: Deepak Malusare


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

By: Deepak Malusare


Data Manipulation Language

A DML statement is executed when you:


 Addnew 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.

By: Deepak Malusare


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

By: Deepak Malusare


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

By: Deepak Malusare


The INSERT Statement

 Add new rows to a table by using the INSERT


statement.
INSERT INTO table [(column [, column...])]
VALUES (value [, value...]);

 Only one row is inserted at a time with this


syntax.

By: Deepak Malusare


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.
SQL> INSERT INTO dept (deptno, dname, loc)
2 VALUES (50, 'DEVELOPMENT', 'DETROIT');
1 row created.
 Enclose character and date values within single
quotation marks.

By: Deepak Malusare


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.

By: Deepak Malusare


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.

By: Deepak Malusare


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

By: Deepak Malusare


Inserting Date Values

 Date values must be converted from


characters to dates using the
TO_DATE function and a format
mask
 Example:

By: Deepak Malusare


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'

By: Deepak Malusare


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

By: Deepak Malusare


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

By: Deepak Malusare


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

By: Deepak Malusare


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

EMP
EMPNO ENAME JOB ... DEPTNO

7839 KING PRESIDENT 10


7698 BLAKE MANAGER 30
7782 CLARK MANAGER 20
10
7566 JONES MANAGER 20
...

By: Deepak Malusare


The UPDATE Statement

 Modify existing rows with the UPDATE


statement.
UPDATE table
SET column = value [, column = value, ...]
[WHERE condition];

 Update more than one row at a time, if


required.

By: Deepak Malusare


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
By: Deepak Malusare
Search Condition Examples

WHERE s_name = ‘Sarah’


WHERE s_age > 18
WHERE s_class <> ‘SR’

 Text in single quotes is case sensitive

By: Deepak Malusare


Updating Rows in a Table
 Specific row or rows are modified when you
specify the WHERE clause.
SQL> UPDATE emp
2 SET deptno = 20
3 WHERE empno = 7782;
1 row updated.

 All rows in the table are modified if you omit


the WHERE clause.
SQL> UPDATE employee
2 SET deptno = 20;
14 rows updated.

By: Deepak Malusare


Updating Rows:
Integrity Constraint Error
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

By: Deepak Malusare


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

By: Deepak Malusare


The DELETE Statement

 You can remove existing rows from a table by


using the DELETE statement.
DELETE [FROM] table
[WHERE condition];

By: Deepak Malusare


Deleting Rows from a Table
 Specific rows are deleted when you specify the
WHERE clause.
SQL> DELETE FROM department
2 WHERE dname = 'DEVELOPMENT';
1 row deleted.

 All rows in the table are deleted if you omit


the WHERE clause.
SQL> DELETE FROM department;
4 rows deleted.

By: Deepak Malusare


Deleting Rows:
Integrity Constraint Error

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

By: Deepak Malusare


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

By: Deepak Malusare


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

By: Deepak Malusare


Controlling Transactions
 Transaction

INSERT UPDATE INSERT DELETE

COMMIT Savepoint A Savepoint B

ROLLBACK to Savepoint B

ROLLBACK to Savepoint A

ROLLBACK

By: Deepak Malusare


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.

By: Deepak Malusare


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.

By: Deepak Malusare


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.

By: Deepak Malusare


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.

By: Deepak Malusare


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.

By: Deepak Malusare


Savepoints

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

By: Deepak Malusare


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.

By: Deepak Malusare


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;

By: Deepak Malusare


Summary

Statement Description

INSERT Adds a new row to the table

UPDATE Modifies existing rows in the table

DELETE Removes existing rows from the table

COMMIT Makes all pending changes permanent

SAVEPOINT Allows a rollback to the savepoint marker

ROLLBACK Discards all pending data changes

By: Deepak Malusare


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

By: Deepak Malusare


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

By: Deepak Malusare


General Syntax Used to Create a
New Sequence

By: Deepak Malusare


Creating Sequences

 Syntax:
CREATE SEQUENCE sequence_name
[optional parameters];

 Example:
CREATE SEQUENCE f_id_sequence
START WITH 200;

By: Deepak Malusare


Viewing Sequence Information
 Query the SEQUENCE Data Dictionary View:

By: Deepak Malusare


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

By: Deepak Malusare


Pseudocolumn Examples
Pseudocolumn Output
Name
CURRVAL Most recently retrieved sequence
value
NEXTVAL Next value in a sequence

SYSDATE Current system date from


database server
USER Username of current user

By: Deepak Malusare


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

By: Deepak Malusare


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

By: Deepak Malusare


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, …;

By: Deepak Malusare


Examples of Object Privileges

Object Type Privilege Description


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, Allows user to insert, update, delete table data


UPDATE,
DELETE
Any database ALL Allows user to perform any operation on object
object

By: Deepak Malusare


Granting and Revoking Object
Privileges

By: Deepak Malusare

Potrebbero piacerti anche