Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 51

Enhanced Guide to Oracle 10g

Chapter 3:
Using SQL Queries to Insert,
Update, Delete, and View Data
Manipulating
Manipulating Data
Data
Objectives
Objectives


 After
After completing
completing this
this lesson,
lesson, you
you should
should
be
be able
able to
to do
do the
the following
following::
 Describe
 Describe each
each DML
DML statement
statement
 Insert
 Insert rows
rows into
into aa table
table
 Update
 Update rows
rows in
in aa table
table
 Delete
 Delete rows
rows from
from aa table
table
 Control
 Control transactions
transactions
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
Data
Data Manipulation
Manipulation Language
Language
A
 A DML
DML statement
statement is
is executed
executed when
when
you
you::
Add
 Add new
new rows
rows to
to aa table
table
Modify
 Modify existing
existing rows
rows in
in aa table
table
Remove
 Remove existing
existing rows
rows from
from aa table
table
A
 A transaction
transaction consists
consists of
of aa collection
collection
of
of DML
DML statements
statements that
that form
form aa logical
logical
unit
unit of
of work
work..
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
Adding
Adding aa New
New Row
Row to
to aa Table
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
The
The INSERT
INSERT Statement
Statement

 Add
 Add new
new rows
rows to
to aa table
table by
by using
using the
the
INSERT
INSERT statement
statement..
INSERT
INSERT INTO
INTO table
table [(column
[(column [,
[, column...])]
column...])]
VALUES
VALUES (value
(value [,
[, value...]);
value...]);

 Only
 Only one
one row
row is
is inserted
inserted at
at aa time
time with
with this
this
syntax
syntax..
Inserting
Inserting New
New Rows
Rows
 Insert
 Insert aa new
new row
row containing
containing values
values for
for each
each
column
column..
 List
 List values
values in
in the
the default
default order
order of
of the
the
columns
columns in
in the
the table
table..
 Optionally
 Optionally list
list the
the columns
columns inin the
the INSERT
INSERT
clause
clause..
SQL> INSERT INTO dept (deptno, dname, loc)
2 VALUES (50, 'DEVELOPMENT', 'DETROIT');
1 row created.
 Enclose
 Enclose character
character and
and date
date values
values within
within
single
single quotation
quotation marks
marks..
Inserting
Inserting Rows
Rows with
with Null
Null Values
Values
 Implicit
 Implicit method
method:: Omit
Omit the
the column
column from
from the
the
column
column list
list..
SQL> INSERT INTO dept (deptno, dname )
2 VALUES (60, 'MIS');
1 row created.

•• Explicit
Explicit method:
method: Specify
Specify the
the NULL
NULL
keyword.
keyword.
SQL> INSERT INTO dept
2 VALUES (70, 'FINANCE', NULL);
1 row created.
Inserting
Inserting Special
Special Values
Values

 The
The SYSDATE
SYSDATE function
function records
records the
the
current
current date
date and
and time
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.
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
Inserting Date Values

 Date values must be converted from


characters to dates using the
TO_DATE function and a format
mask
 Example:
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'
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’)
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()
Inserting
Inserting Specific
Specific Date
Date Values
Values
 Add
 Add aa new
new employee
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
Verify your
your addition.
addition.
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
----- ------- -------- ---- --------- ---- ---- ------
2296 AROMANO SALESMAN 7782 03-FEB-97 1300 10
Changing
Changing Data
Data in
in aa Table
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
...
The
The UPDATE
UPDATE Statement
Statement

 Modify
 Modify existing
existing rows
rows with
with the
the UPDATE
UPDATE
statement
statement..
UPDATE
UPDATE table
table
SET
SET column
column == value
value [,
[, column
column == value,
value, ...]
...]
[WHERE
[WHERE condition];
condition];

 Update
 Update more
more than
than one
one row
row at
at aa time,
time, if
if
required
required..
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
Search Condition Examples

WHERE s_name = ‘Sarah’


WHERE s_age > 18
WHERE s_class <> ‘SR’

 Text in single quotes is case sensitive


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

 All
 All rows
