Oracle SQL Tutorial
Oracle SQL Tutorial
Oracle SQL Tutorial
SQL*Plus — schemata — data types — DML & DDL examples — editing commands —
using external files — the dual pseudo-table — introduction to transactions — optional
exercise — references.
Introduction
During this tutorial you will build on your databases knowledge by learning the
fundamentals of Oracle, one of the most widely used database management system in
industry.
SQL*Plus
You will be prompted for your username and password. If you haven't got an account,
you can try to use scott for the username, and tiger for the password. You will learn at a
later stage how to change your password. The last piece of information required by
SQL*Plus is the name of the database you want to use (called host string).
You are now connected to a shared database, on which you have an account (called a
schema ).
Basic SQL
Table 1 outlines the main Oracle SQL data types, together with their MySQL equivalent.
Note is the VARCHAR2 type, so called for historical reasons. The NUMBER(p,s) type
takes two arguments; precision and scale. The precision of a number its number of
significant decimal digits, and its scale is the number of digits after the decimal point.
You should now be able to create a few tables and populate them.
title VARCHAR2(60),
author VARCHAR2(60),
isbn NUMBER(10,0)
isbn NUMBER(10,0)
reviewer VARCHAR2(30),
comments VARCHAR2(150)
Note the use of the SYSDATE function that returns the system's current date in the
DEFAULT clause above. The `/' character terminates an SQL statement and submits it
to SQL*Plus.
You should be already familiar with the syntax of the primary key and referential
integrity constraints. They function in Oracle in a similar fashion as in MySQL.
pk_books and fk_books_booksrev are constraint names.
Now check the schema of the tables you have just created using the desc
<table_name> command (same command as in MySQL).
9876543210,
'14-FEB-1895'
9876543210,
'Alice',
Editing Commands
Before starting the next section, you should practise creating and populating some more
tables.
SQL*Plus — schemata — data types — DML & DDL examples — editing commands —
using external files — the dual pseudo-table — introduction to transactions — optional
exercise — references.
You are now armed to attempt some more complex SQL expressions.
Sequence numbers.
A SEQUENCE is an Oracle object that generates integers according to a specific pattern.
Sequence numbers are commonly utilised to supply auto-generated primary keys. The
default behaviour of a SEQUENCE is to increment its current value by one to get the next.
You may already have used sequences in MySQL, using the AUTO_INCREMENT
attributes. Note however the two differences with Oracle's sequences:
The following code creates a SEQUENCE that we will then use to insert some more
values in the books table.
'Oliver Twist',
'Charles Dickens',
book_seq.NEXTVAL,
'12-SEP-1839'
Apart from the the Oracle peculiarities we have already discussed, you can re-use most
of your knowledge of SQL. You may want for example to experiment with the UPDATE
and DELETE statements.
Introduction to Transactions
Transaction management is a broad topic to which you have been introduced in the
database lectures. You should refer to your notes for a more detailed coverage of the
subject, as we will here just remind a few points. A transaction is a logical unit of work ,
that could be for example the placement of an order. On completion, a transaction
needs to be either confirmed —making all the changes permanent—or cancelled —
returning the database into the state it was before starting the transaction.
These two actions are performed in SQL by issuing one of the two commands COMMIT
or ROLLBACK.
To experiment with transactions, you will need to work in pairs (say Alice and Bob) and
allow the other student to read the data in your books table. So Alice will need to enter:
Now Alice should enter some data in her books table. Bob can then attempt to view the
newly inserted data by typing:
Note how you can prefix the table name with its schema to reference other students'
tables. Can Bob view the changes Alice has made? What happens if Alice COMMITs the
transaction? Try also with ROLLBACK.
Try to relate your observations with your understanding of transactions.
ISBNs (International Standard Book Number) are unique, 10-digit book identifiers used
in the publishing industry. With the help of the references given at the end of this
document, create a sequence to generate 10-digit integers for use with the books table.
References
You can copy & paste the following URIs (note that you will need a username/password
to access Oracle's web site. You can use [email protected]/database):
PL/SQL Tutorial
Introduction
SQL statements are defined in term of constraints we wish to fix on the result of a
query. Such a language is commonly referred to as declarative. This contrasts with the
so called procedural languages where a program specifies a list of operations to be
performed sequentially to achieve the desired result. PL/SQL adds selective (i.e.
if...then...else...) and iterative constructs (i.e. loops) to SQL.
PL/SQL is most useful to write triggers and stored procedures. Stored procedures are
units of procedural code stored in a compiled form within the database.
PL/SQL Fundamentals
Your first example in PL/SQL will be an anonymous block —that is a short program that
is ran once, but that is neither named nor stored persistently in the database.
SQL> SET SERVEROUTPUT ON
SQL> BEGIN
2 dbms_output.put_line('Welcome to PL/SQL');
3 END;
4 /
You are referred to Table 2 for a list of operators, and to Table 3 for some useful built-in
functions.
Debugging.
Unless your program is an anonymous block, your errors will not be reported. Instead,
SQL*Plus will display the message ``warning: procedure created with compilation
errors''. You will then need to type:
to see your errors listed. If yo do not understand the error message and you are using
Oracle on UNIX, you may be able to get a more detailed description using the oerr
utility, otherwise use Oracle's documentation (see References section). For example, if
Oracle reports ``error PLS-00103'', you should type:
If you have submitted the program above to Oracle, you have probably noticed that it is
executed straight away. This is the case for anonymous blocks, but not for procedures
and functions. The simplest way to run a function (e.g. sysdate) is to call it from within
an SQL statement:
2 /
Next, we will rewrite the anonymous block above as a procedure. Note that we now use
the user function to greet the user.
IS
BEGIN -- `BEGIN' ex
|| user_name || '!');
END;
Once you have compiled the procedure, execute it using the EXEC command.
Both procedures and functions should remind you of Java methods. The similarities and
differences between them are outlined in Table 1.
Table 1: Functions, procedures and Java methods compared.
PL/SQL alone does not allow us to query a database, and use the resulting data in our
program. However, any SQL (i.e. DML) may be embedded in PL/SQL code. In
particular, there exists a form of the ``SELECT'' statement for assigning the result of a
query to a variable. Note the following code requires the books and book_reviews
tables that you should have created during the first Oracle tutorial.
2 (author_param VARCHAR2)
3 IS
4 review_count NUMBER;
5 BEGIN
14 dbms_output.put_line('There is 1 review.');
15 ELSE
16 dbms_output.put_line('There is no review.');
17 END IF;
18 END;
19 /
The last program we are going to write will display the number of reviews relevant to
each author. Notice that the query may now return multiple rows. However, a
SELECT...INTO... statement can only retrieve data from (at most) one tuple into
individual variables.
Cursors3 provide a means to retrieve multiple rows into a buffer (when you OPEN the
cursor) that can then be traversed sequentially (FETCH) to retrieve individual rows—until
there is no more data (cur_revs%NOTFOUND becomes true).
auth VARCHAR2(30);
cnt NUMBER;
CURSOR cur_revs IS
BEGIN
OPEN cur_revs;
LOOP
|| auth);
ELSE
END IF;
END LOOP;
CLOSE CUR_REVS;
END;
Table 3: Some Oracle built-in functions. You are referred to Oracles's documentation
(see References section) for specific usage examples.
Function Description
String Functions
upper(s), lower(s) convert string s to upper/lower-case
initcap(s) capitalise first letter of each word
ltrim(s), rtrim(s) remove blank char. from left/right
substr(s,start,len) sub-string of length len from position start
length(s) length of s
Date Functions
sysdate current date (on Oracle server)
to_date(date, format) date formatting
Number Functions
round(x) round real number x to integer
mod(n,p) n modulus p
abs(x) absolute value of x
dbms_random.random() generate a random integer
Type Conversion Functions
to_char() convert to string
to_date() convert to date
to_number() convert to number
Miscellaneous Functions
user current Oracle user
References
You can copy & paste the following URI (note that you will need a username/password
to access Oracle's web site. You can use [email protected]/database):
http://download-
west.oracle.com/docs/cd/A91202_01/901_doc/appdev.901/a89856/toc.htm
Introduction
This document presents Oracle's data dictionary, also called the system catalogue. The
data dictionary is the repository of all the meta-data relevant to the objects stored in the
database—and also of information concerning the DBMS itself.
Dictionary Content
Defining metadata.
The term metadata is often defined as data about data. That is, data that provides
information about the tables, views, constraints, stored procedures, etc. stored within
the database. If we take a table as an example, the dictionary will store information such
as:
its name
when it was created and when it was last accessed
the names and data types of its attributes (i.e. structural information)
its owner, who may read and write to it (i.e. security information)
where the data is stored (i.e. physical information)
Security in Oracle.
Oracle defines two categories of privileges: object privileges and system privileges.
Both categories are granted and revoked using the GRANT and REVOKE SQL constructs:
GRANT <object_privilege> ON <object> TO <user> and GRANT
<system_privilege> TO <user>. You have already used the former (see
Introduction to Oracle.)
System privileges mainly specify the types of objects a user is allowed to manipulate
(tables,...) and what (s)he can do with them. Object privileges define the access rights
at the objects level (and even at the attribute level for tables).
Dictionary Structure
The data dictionary is implemented in Oracle as a set of read-only tables and views.
Figure 1 presents the two-level structure of the dictionary. At the root of the tree is the
dictionary table, that features two attributes: table_name and comments. The
comment field presents an informal description of the corresponding dictionary table.
For instance, we can request information about the dictionary table:
and get:
As an exercise, write a query to find out how many tables make up the data dictionary.
The second level of the dictionary is divided into four categories of tables. ``User'' tables
describe the objects you own. They are only accessible to you. ``All'' tables describe the
objects of all the users, and are accessible to all the users. ``DBA'' tables contain
information only relevant and accessible to database administrators. And last, ``V$''
tables reflect the internal state of the DBMS and are mainly useful to DBAs for
performance audit and optimisation.
You should refer to Figure 1 for a list of commonly-used dictionary tables. Also,
remember that you can obtain the schema of any table with the desc command1 (see
Introduction to Oracle)
Introduction
The Java DataBase Connectivity API is a set of classes allowing a straightforward
and vendor-neutral access to database management systems. We will review the
basic features of JDBC and their use with Oracle
JDBC Overview
Accessibility.
JDBC provides a set of high-level classes that enable anyone acquainted with SQL and
Java to write database applications. Considerations like networking and database
protocols are transparent to the application programmer. These are handled by classes
within JDBC drivers.
Connecting to Oracle
We will review below how to access Oracle using both types of driver. First, we use the
thin driver to connect to Oracle and execute an update statement. Note that the
example below is only intended as an illustration. Try to understand the code. You will
have opportunities for ``hands-on'' practice in the next section.
import java.io.*;
import java.sql.*;
If we want use the OCI driver, the JDBC connection URL above needs to be altered.
The only element now required is the service name of the database: database_name.
The remainder is resolved using the local Oracle configuration file.
DriverManager.getConnection(
"jdbc:oracle:oci8:@database_name", "scott","tiger");
In this section we present the DbObject class that allows to connect to an Oracle
database, and execute SQL statements. You will need to download the file
DbObjectClasses.jar into your home area and run the command (in UNIX or in a DOS
box):
DbObject.java and DbObject.class, the java source and class for our
database access class
DbObject.conf, the configuration file of DbObject
DbTest.java and DbTest.class, the java source and class file for the test
class DbTest.
java DbTest
The programme will perform INSERT, UPDATE and SELECT statements. You should
now read carefully both java source files.
Exercises
References
You can copy & paste the following URIs (note that you will need a username/password
to access Oracle's web site. You can use [email protected]/database):
Introduction
You have been reviewed so far JDBC basics. In the next sections, we will discuss
two more advanced topics: how to run PL/SQL code from Java—and conversely,
how to run Java code from PL/SQL. The two issues we are going to address during
this laboratory have a larger scope than the ones in the previous laboratories.
Java versus PL/SQL.
The considerations listed below outline why and when to use Java rather than PL/SQL:
Java offers more opportunities for reuse accross applications (c.f. class
Mod11Ck below)
there are more Java programmers that PL/SQL programmers
Java is potentially more efficient for non-database related programmative tasks
PL/SQL is a proprietary language only supported by Oracle.
PL/SQL is tightly integrated with the Oracle DBMS, therefore (argueably) easier
to use for database applications
it is more efficient for database-oriented programmative tasks.
Putting it to work...
The two classes in PicDispClasses.jar display pictures stored as BLOBs in Oracle.
To avoid overloading the database, you will all use the same table pic_store and
account scott/tiger1. Extract the source and class files from the jar archive and
execute the program as follows:
Compile the Java class above and load it into Oracle by issuing the following command:
comp-load-j ./Mod11Ck.java
Note that this is not a standard Oracle utility, but a script that I wrote to read your Oracle
username and password from the DbObject.conf file (see Introduction to Oracle &
Java.) Be aware that DbObject.conf is expected to be in the current directory.
You should be able to lookup the data dictionary to find out whether the Java class
compiled successfully (see Oracles's Data Dictionary.) The class will be stored in
compiled format as a BLOB, in the database.
Next, we need to write a call specification to publish our java (static) method as a
PL/SQL function.
We can now write a trigger (c.f. rules in Postgres) that will validate the ISBN for each
INSERT statement executed on the books table. If the last digit of the ISBN about to be
inserted does not match the calculated check-digit, an exception is raised—leading the
INSERT statement to be rolled-back.