DBDev 03A
DBDev 03A
Chapter 3
Using SQL Queries to Insert, Update, Delete, and
View Data
2 / 70
Introduction
! DML commands that allow users to retrieve data
are called 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
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
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, … );
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
2. In the first
row, Tammy
Jones’ F_ID
value is 1
8 / 70
Using the INSERT Command
9 / 70
Using the INSERT Command
! 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.
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’));
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;
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.
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.
25 / 70
Creating Transactions and Committing
New Data
! Oracle DBMS implements transaction processing
by locking data rows associated with pending
transactions.
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.
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.
30 / 70
Creating Transactions and Committing
New Data
SQL> SAVEPOINT course_save1;
1 row created.
Savepoint created.
1 row created.
Rollback completed.
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
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
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 <.
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.
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;
45 / 70
Truncating Tables
! After a DML statement executes, you must commit the
transaction before the DBMS makes the changes visible
to other users.
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.
47 / 70
Truncating Tables
! Syntax:
TRUNCATE TABLE tablename;
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.
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
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.
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.
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’.
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.
SELECT sequence_name.CURRVAL
FROM DUAL;
60 / 70
Using Sequences
! Ex:
! To retrieve the next LOC_ID_SEQUENCE value
----------
21
61 / 70
Using Sequences
! Multiple users may simultaneously use a sequence to
retrieve surrogate key values.
62 / 70
Using Sequences
! The Oracle DBMS uses user sessions to ensure
that all sequence users receive unique sequence
numbers.
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”.
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, …;
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