rows in
in the
the table
table are
are modified
modified if
if you
you
omit
omit the
the WHERE
WHERE clause
clause..
SQL>
SQL> UPDATE
UPDATE employee
employee
22 SET
SET deptno
deptno == 20;
20;
14
14 rows
rows updated
updated..
Updating
Updating Rows
Rows::
Integrity
Integrity Constraint
Constraint Error
Erroriisstt
e
exx
oott
s
s nn
SQL>
SQL> UPDATE
UPDATE emp
emp ooee
5 dd
22 SET
SET deptno
deptno == 55
55
5
5 5
33 WHERE
WHERE deptno = 10;
deptno = 10; eerr
m bb
n uu m
n tt n
een
r
r m
ttm
UPDATE
UPDATE emp ppaa
emp
D e
e
** D
ERROR at line 1: 
ERROR at line 1:
ORA-02291:
ORA-02291: integrity
integrity constraint
constraint (USR.EMP_DEPTNO_FK)
(USR.EMP_DEPTNO_FK)
violated
violated -- parent
parent key
key not
not found
found
Removing
Removing aa Row
Row from
from aa Table
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
...
The
The DELETE
DELETE Statement
Statement

 You
You can
can remove
remove existing
existing rows
rows from
from aa table
table by
by
using
using the
the DELETE
DELETE statement
statement..
DELETE
DELETE [FROM]
[FROM] table
table
[WHERE
[WHERE condition];
condition];
Deleting
Deleting Rows
Rows from
from aa Table
Table
 Specific
 Specific rows
rows are
are deleted
deleted when
when you
you specify
specify
the
the WHERE
WHERE clause
clause..
SQL>
SQL> DELETE
DELETE FROM
FROM department
department
22 WHERE
WHERE dname
dname == 'DEVELOPMENT';
'DEVELOPMENT';
11 row
row deleted
deleted..

 All
 All rows
rows in
in the
the table
table are
are deleted
deleted if
if you
you omit
omit
the
the WHERE
WHERE clause
clause..
SQL>
SQL> DELETE
DELETE FROM
FROM department;
department;
44 rows
rows deleted
deleted..
Deleting
Deleting Rows
Rows::
Integrity
Integrity Constraint
Constraint Error
Error
rrooww
SQL>
SQL> DELETE
DELETE FROM
FROM dept
dept e t
t e
e a
a e yy
22 WHERE
WHERE deptno = 10; ott d
deptno = 10; e
e ll e
d maarryy kk e
a
a n
n nn o p rrii m kk e
eyy
o uu c
c s
s aa p i
i g
g n
n
Y o
Y onnttaai i n
n f oorree
a
cco d aass a abbllee.. f
DELETE
DELETE FROM
FROM dept
dept aatt
tthh s uusseed eerr tta
**
a
a tt i
i s n o
o t
t h
h
ERROR at line 1: h
tth i n
n a
a n
ERROR at line 1:
ORA-02292:
ORA-02292: integrity
integrity constraint
i
constraint (USR.EMP_DEPTNO_FK)
(USR.EMP_DEPTNO_FK)
violated
violated -- child
child record
record found
found
Database
Database Transactions
Transactions

 Begin
 Begin when
when the
the first
first executable
executable SQL
SQL
statement
statement is
is executed
executed
 End
 End with
with one
one ofof the
the following
following events
events::
 COMMIT
 COMMIT or
or ROLLBACK
ROLLBACK is
is issued
issued
 DDL
 DDL or
or DCL
DCL statement
statement executes
executes ((automatic
automatic
commit
commit))
 User
 User exits
exits
 System
 System crashes
crashes
Advantages
Advantages of
of COMMIT
COMMIT
and
and ROLLBACK
ROLLBACK Statements
Statements
 Ensure
 Ensure data
data consistency
consistency
 Preview
 Preview data
data changes
changes before
before making
making
changes
changes permanent
permanent
 Group
 Group logically
logically related
related operations
operations
Controlling
Controlling Transactions
Transactions

 Transaction
Transaction

INSERT UPDATE INSERT DELETE

COMMIT Savepoint A Savepoint B

ROLLBACK to Savepoint B

ROLLBACK to Savepoint A

ROLLBACK
Implicit
Implicit Transaction
Transaction Processing
Processing
 An
 An automatic
automatic commit
commit occurs
occurs under
under the
the
following
following circumstances
circumstances::
 DDL
 DDL statement
statement is
is issued
issued
 DCL
 DCL statement
statement is
is issued
issued
 Normal
 Normal exit
