0% found this document useful (0 votes)
20 views70 pages

DBDev 03A

Uploaded by

T O K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views70 pages

DBDev 03A

Uploaded by

T O K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

Guide to Oracle 10g

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

By Ahmed M. Zeki for ITBIS373


Objectives
! Run a script to create DB tables automatically
! Insert data into DB tables
! Create DB transactions and commit data to the
DB
! Create search conditions in SQL queries
! Update and delete DB records and truncate
tables
! Create and use sequences to generate surrogate
key values automatically
! Grant and revoke DB object privileges

2 / 70
Introduction
! DML commands that allow users to retrieve data
are called queries.

! DML commands that insert, update, or delete data


are called action queries.

3 / 70
Using Scripts to Create DB Tables
! Script
◦ Text file that contains one or more SQL commands

! Run a script
◦ Type start at SQL prompt
◦ Blank space
◦ Full path and filename of script file
.sql can be
ommited

! Ex: START c:\oracle\myscript.sql


START can be
replaced with @

4 / 70
Deleting all Tables from Previous
Chapter
! DROP TABLE enrollment CASCADE CONSTRAINTS
! DROP TABLE course_section CASCADE
CONSTRAINTS
! DROP TABLE term CASCADE CONSTRAINTS

In script: Ch3EmptyNorthwoods.sql

! If the table does not exist, you receive an error.


Also if you try to create a table that is already exist.

5 / 70
Using the INSERT Command
! Inserting values into every column:
INSERT INTO tablename
VALUES (column1_value, column2_value, … );

! Ex:
Must contain a value for each column
INSERT INTO location
VALUES (1, ‘CR’, ‘101’, NULL);
Consider the data type. Because the If the data is unknown or undetermined use NULL
room column has VARCHAR2 type, use
single quotation. To include an a single
quotation use two single quotations, e.g.
John’’s.

6 / 70
Using the INSERT Command
! Inserting values in a specific column:
INSERT INTO tablename (columnname1,
columnname2, … );
VALUES (column1_value, column2_value, … );

! Ex: You can list columns in any order

INSERT INTO FACULTY (F_FIRST, F_LAST, F_ID)


VALUES (‘Teresa’, ‘Marx’, 1);

1 is converted into a
character but Marx can’t
be converted into a
number.

7 / 70
Using the INSERT Command
! Ensure all foreign keys that new row references have already been added to DB
! Ex: 5. Note that this record has a foreign key value of LOC_ID 9

3. This value 4. Therefore,


refers to the FACULTY
F_ID row now for
(Teresa F_ID 1 must
Marx) in the already be in
FACULTY the DB before
table you can add
the first
STUDENT row,
1. Suppose or a foreign key
you want to reference error
insert the occurs
first row in
the
STUDENT
table

2. In the first
row, Tammy
Jones’ F_ID
value is 1
8 / 70
Using the INSERT Command

6. This LOCATION 7. The LOC_ID 9


row must already record in the
be in the DB LOCATION table
before you can has no foreign key
add the row to the values to
FACULTY table. reference.

6. Therefore, you can:


- Insert LOC_ID 9 in the LOCATION table
- Insert the associated FACULTY record, then
- Add the STUDENT record

9 / 70
Using the INSERT Command

- Same order as the column in


the table (otherwise: error)
- You must include a value for
every column
- Text strings within single
quotation

! Insert the row for F_ID 1 (Teresa Marx) in the FACULTY table:
INSERT INTO FACULTY (F_ID, F_LAST, F_FIRST, F_MI,
LOC_ID)
VALUES (1, ‘Marx’, ‘Teresa’, ‘J’, 9);

10 / 70
Format Models
! Also called format mask
! Used to specify different output format from default
! Format models only change the way the data
appears, and do not affect how Oracle stores the
data.

! For DATE/TIMESTAMP data types


◦ Default: DD-MON-YY

11 / 70
Format Models
! Digit 9 represents numbers

12 / 70
Format Models

13 / 70
Format Models