exit from
from SQL
SQL**Plus,
Plus, without
without explicitly
explicitly
issuing
issuing COMMIT
COMMIT or
or ROLLBACK
ROLLBACK
 An
 An automatic
automatic rollback
rollback occurs
occurs under
under an
an
abnormal
abnormal termination
termination of
of SQL
SQL**Plus
Plus or
or aa
system
system failure
failure..
State
State of
of the
the Data
Data Before
Before
COMMIT
COMMIT or or ROLLBACK
ROLLBACK
 The
 The previous
previous state
state of
of the
the data
data can
can be
be recovered
recovered..
 The
 The current
current user
user can
can review
review the
the results
results of
of the
the
DML
DML operations
operations by
by using
using the
the SELECT
SELECT statement
statement..
 Other
 Other users
users cannot
cannot view
view the
the results
results of
of the
the DML
DML
statements
statements by
by the
the current
current user
user..
 The
 The affected
affected rows
rows are
are locked
locked;; other
other users
users cannot
cannot
change
change the
the data
data within
within the
the affected
affected rows
rows..
State
State of
of the
the Data
Data After
After COMMIT
COMMIT
 Data
 Data changes
changes are
are made
made permanent
permanent in
in the
the
database
database..
 The
 The previous
previous state
state of
of the
the data
data isis permanently
permanently
lost
lost..
 All
 All users
users can
can view
view the
the results
results..
 Locks
 Locks on on the
the affected
affected rows
rows are
are released;
released; those
those
rows
rows areare available
available for
for other
other users
users to to manipulate
manipulate..
 All
 All savepoints
savepoints areare erased
erased..
Committing
Committing Data
Data
 Make
 Make the
the changes
changes..
SQL>
SQL> UPDATE
UPDATE emp
emp
22 SET
SET deptno
deptno == 10
10
33 WHERE
WHERE empno
empno == 7782;
7782;
11 row
row updated
updated..

•• Commit
Commit the
the changes.
changes.
SQL> COMMIT;
Commit complete.
State
State of
of the
the Data
Data After
After ROLLBACK
ROLLBACK

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

 Used to mark
individual
sections of a
transaction
 You can roll back
a transaction to a
savepoint
Rolling
Rolling Back
Back Changes
Changes
to
to aa Marker
Marker
 Create
 Create aa marker
marker in
in aa current
current transaction
transaction by
by using
using
the
the SAVEPOINT
SAVEPOINT statement
statement..
 Roll
 Roll back
back to
to that
that marker
marker by
by using
using the
the ROLLBACK
ROLLBACK
TO
TO SAVEPOINT
SAVEPOINT statement
statement..
SQL> UPDATE...
SQL> SAVEPOINT update_done;
Savepoint created.
SQL> INSERT...
SQL> ROLLBACK TO update_done;
Rollback complete.
Truncating
Truncating Tables
Tables

 Removes
Removes allall table
table data
data without
without saving
saving any
any
rollback
rollback information
information
 Advantage:
 Advantage: fast
fast way
way to
to delete
delete table
table data
data
 Disadvantage:
 Disadvantage: can’t
can’t be
be undone
undone

 Syntax:
Syntax:
TRUNCATE
TRUNCATE TABLE
TABLE tablename
tablename;;
Summary
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


Sequences
 Sequential list of numbers that is
automatically generated by the database
 Used to generate values for surrogate
keys
Creating New Sequences
 CREATE SEQUENCE command
 DDL command
 No need to issue COMMIT command
General Syntax Used to Create a
New Sequence
Creating Sequences

 Syntax:
CREATE SEQUENCE sequence_name
[optional parameters];

 Example:
CREATE SEQUENCE f_id_sequence
START WITH 200;
Viewing Sequence Information
 Query the SEQUENCE Data Dictionary View:
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


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

Current system date from SYSDATE


database server
Username of current user USER
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
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’);
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, …;
Examples of Object Privileges

Description Privilege Object Type


Allows user to change object’s structure using ALTER Table, Sequence
the ALTER command
Allows user to drop object DROP Table, Sequence

Allows user to view object SELECT Table, Sequence

Allows user to insert, update, delete table data INSERT, Table


UPDATE,
DELETE
Allows user to perform any operation on object ALL Any database
object
Granting and Revoking Object
Privileges

You might also like