14 / 70
Inserting Date and Interval Values
! Inserting values into DATE columns
◦ Specify the date value as a character string, then Use
TO_DATE function to convert string to DATE
◦ Syntax
● TO_DATE('date_string', 'date_format_model')
◦ Ex:
● TO_DATE(‘08/24/2006', ‘MM/DD/YYYY')
● TO_DATE(’24-AUG-2005', ‘DD-MON-YYYY‘)
◦ Ex:
● To convert a 10:00 AM to a DATE format:
● TO_DATE(’10:00 AM’, ‘HH:MI AM’)
◦ Ex:

15 / 70
Inserting Date and Interval Values
! Inserting values into INTERVAL columns
◦ Insert values as strings, then use a function to convert the
character to an internal INTERVAL data format.
◦ Syntax Hyphen
● TO_YMINTERVAL('years-months')
Integer - Integer

● TO_DSINTERVAL('days HH:MI:SS.99')
◦ Ex:
● TO_YMINTERVAL(‘4-9’)
● TO_DSINTERVAL(‘0 01:15:00’)

Fractional second
value is optional

16 / 70
Inserting Date and Interval Values
! Ex: How long the student has been enrolled at the
university
INSERT INTO student
VALUES (‘JO100’, ‘Jones’, ‘Tammy’, ‘R’,
‘1817 Eagleridge Circle’, ‘Tallahassee’,
‘FL’, ‘32811’, ‘7155559876’, ‘SR’,
TO_DATE(’07/14/1985’, ‘MM/DD/YYYY’),
‘8891’, 1, TO_YMINTERVAL(‘3-1’));

! Ex: Add 2 years and 2 months to a given date


◦ TO_DATE(’07/14/1985’, ‘MM/DD/YYYY’) +
TO_YMINTERVAL(‘2-2’)
Type: Date

Type: Interval 17 / 70
Example
! SQL> CREATE TABLE coupons (
2 coupon_id INTEGER,
3 name VARCHAR2(30),
4 duration INTERVAL YEAR(3) TO MONTH
5 );

Table created.

SQL> INSERT INTO coupons (coupon_id, name, duration) VALUES (1, '$1 off Z Files', INTERVAL '1' YEAR);

1 row created.

SQL> INSERT INTO coupons (coupon_id, name, duration) VALUES (2, '$2 off Pop 3', INTERVAL '11' MONTH);

1 row created.

SQL> INSERT INTO coupons (coupon_id, name, duration) VALUES (3, '$3 off Modern Science', INTERVAL '14' M
ONTH);

1 row created.

SQL> INSERT INTO coupons (coupon_id, name, duration) VALUES (4, '$2 off Tank War', INTERVAL '1-3' YEAR T
O MONTH);

1 row created.

18 / 70
Example
! SQL> INSERT INTO coupons (coupon_id, name, duration) VALUES (5, '$1 off Chemistry', INTERV
AL '0-5' YEAR TO MONTH);

1 row created.

SQL> INSERT INTO coupons (coupon_id, name, duration) VALUES (6, '$2 off Creative Yell', INTE
RVAL '123' YEAR(3));

1 row created.

SQL>
SQL> SELECT * FROM coupons;

COUPON_ID NAME DURATION


---------- ------------------------------ ---------------------------------------------------------------------------
1 $1 off Z Files +001-00
2 $2 off Pop 3 +000-11
3 $3 off Modern Science +001-02
4 $2 off Tank War +001-03
5 $1 off Chemistry +000-05
6 $2 off Creative Yell +123-00

6 rows selected.
19 / 70
Inserting LOB Column Locators
! Oracle stores LOB data in a separate physical
location from other types of data in a row.
! When inserting data in an LOB column, you must
initially insert a locator for the data.
! An LOB locator is a structure that contains
information that identifies the LOB data type and
points to the alternate memory location.
! After inserting the LOB locator, you then write a
program or use a utility to insert the binary data
into the DB.

20 / 70
Inserting LOB Column Locators
! To create a locator for a BLOB data column:
EMPTY_BLOB()

! Ex:
INSERT INTO FACULTY (F_ID, F_LAST, F_FIRST, F_IMAGE)
VALUES (2, ‘Zhulin’, ‘Mark’, Empty_BLOB());

21 / 70
Creating Transactions and Committing
New Data
! When you create a new table or update the structure of an
existing table, the DBMS changes the rows immediately and
makes the change visible to other users.

! This is not the case when you insert, update, or delete data
rows.

! Oracle allows users to execute a series of action queries as a


transaction which represent a logical unit of work.

! In a transaction, all action queries need to succeed, or non


should succeed.

22 / 70
Creating Transactions and Committing
New Data
! Example of purchase transaction: there are
3processes:
◦ The DBMS must insert the purchase information in the
ORDERS table
◦ The DBMS must insert the purchase information in the
ORDER_LINE table
◦ The DBMS must reduce the item’s quantity on hand value
in the INVERNORY table.
! If the 1st two were successfully done, but the 3rd
fails ! INVENTORY table does not contain the
updated value for the quantity on hand.
! Hence, all three queries need to succeed or non
should succeed. 23 / 70
Creating Transactions and Committing
New Data
! After the user enters all of the action queries in a
transaction, he can either COMMIT (save) all of the
changes or ROLL BACK (discard) all changes
! When Oracle executes an action query, it updates
the data in the DB and also records information
that enables the DBMS to undo the action query’s
changes.
! The DBMS saves this information to undo the
changes until the user commits or rolls back the
transaction that includes the action query.

24 / 70
Creating Transactions and Committing
New Data
! The purpose of transaction processing is to enable
every user to see a consistent view of the DB.

! To achieve this consistency, a user cannot view or


update data values that are part of another user’s
uncommitted transaction because these
uncommitted transactions (pending transactions)
might be rolled back.

25 / 70
Creating Transactions and Committing
New Data
! Oracle DBMS implements transaction processing
by locking data rows associated with pending
transactions.

! When the DBMS locks a row, other users cannot


view or modify the row.

! When the user commits the transaction, the DBMS


releases the lock on the rows, and other users can
view and update the rows again.

26 / 70
Creating Transactions and Committing
New Data
! You do not explicitly create new transactions in
Oracle, rather, a new transaction begins when you
start SQL*PLUS and execute a command, and the
transaction ends when you commit the current
transaction.
! After you commit the current transaction, another
transaction begins when you type a new query.
! You commit a transaction by executing the
COMMIT command.
! After you execute the COMMIT command a new
transaction begins.

27 / 70
Creating Transactions and Committing
New Data
! You can configure SQL*PLUS to commit every query
automatically after you execute the query, but this is not
recommended because you will not be able to create
transactions.

! Oracle automatically commits the current transaction


when you exit SQL*PLUS. However, it is a good practice
to explicitly commit your changes often so rows are
available to other users. This ensures your changes are
saved if you do not exit normally because of a power
failure.

28 / 70
Creating Transactions and Committing
New Data
! The rollback process enables you to restore the
DB to its state the last time you issued the
COMMIT command. In that case the DBMS rolls
back all changes made in subsequent action
queries.

29 / 70
Creating Transactions and Committing
New Data
! You can use rollbacks with savepoints.

! Savepoint is a bookmark that designates the


beginning of an individual section of a transaction.

! You can roll back part of a transaction by rolling


back the transaction only to the savepoint.

30 / 70
Creating Transactions and Committing
New Data
SQL> SAVEPOINT course_save1;

! Ex: Savepoint created.

SQL> INSERT INTO course


2 VALUES (‘CGS 270’, ‘Database Management’, 3);

1 row created.

SQL> SAVEPOINT course_save2;

Savepoint created.

SQL> INSERT INTO course


2 VALUES (‘COP 174’, ‘Intorduction to Java’, 3);

1 row created.

SQL> ROLLBACK TO course_save2;

Rollback completed.

SQL> SELECT * FROM course;

COURSE_NO COURSE_NAME CREDITS


---------- ------------------------- ---------
CGS 270 Database Management 3

SQL> 31 / 70
Search Conditions
! To write queries to update, delete or retrieve DB rows
you often need to specify which rows you intend to be
affected.
! To identify a row you use search condition which is an
expression that seeks to match specific table rows. It
can be also used to compare column values to
numerical, date, and character values.
! Syntax:
WHERE columnname comparison_operator search_expression

32 / 70
Search Conditions

33 / 70
Search Conditions

34 / 70
Defining Search Expressions
! NUMBER example
◦ WHERE f_id = 1
! Character data example
◦ WHERE s_class = 'SR'
! DATE example
◦ WHERE s_dob = TO_DATE('01/01/1980', ‘MM/
DD/YYYY')

35 / 70
Defining Search Expressions
! If you choose to search for a data value without
using the TO_DATE function, the search condition
must be in the same format as Oracle internal
storage format (i.e DD-MON-YY).
◦ Use < for date before a given date
◦ Use > for date after a given date
◦ Use = to match a given date

36 / 70
Defining Search Expressions
! To search for data values that match an INTERVAL
column, you must use the TO_INTERVAL and
TO_YMINTERVAL and TO_DSINTERVAL
functions to convert the character string
representation of the interval to the INTERVAL
data type.
! Ex:
WHERE c_sec_duration = TO_DSINTERVAL(‘0 1:15:00’)
WHERE time_enrolled < TO_YMINTERVAL(‘1-0’)

37 / 70
Creating Complex Search Conditions

! Combines multiple search conditions using


AND,OR, and NOT logical operators.
! EX
◦ WHERE bldg_code =‘CR’ AND capacity >50
◦ WHERE day=‘MW’ OR day =‘UTH’
◦ WHERE NOT(s_class = ‘FR’)

38 / 70
Updating Table Rows
! To update column values in one or more rows in a
table use UPDATE action query. UPDATE
Specifies the name of the table to update and lists
the name of the column(s) to update, along with
the new data value(s).
! UPDATE also contains a search condition to
identify the row(s) to update.
! Syntax
◦ UPDATE tablename
SET column1 = newvalue1, column2 = newvalue2, …
WHERE search condition;

39 / 70
Updating Table Rows
! You can update multiple columns in the same table
using a single UPDATE.
! You can update rows in only one table at a time in
a single UPDATE.
! If you omit the search condition, the query updates
every table row.
! Ex:
UPDATE FACULTY VARCHAR2

SET f_rank = ‘ASSOCIATE’, f_pin = 1181


WHERE f_id = 1;

40 / 70
Updating Table Rows

41 / 70
Updating Table Rows
! You can update multiple rows in a table with a
single UPDATE command by specifying a search
condition that matches multiple rows using > or <.

! Ex: updates the value of s_class for all rows in the


STUDENT table
UPDATE STUDENT
SET s_class = ‘SR’;

42 / 70
Deleting Table Rows
! Syntax
DELETE FROM tablename
WHERE search condition;
! Ex:

43 / 70
Deleting Table Rows
! You can delete multiple rows from a table if the
search condition matches several rows.

! If you omit the search condition, DELETE will


delete all table rows.

44 / 70
Deleting Table Rows
! When a row’s value is a foreign key that references
another row, it is called a child row.
◦ The row for Teresa Marx is child row of the row for LOC_ID 9.
◦ You can’t delete a row if it has a child row. Hence you can’t
delete the row for LOC_ID 9 unless you first delete the row in
which the foreign key value exists (F_ID 1, faculty member
Teresa Marx).
DELETE FROM LOCATION
WHERE loc_id = 9;

DELETE FROM lOCATION


*
ERROR at line 1:
ORA-02292: integrity constraint (SYSTEM.FACULTY_LOC_ID_FK)
violated – child record found

45 / 70
Truncating Tables
! After a DML statement executes, you must commit the
transaction before the DBMS makes the changes visible
to other users.

! The DELETE action query is a DML statement.

! Wherever you delete a row using a DELETE action


query, an Oracle DBMS process records rollback
information that the DBMS uses to restore the row if you
roll back the transaction.
! For a DELETE action query, rollback information includes
all of the column values for the deleted data row.

46 / 70
Truncating Tables
! If you use a DELETE action query to delete many rows
such as all of the rows in a table, the DBMS must make a
copy of each deleted value.

! For a table with many columns and rows, this process


can take a long time.

! When you need to delete all of the rows in a table quickly,


you can truncate the table, which means you remove all
of the table data without saving any rollback information.

! When you truncate a table, the table structure and


constraints remain intact.

47 / 70
Truncating Tables
! Syntax:
TRUNCATE TABLE tablename;

! You can’t truncate a table that has foreign key


constraints as long as the foreign key constraints
are enabled.
! Therefore you must disable a table’s FK
constraints before you can truncate the table.

ALTER TABLE tablename


DISABLE CONSTRAINT constraint_name;

48 / 70
Truncating Tables
! LOC_ID column in the LOCATION table is a FK in both
the FACULTY table and the COURSE_SECTION table,
so you must first disable the LOC_ID FK constraints in
the FACULTY and COURSE_SECITON tables. Then you
truncate the LOCATION table.

49 / 70
SEQUENCES
! Sequential lists of numbers that the Oracle DBMS
generates to create unique surrogate key values.

! It is a DB object, so you use the DDL (Data


Description Language): CREATE command to
create a new sequence. Because the CREATE
SEQUENCE command is a DDL command, the
DBMS immediately creates the sequence when
you execute the command, and you do not need to
type COMMIT to save the sequence.

50 / 70
SEQUENCES
! Every sequence in your user schema must have a unique
name, and the name must follow the Oracle naming
standard rules.
! Syntax Any integer, Default: 1

The default max value is


Any +ve or –ve integer, Ensuresthat
Specifies thatwhenever
the DBMS 27grants
NOMAXVALUE: 10you request
when omitted: 1 sequence numbers to
a sequence value the DBMS users in the
exact chronological
automatically order the
generates in which the
specified
users The
request default
the min
values.
number_of_values and stores themvalue
Ex: is
the 1 st

userinwho NOMINVALUE:
the requests
cache. This a number 10
improves -26
from DBthe
sequence is granted
performance when many users aresequence
number 1,when
simultaneously
Specifies that the 2nd user whosequence
requesting
the sequence requests
reaches
a
its MAXVALUE, value is
values. Default: granted
Oracle
it cycles sequence
backstores 20
and starts
number2,
sequence and so
numbersforth.inThis
the
again at its MINVALUE. If cycle parameter is useful
cache.
for tracking
The
is omitted NOCACHE the order
or replaced withinNOCYCLE,
parameter which users
directs the
the
request
DBMS sequence
not to values.
cache any
sequence continues to generate values By default,
sequence
until this value isitsNOORDER,
it reaches values.
MAXVALUE, which
then it
specifies
quits generating values. not
that the DBMS does
necessarily grant the sequence
values in the same order that users
request the values.

51 / 70
SEQUENCES

52 / 70
Viewing Sequence Information
! A large DB application may use many sequences !
forget your sequences names.
! To review the names you can query the
USER_SEQUENCES data dictionary view, which has a
column named SEQUENCE_NAME, which displays the
names of all of the sequences in your user schema.

SELECT SEQUENCE_NAME
FROM USER_SEQUENCE

SEQUENCE_NAME
--------------------------
LOC_ID_SEQUENCE

53 / 70
Viewing Sequence Information
! USER_SEQUENCE view contains other columns
that provide additional information about
sequences, such as the MINVALUE and
MAXVALUE specifications, and the last value the
sequence generated.

54 / 70
Using Sequences
! Oracle pseudocolumn acts like a column in a DB
table, but is actually a command that returns a
specific value.

! To retrieve a current or next value of a sequence:


◦ CURRVAL: most recent sequence value retrieved during
the current user session.
◦ NEXTVAL: next avaialble sequence value.

55 / 70
Using Sequences
! To retrieve the next value in a sequence, you
reference the NEXTVAL pseudocolumn use:
sequence_name.NEXTVAL
! Ex:
! 1. retrieve the next value in LOC_ID_SEQUENCE
and insert value into a row in the LOCATION table
INSERT INTO LOCATION (LOC_ID)
VALUES(loc_id_sequence.NEXTVAL)

56 / 70
Using Sequences
! 2. insert a row into the LOCATION table using
LOC_ID_SEQUENCE and the NEXTVAL
pseudocolumn

57 / 70
Using Sequences
! Sometimes you need to access the next value of a
sequence, but you don’t want to insert a new row.

! Ex: suppose you want to display F_ID value on a


form, but you need to have the faculty enter more
information before you actually insert the new row
into the DB:
SELECT sequence_name.NEXTVAL
FROM DUAL;

58 / 70
Using Sequences
! Dual is a simple table that belongs to the SYSTEM
user schema. It has one row, which contains a
single column that contains the character string ‘X’.

! All DB users can use DUAL in SELECT queries,


but they can’t modify or delete values in DUAL.

59 / 70
Using Sequences
! Whenever you execute a SELECT query using
pseudocolumn with any DB table, the query
returns a value for each table row. It is more
efficient to retrieve psedocolumn from DUAL,
which has only one row, than from other tables that
may contain many rows.

! To view the current value of the sequence:

SELECT sequence_name.CURRVAL
FROM DUAL;

60 / 70
Using Sequences
! Ex:
! To retrieve the next LOC_ID_SEQUENCE value

SQL> SELECT LOC_ID_SEQUENCE.NEXTVAL


2 FROM DUAL
21 is the NEXTVAL. Now that it
has been accessed, 21 becomes
NEXTVAL the current value.

----------
21

SQL> SELECT LOC_ID_SEQUENCE.CURRVAL


2 FROM DUAL
Confirms that 21 is the current
CURRVAL value.
----------
21

61 / 70
Using Sequences
! Multiple users may simultaneously use a sequence to
retrieve surrogate key values.

! The DBMS must guarantee that each user who accesses


a sequence receives a unique sequence number.

! When a user connects to an Oracle DB, the user creates


a user session.

! A user session starts when a user starts a client


application such as SQL*PLUS, and logs onto the DB. A
user session terminates when the user exits the
application.

62 / 70
Using Sequences
! The Oracle DBMS uses user sessions to ensure
that all sequence users receive unique sequence
numbers.

! When the DBMS uses a sequence value to your


user session, no other user’s session can access
that sequence value.

! This prevents two different users from assigning


the same primary key values to rows.

63 / 70
Using Sequences
! You can use the CURRVAL pseudocolumn to access the last
value that you retrieved from a sequence only during the same
DB user session in which you used the NEXTVAL
pseudocolumn to retrieve the value.

! Ex:
SELECT LOC_ID_SEQUENCE.NEXTVAL FORM DUAL;
◦ The value 22 will appear (for instance)
◦ Exit SQL*PLUS
◦ START SQL*PLUS again and log onto the DB
SELECT LOC_ID_SEQUENCE.CURRVAL FROM DUAL;

64 / 70
Using Sequences
! You receive the error message:
◦ “Error at line 1:ORA-08002: sequence
LOC_ID_SEQUENCE.CURRVAL is not yet defined in this
session”.

! This indicates that no CURRVAL exists for the


sequence because you exited SQL*PLUS and
started a new session.

! A CURRVAL can be selected from a sequence only


after selecting a NEXTVAL.

65 / 70
Deleting Sequences
! DROP LOC_ID_SEQUENCE

66 / 70
DB Object Priviliges
! When you create DB objects such as tables or
sequences, other users can’t access or modify the
objects in your user schema unless you give them
explicit privileges to do so.

67 / 70
Granting Object Privileges
! Permissions that you can grant to other users to
allow them to access or modify your database
objects
GRANT privilege1, privilege2, …
ON object_name
TO user1, user 2, …;

! In this syntax, the GRANT clause lists each


privileges to be granted, such as ALTER or DROP.

68 / 70
Granting Object Privileges
! Note that in a single command, you can grant privileges
for only one object at a time, but you can grant privileges
to many users at once. If you want to grant privileges to
every DB user, you can use the keyword PUBLIC in the
TO clause.

69 / 70
Revoking Table Privileges
! To cancel a user’s object privileges:
REVOKE privilege1, privilege2, …
ON object_name
FROM user1, user 2, …;
! When you grant a privileges to the PUBLIC, the privilege
can be revoked only by a user who has been granted the
DBA system privileges.

70 / 70

You might also like