Sunteți pe pagina 1din 52

Computer Science Laboratory

Ghent University, Faculty of Engineering

Introduction to Oracle SQL


October 2001

Contents
1 Introduction
1.1 An Oracle database

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2 Data Definition Language


2.1 Databases . . . . . . . . . . . . . . . . . . .
2.1.1 Create database . . . . . . . . . . .
2.1.2 Alter database . . . . . . . . . . . .
2.2 Tablespaces . . . . . . . . . . . . . . . . . .
2.2.1 Create tablespace . . . . . . . . . . .
2.2.2 Alter tablespace . . . . . . . . . . .
2.2.3 Drop tablespace . . . . . . . . . . .
2.3 Tables . . . . . . . . . . . . . . . . . . . . .
2.3.1 Create table . . . . . . . . . . . . . .
2.3.2 Alter table . . . . . . . . . . . . . .
2.3.3 Drop table . . . . . . . . . . . . . .
2.4 Indexes . . . . . . . . . . . . . . . . . . . .
2.4.1 Create index . . . . . . . . . . . . .
2.4.2 Alter index . . . . . . . . . . . . . .
2.4.3 Drop index . . . . . . . . . . . . . .
2.5 (Materialized) views . . . . . . . . . . . . .
2.5.1 Create view . . . . . . . . . . . . . .
2.5.2 Alter view . . . . . . . . . . . . . . .
2.5.3 Drop view . . . . . . . . . . . . . . .
2.5.4 Create materialized view . . . . . . .
2.5.5 Alter materialized view . . . . . . .
2.5.6 Drop materialized view . . . . . . .
2.6 Synonyms . . . . . . . . . . . . . . . . . . .
2.6.1 Create synonym . . . . . . . . . . .
2.6.2 Drop synonym . . . . . . . . . . . .
2.7 Sequences . . . . . . . . . . . . . . . . . . .
2.7.1 Create sequence . . . . . . . . . . .
2.7.2 Alter Sequence . . . . . . . . . . . .
2.7.3 Drop sequence . . . . . . . . . . . .
2.8 Programmable objects . . . . . . . . . . . .
2.8.1 Stored procedures and user functions
2.8.2 Packages . . . . . . . . . . . . . . . .
2.8.3 Triggers . . . . . . . . . . . . . . . .
2.9 Users, roles and privileges . . . . . . . . . .
2.9.1 Create user . . . . . . . . . . . . . .
2.9.2 Alter user . . . . . . . . . . . . . . .
2.9.3 Drop user . . . . . . . . . . . . . . .
2.9.4 Create role . . . . . . . . . . . . . .
3

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

5
5
7
7
8
9
10
10
10
11
12
12
15
18
18
18
19
20
20
20
21
21
21
22
23
23
23
23
24
24
25
25
26
26
28
29
30
31
32
32
33

CONTENTS
2.9.5 Alter role . . . . .
2.9.6 Drop role . . . . .
2.9.7 Grant privilege . .
2.9.8 Revoke privilege .
2.10 Oracle built-in datatypes
2.11 The Data Dictionary . . .
2.11.1 Introduction . . .
2.11.2 Overview . . . . .

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.

33
33
33
34
35
36
36
37

3 Data Manipulation Language


3.1 Retrieving data from the database . . . .
3.1.1 The select clause . . . . . . . . . .
3.1.2 The from clause . . . . . . . . . .
3.1.3 The where clause . . . . . . . . . .
3.1.4 Joining tables . . . . . . . . . . . .
3.1.5 Grouping and aggregate functions
3.1.6 Sorting the result of the query . .
3.2 Expressions . . . . . . . . . . . . . . . . .
3.2.1 Simple expressions . . . . . . . . .
3.2.2 Compound expressions . . . . . . .
3.2.3 Function expressions . . . . . . . .
3.2.4 CAST expressions . . . . . . . . .
3.2.5 DECODE expressions . . . . . . .
3.2.6 CASE expressions . . . . . . . . .
3.3 Conditions . . . . . . . . . . . . . . . . . .
3.3.1 Simple comparison conditions . . .
3.3.2 Group comparison conditions . . .
3.3.3 Membership conditions . . . . . .
3.3.4 Range conditions . . . . . . . . . .
3.3.5 Null conditions . . . . . . . . . . .
3.3.6 Exists conditions . . . . . . . . . .
3.3.7 Like conditions . . . . . . . . . . .
3.3.8 Compound conditions . . . . . . .
3.4 Inserting data into the database . . . . . .
3.4.1 The value clause . . . . . . . . . .
3.4.2 Using a subquery . . . . . . . . . .
3.5 Changing existing data . . . . . . . . . . .
3.6 Deleting data from the database . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

39
39
40
40
40
41
41
42
42
43
44
44
46
47
47
47
48
49
49
50
50
50
50
50
51
51
51
51
52

Chapter 1

Introduction
The Structured Query Language (SQL) is the standard language used to interact with relational
database systems. All major database management systems support SQL. Most of these systems
implement only part of the ISO standard, completed with their own extensions. This tutorial is
based on the Oracle implementation.
SQL consists of two parts. One part, the Data Definition Language (DDL), is used to define
and modify the structure of a database. Chapter 2 explains this part. The other part, the Data
Manipulation Language (DML), is used to query and to change the data in a database. This is
explained in chapter 3.
As this is only an introduction, many of the more advanced options are omitted. Especially
following topics are not discussed:
Advanced options related to the physical storage of data.
Options related to partitioning and clustering of tables.
Object Relational constructs.
Options related to embedded use of SQL.
For a more exhaustive explanation of all these subjects we refer to the Oracle 8i SQL Reference.

1.1

An Oracle database

Before getting started with SQL, we will have a quick look at the organization of an Oracle
database. This will be helpful to understand some SQL constructs. Note the information in this
section is typical for Oracle. DBMSs differ a lot in the general construction of their databases.
An Oracle Instance is a collection of processes (and memory buffers) that run on a server.
It is created when an Oracle database is started. When the database is stopped, the instance is
disposed. An Oracle Instance provides access to exactly one database. On the other hand, several
instances (generally running on different servers with shared storage facilities) can manage the
same database. This is possible using the Oracle Parallel Server option.
A database is identified by its own name and the domain name of the server it runs on (e.q.
csl.telin@egidius.rug.ac.be, is the database csl.telin running on the egidius server).
At the logical level a database consists of one or more tablespaces. Tablespaces are used to
divide the data of the database in logical units, for instance each application that uses the database
could have its own tablespace. A lot of management operations (such as putting them online or
offline, move to another database) can be applied to tablespaces. Therefore a good separation of
the data in tablespaces simplifies database management.
5

CHAPTER 1. INTRODUCTION

Figure 1.1: An example setup of a database


Each database has at least one tablespace (the system tablespace). Unless the database goes
offline, this tablespace is always online. It contains the data dictionary tables and views. These
are tables and views that contain the metadata about the structure of the database.
At the physical level, each tablespace consists of one or more data files. Figure 1.1 shows a
possible configuration of an Oracle database.
Apart from the tablespaces, each user has its own schema. This schema contains all the
database objects that are owned by this user. The name of the schema corresponds to the username. Schemas and tablespaces are independent concepts.
The use of other objects in a database is explained in the next chapter together with the SQL
statement to handle them.

Chapter 2

Data Definition Language


As mentioned before, the Data Definition Language is used to define or alter the structure of a
database. In general the DDL has a CREATE, ALTER and DROP statement for each kind of
object in the database. This chapter has one section for each kind of object, where the purpose
of the object and the DDL statements to handle them is explained.
The properties of the objects are not discussed in depth. The focus is on the logical and semantic properties, because these commonly have counterparts in other relational DBMSs. Properties
concerning physical storage are usually not discussed. Also note that not all of the object types
that are available in Oracle are mentioned. After reading this tutorial, the reader should be able
to use the Oracle documentation to learn more about the omitted properties and object types.
It has to be mentioned that nowadays database administration is commonly done with the
help of graphical tools. These tools allow the user to create, alter and drop database objects with
no or little knowledge of SQL. Whether these tools use SQL to interact with the database or not
depends on the product. Typically Oracle tools do. In most cases the user can even see and
modify the created SQL code.
Although these tools are far more easier to use (compared to writing SQL code), it is often
very helpful to know how the underlying SQL statements work because this will provide a more
formal grip to interpret the options offered by a graphical user interface. Furthermore, a lot of
database products (not including Oracle) offer a lot of wizards to do straightforward actions only.
To execute more complicated operations the user still needs to write the SQL statements.

2.1

Databases

A database is the largest unit of storage in the oracle environment. All other types of objects are
stored within a database. It is common that one server (or a cluster of servers) contains only one
database, especially in Oracle where a database can be logically divided in tablespaces (in other
systems databases have a similar function as tablespaces have in Oracle).
7

2.1.1

CHAPTER 2. DATA DEFINITION LANGUAGE

Create database

- CREATE - DATABASE - database

?- CONTROLFILE - REUSE

- LOGFILE ?- GROUP - integer - filespec

- MAXLOGFILES - integer

- MAXLOGMEMBERS - integer

- MAXDATAFILES - integer

- MAXINSTANCES - integer

- ARCHIVELOG

- NOARCHIVELOG ?


- CHARACTER - SET - charset


- NATIONAL - CHARACTER - SET - charset

- DATAFILE ? filespec

file spec:

- - filename - - SIZE - integer

- K

- M

? - REUSE
66

Most of the properties available in this statement are related to the files used by the database
to store data and logging information.
CONTROLFILE REUSE
Use this clause to indicate that existing control files should be reused for the new database, ignoring
and overwriting any information they currently contain. The control files contain information
about all other files in the database, so they are the primary resource of information about a
database for the Oracle system.
LOGFILE clause
The log file clause specifies the files to used for the redo log. Each log file has a group number.
All log files in the same group are copies of each other. Oracle requires at least 2 log file groups.
MAXLOGFILES
This clause specifies the maximum number of log file groups in the database.
MAXLOGMEMBERS
This clause specifies the maximum numbers of files in one redo log file group.

?-

2.1. DATABASES

MAXDATAFILES
Defines the initial maximum number of files for data storage. This parameter is only used to
determine the space needed for filenames in the control files. The control files are extended
automatically if more data files are added to the database.
MAXINSTANCES
This parameter specifies how much instances can have this database mounted and opened.
ARCHIVELOG, NOARCHIVELOG
Specify ARCHIVELOG if the contents of redo log files have to be archived before they are reused.
This clause prepares for the possibility of media recovery. Specify NOARCHIVELOG if the redo
log files can be reused without archiving them. This is the default setting.
CHARACTER SET
Use this property to specify the character set used to store data.
NATIONAL CHARACTER SET
Use this property to specify the character set used to store data of the types NCHAR, NCLOB
and NVARCHAR2.

2.1.2

Alter database

- ALTER - DATABASE - database

- recover_clause
- datafile_tempfile_clauses
- logfile_clauses
- controlfile_clauses

- MOUNT

- OPEN
- READ - WRITE

- READ - ONLY
?

- RENAME - GLOBAL_NAME - TO - database ? . - domain

,
,

- RENAME - FILE ? - filename - - TO ? - filename -


- CHARACTER - SET - character_set


- NATIONAL - CHARACTER - SET - character_set
?

An alter database statement can be used to modify, maintain or recover a database.


recover clause
This clause is used for recovery operation.

10

CHAPTER 2. DATA DEFINITION LANGUAGE

datafile tempfile clauses, logfile clauses


These clauses are used to add, drop or change data files, temp files and log files respectively.
MOUNT
Use this clause to mount an unmounted database.
OPEN
Use this clause to open a mounted database. A database can be opened read only mode or in
read/write mode. Read/write is the default mode.

2.2

Tablespaces

As mentioned before, a tablespace is a logical unit of storage in an Oracle database. Tablespaces


can be deleted, exported and imported in one single operation. When carefully chosen and managed, they can save a lot of time for a database administrator.

2.2.1

Create tablespace

- CREATE - TABLESPACE - tablespace - DATAFILE ? file_spec

?- LOGGING

- NOLOGGING

- ONLINE

- OFFLINE ?

- PERMANENT

- TEMPORARY ??

LOGGING, NOLOGGING
This clause determines the default logging behaviour of tables and indexes created in this tablespace.
ONLINE, OFFLINE
Specify ONLINE to make the tablespace available immediately after creation. This is the default
mode. Specify OFFLINE to make the tablespace unavailable immediately after creation.
PERMANENT, TEMPORARY
Specify PERMANENT if the tablespace will be used to store permanent objects. Specify TEMPORARY if the tablespace will be used to hold temporary objects only.

2.2.2

Alter tablespace

- ALTER - TABLESPACE - tablespace

2.2. TABLESPACES

11
- datafile-tempfile_clauses

- ONLINE

- OFFLINE
- NORMAL

- TEMPORARY

- IMMEDIATE

- FOR - RECOVER ?

6

- BEGIN

- END
? BACKUP

- READ - ONLY

- WRITE ?

- PERMANENT

- TEMPORARY

- LOGGING

- NOLOGGING ?
?

Datafile temp clauses


This clause is used to add or change (rename) the data files of the tablespace.
ONLINE, OFFLINE
Use these clauses to put a tablespace online or offline.
BEGIN, END BACKUP
Use the BEGIN BACKUP clause to indicate that an open backup is to be performed on the data
files of the tablespace. Use END BACKUP after completion of the backup.
READ ONLY, READ WRITE
Change the read/write mode of the tablespace.
PERMANENT, TEMPORARY
Use this clauses to change the tablespace from a permanent one to a temporary or vice versa.

2.2.3

Drop tablespace

- DROP - TABLESPACE - tablespace

- INCLUDING - CONTENTS - CASCADE - CONSTRAINTS

66

Use this statement to remove a tablespace from the database. Use the INCLUDING CONTENTS
to drop all the contents of the tablespace too. If this clause is omitted and the tablespace is not
empty, Oracle will rise an error.

12

CHAPTER 2. DATA DEFINITION LANGUAGE

2.3

Tables

Tables are the basic unit of data storage in an Oracle database. Data is stored in rows (tuples)
which have been subdivided in columns (attributes). A table is defined with a table name and
a set of columns. Each column has a column name, a datatype and a width. The width can be
predetermined by the datatype, as in DATE. If columns are of the NUMBER datatype, precision
and scale need to be defined instead of width. A row is a collection of column information
corresponding to a single record. You can specify rules for each column of a table. These rules are
called integrity constraints. One example is a NOT NULL integrity constraint. This constraint
forces the column to contain a non null value in every row. After a table is created, rows of data
can be inserted using SQL statements. Table data can then be queried, deleted, or updated using
SQL.

2.3.1

Create table

- CREATE - GLOBAL - TEMPORARY - TABLE - schema - . - table


- ( - relational_properties - )
- ON - COMMIT - DELETE

- PRESERVE ? ROWS

6

- TABLESPACE - tablespace

- table_properties
6

- AS - subquery
6

Specify the name of the new table after the TABLE keyword. Use a schema indicator if the table
has to be created in a non default schema (the default is the current users schema).
The relational properties of the table (the content definition) is specified in the table properties
clause. This clause is explained in the next subsection.
Use the tablespace clause to specify in which tablespace the table should be stored. If this clause
is omitted, the table is stored in the default tablespace for the current user. The table properties
clause is explained in the last subsection.
The AS subquery clause can be used to fill the table with the results of a query immediately
after creation.
Relational properties

?- column - datatype
- table_constraint

- DEFAULT - expr

? column_constraint
6

6
?-

In this clause of the create table statement, columns and constraints are specified.
A column definition consists of the name of the column, the datatype of the column and, if
applicable, a default value. The datatype of the default value should be the same datatype as the
column.
Column constraints
If there are column specific constraints (constraints which involve only one column), these have to
be specified immediately after the column specification.

2.3. TABLES

13

- CONSTRAINT - constraint

- NOT - NULL
6

- UNIQUE


- PRIMARY - KEY ?

- REFERENCES - schema - . - table


- ( - column - )
- ON - DELETE - CASCADE

- SET - NULL ?

6

- CHECK - ( - condition - )

Use the CONSTRAINT keyword followed by a name to specify a name for the constraint. If
this clause is omitted, a system generated name is used.
There are several kinds of column constraints:
NOT NULL:
Every row of the table must have a non null value for this column.
UNIQUE PRIMARY KEY:
Each row must have a unique value for this column. Primary Key columns cannot contain
null values.
REFERENCES:
This column is a foreign key column. See table constraints for more information on foreign
keys.
CHECK:
A check constraint contains a condition that must be satisfied by all (non null) values in this
column.
Table constraints
Table constraints have similar functions as the corresponding column constraints, but they (can)
involve more than one column.

- CONSTRAINT - constraint

- UNIQUE
,

- PRIMARY - KEY ?( ? column - )

- foreign_key_clause


- CHECK - ( - condition - )
?

Use the constraint clause to give a name to the constraint. If this clause is omitted, a system
generated name will be used.
UNIQUE PRIMARY KEY:
Specifies a set of column that contain unique values. Primary keys cannot contain null
values. Oracle automatically creates an index for each unique or primary key constraint.

14

CHAPTER 2. DATA DEFINITION LANGUAGE


REFERENCES:

- FOREIGN - KEY - ( ? column - ) - REFERENCES - schema - .



- table - ( ? column - )
- ON - DELETE - CASCADE

- SET - NULL ?
6
Specifies a set of columns that references another table. This constraint checks if the value
of the foreign key exists in the referenced table. If the referenced columns are not specified,
Oracle assumes that the primary key is referenced.
Use the ON DELETE clause to specify what should happen when the referenced row is
deleted. With the CASCADE option, the referencing rows will be deleted together with the
referenced row. With the SET NULL option, all references to the deleted row will be set to
null values. When this clause is omitted, the deletion of referenced rows is not allowed.
CHECK:
A check constraint contains a condition that must be satisfied by all rows of the table.
Table properties

- CACHE

- NOCACHE ? - MONITORING

- NOMONITORING ? ? enable_diable_clause

CACHE, NOCACHE
Used to specify whether the data of this table should be cached or not. Caching will speed up
repeated access to the table, but may slow down access to other tables.
MONITORING, NOMONITORING
Enable or disable monitoring of this table. With monitoring enabled, Oracle will collect statistics
that can be used by the query optimizer to speed up queries.
enable disable clause

- ENABLE
- VALIDATE

- NOVALIDATE ?

6
,

- DISABLE
?- UNIQUE - ( ? column - )


- PRIMARY - KEY

- CONSTRAINT - constraint
?- CASCADE

Use this clause enable or disable a constraint. When a constraint is enabled, all updates of
the table are checked against the constraint; if it is disabled, this check not performed. When a

2.3. TABLES

15

constraint is enabled, VALIDATE can be used to make sure that the existing content of the table
satisfies the constraint. If NOVALIDATE is specified, the existing content of the table may violate
the constraint.
When disabling a constraint, CASCADE can be specified to disable all the constraint that
depend on the disabled constraint.

2.3.2

Alter table

- ALTER - TABLE - schema - . - table

?- ADD - ( - add_column_options - )


- MODIFY - ( - modify_column_options - )

- MOVE - ONLINE - TABLESPACE - tablespace

- LOGGING

- NOLOGGING ?

- drop_constraint_clause
- drop_column_clause

- CACHE

- NOCACHE ?

- MONITORING

- NOMONITORING ?


- RENAME - TO - new_table_name

?
?6

? - enable_disable_clause

- ENABLE

- DISABLE ?- TABLE - LOCK


- ALL - TRIGGERS ??
6

With the alter table statement one can change the definition of a table. The semantics of the table
properties have been explained in the previous section, so they will only be mentioned here.
ADD clause
add column options ::=

16

CHAPTER 2. DATA DEFINITION LANGUAGE

?- column - datatype

- DEFAULT - expr

- col_ref_constraint
6

? col_constraint

- table_constraint
- table_ref_constraint

?-

Use the ADD clause to add columns or constraints to the table.


MODIFY clause
modify column options ::=

? column

- datatype

- DEFAULT - expr

? col_constraint

Use this clause to change the definition of existing columns in the table.
MOVE clause
Use this clause to move the table to another tablespace. Specify ONLINE if the table should be
accessible for DML operations during the rebuild.
LOGGING, NOLOGGING
Specify one of these keywords to indicate whether this operation should be logged or not.
Drop constraint clause



- DROP
- PRIMARY - KEY

- UNIQUE - ( ? column - ) ?- CASCADE

- CONSTRAINT - constraint
?

Use this clause to drop a constraint on the table. A primary key or unique constraint cannot be
dropped if they are referenced by foreign key constraints. If these foreign keys have to be dropped
together with the primary key or unique constraint, add CASCADE to the clause.
Drop column clause

2.3. TABLES

17

- SET - UNUSED - COLUMN - column


- ( ? column - ) ? ?- CASCADE - CONSTRAINTS

- INVALIDATE
?

- DROP - COLUMN - column

- ( ? column - ) ? ?- CASCADE - CONSTRAINTS

- INVALIDATE
? - CHECKPOINT - integer

- DROP - UNUSED - COLUMNS

- COLUMNS - CONTINUE ?- CHECKPOINT - integer

There several ways to remove a column from the table definition. The most convenient way is
to use the second option in the schema. Specify one column name after the COLUMN keyword
or a list of column names to be removed.
Specify CASCADE CONSTRAINTS to remove constraints that depend on the removed column(s). If this clause is omitted, and a constraints depending on a removed column exists, Oracle
will raise an error.
Specify INVALIDATE to automatically invalidate all objects (such as views, triggers, programmed units, etc.) that reference the removed column.
The CHECKPOINT clause can be used to specify that Oracle has to take a checkpoint each
time integer rows have been removed. This prevents the rollback buffers from being overloaded.
If integer is omitted, the default value of 512 is used. The Disadvantage of this technique is that
a full rollback of the operation is not possible. If the operation fails, the table remains in an
unusable state. The unusable table can either be dropped or the DROP COLUMNS CONTINUE
clause in this statement can be used to bring the table in a consistent state.
The first option in the schema above has exactly the same logical meaning as the DROP clause
described above, but it does not physically remove the column from the database. This means
that an unused column is not accessible (and not restorable), but that the data still exist. Using
this way to remove a column results in a better response time, since Oracle does not have to
reorganize the table.
The DROP UNUSED COLUMNS clause can be used to physically remove the unused column(s) of the table.
RENAME
Use this clause to change the name of the table.
Enable, disable clause
Compared to the enable disable clause of the create table statement, two additional options are
available. Table lock can be enabled or disabled. DDL statements executed on a table need to
lock that table before any changes can be made to the table definition, if the table lock is disabled,
the DDL statement cannot be executed.
Use the ALL TRIGGERS clause to enable or disable all triggers of the table at once.

18

CHAPTER 2. DATA DEFINITION LANGUAGE

2.3.3

Drop table

- DROP - TABLE - schema - . - table

- CASCADE - CONSTRAINTS

Use this clause to remove a table from the database.

2.4

Indexes

Indexes are optional structures associated with tables. Indexes can be created to increase the
performance of data retrieval. When processing a request, Oracle can use some or all of the
available indexes to locate the requested rows efficiently. Indexes are useful when applications
often query a table for a range of rows or a specific row.
Indexes are created on one or more columns of a table. Once created, an index is automatically
maintained and used by Oracle. Changes to table data (such as adding new rows, updating rows, or
deleting rows) are automatically incorporated into all relevant indexes with complete transparency
to the users. This, of course, decreases the performance of update actions.
Indexes are logically and physically independent of the data. They can be dropped and created
any time with no effect on the tables or other indexes. If an index is dropped, all applications
continue to function. However, access to previously indexed data could be slower.

2.4.1

Create index

- CREATE
- UNIQUE

- BITMAP ?- INDEX - schema - . - index - ON


6

- schema - . - table - t_alias - ( ?- column


6

- column_expression

? - ONLINE

- LOGGING

- NOLOGGING ?

- COMPUTE - STATISTICS

- TABLESPACE - tablespace

- DEFAULT

- COMPRESS - integer

- NOCOMPRESS
?

? 6


? - ASC

- DESC ? - )
6

2.4. INDEXES

19

Use the keyword UNIQUE to indicate that this index has to check a unique key constraint on its
base table. Normal indexes use a B-Tree to store the keys. If the keyword BITMAP is used, the
keys are stored in a bitmap like structure. Bitmap storage cannot be combined with a unique key
index.
After the index name, the index content is specified: the name of the base table and a list of
expressions which make up the index key. In general, the expressions are column names, but it is
possible to index on computed values. Use the ASC or DESC keywords to indicate that the key
values have to be indexed ascending or descending respectively.
The last part of this statement contains property settings that are not content related. The
tablespace clause specifies in which tablespace the index has to be stored.
The COMPRESS property tells Oracle to compress the index, by storing repeated key values only once. The integer following the keywords specifies how much levels (= number of key
columns) of compression Oracle may apply. This integer is minimum one and maximum the number of key columns (minus one for unique indexes). Specify NOCOMPRESS (default) to prohibit
compression.
Specify the ONLINE keyword to indicate that the base should not be locked during the creation
of the index.
Specify COMPUTE STATISTICS to collect statistics at relatively little cost during the creation
of the index. These statistics are stored in the data dictionary for use by the query optimizer.

2.4.2

Alter index

- ALTER - INDEX - schema - . - index

- REBUILD ?- TABLESPACE - tablespace

- ONLINE

- COMPUTE - STATISTICS

- COMPRESS - integer

- NOCOMPRESS
?

- LOGGING

- NOLOGGING ?
?

- ENABLE

- DISABLE ?

- UNUSABLE


- RENAME - TO - new_index_name
?

Use this statement to change the properties of an index. The rebuild clause instructs Oracle to
recreate the index entirely. The subclauses of the rebuild clause have the same meaning as in the
create index statement.
The ENABLE clause enables a function based index that has been disabled because a userdefined function used by the index was dropped or replaced. The DISABLE clause disables a
function based index, so the function can be maintained.
Use the UNUSABLE clause to permanently disable an index. An unusable index can only be
enabled by rebuilding it or it can be dropped and recreated.
The RENAME clause provides a new name for the index.

20

CHAPTER 2. DATA DEFINITION LANGUAGE

2.4.3

Drop index

- DROP - INDEX - schema - . - index - FORCE

Use this statement to drop an index.

2.5

(Materialized) views

A view is a tailored presentation of the data contained in one or more tables or other views. A
view takes the output of a query and treats it as a table. Therefore, a view can be thought of as
a stored query or a virtual table. Views can be used in most places where a table can be used.
Because views are derived from tables, they have many similarities. For example, you can define
views with up to 1000 columns, just like a table. You can query views, and with some restrictions
you can update, insert into, and delete from views. All operations performed on a view actually
affect data in some base table of the view and are subject to the integrity constraints and triggers
of the base tables.
Views can be used for several reasons:
Complexity hiding: the optimal storage format of the data (e.g. normalized tables) are
rather complex and not very suitable for direct user access. For this reason views can be
created to hide this complexity while maintaining the optimal storage format.
Query storage: in a general database, most of the queries will be variations on some basic
queries. If these basic queries are available as views, user do not have to recreate them all
the time.
Logical data independence: if the users (and applications) access the data through views,
the database can be restructured without having to change the interface to the normal user
and the applications.
Whereas the data of a normal view is not stored in the database, but retrieved from the base
tables when necessary, the data of a materialized view is stored as if it where a base table. A
materialized view can allow updates or not. Update actions against materialized views are not
propagated in the base tables.
Materialized views are very useful in applications that regularly execute queries on big amounts
of data, but dont need to use the most recent data. Datamining and decision support system are
examples of such applications.

2.5.1

Create view

- CREATE - OR - REPLACE
- NO - FORCE - VIEW

6 6
6

- schema - . - view
6

- ( ? alias


- ) - AS - subquery 6

The create view statement creates a new (non-materialized) view. If a view with the same name
already exists, the OR REPLACE clause can be inserted to replace the existing view definition
with the new one.
Use the FORCE keyword if the view should be created regardless of whether the views base
tables exist or the owner of the schema containing the view has privileges on them. Note that

2.5. (MATERIALIZED) VIEWS

21

these conditions have to be true before any DML actions on the view can take place. By default,
or if the NOFORCE keyword is used, the view is not created if one of the base tables does not
exist or if the owner of the schema containing the view does not have the proper privileges to
execute the query associated with the view.
The views name specification is followed by an optional alias list. This alias list provides
names for the columns in the view. If this list is omitted, the columns get names generated from
the subquery. If some column in the subquery is an expression rather than a column name, an
alias must be provided.
The last part of the statement is the subquery. This subquery specifies the columns of the
view and how to retrieve the rows of the view.

2.5.2

Alter view

- ALTER - VIEW - schema - . - view - COMPILE

Contrary to other alter statements, the alter view statement is not meant to change the definition
of a view. To do that, a create view statement with the REPLACE option should be used.
The alter view statement is used to explicitly recompile an existing view. This is useful to check
if the view is still valid when the base tables or the privileges of the owner have been changed.

2.5.3

Drop view

- DROP - VIEW - schema - . - view

Use the drop view statement to remove a view from the database.

2.5.4

Create materialized view

- CREATE - MATERIALIZED - VIEW

- SNAPSHOT
?- schema - . - view

- BUILD - IMMEDIATE

- DEFERRED
? - refresh_clause

- FOR - UPDATE
- DISABLE

6


- ENABLE
? QUERY - REWRITE - AS - subquery

This create statement can be used with the keywords MATERIALIZED VIEW or SNAPSHOT.
There is no difference in semantics.
Following the view name, the build clause can be used to specify when the snapshot has to be
populated. If this is IMMEDIATE (default), the snapshot is populated immediately after creation.
If this is DEFERRED, the snapshot is populated by the next refresh operation. The refresh clause
is used to specify how and when the snapshot has to be refreshed.
By default a materialized view is not updatable. Use FOR UPDATE to indicate that the
created view should be updatable.

22

CHAPTER 2. DATA DEFINITION LANGUAGE

The rewrite clause can be used to specify that this snapshot can or cannot be used for query
rewrite. Query rewrite is a feature of the query optimizer. If a query (which does not use the
snapshot) could be executed faster by using the contents of the snapshot (instead of regenerating
it), the query optimizer will take advantage of this if query rewrite is enabled. Note that the results
of the query might be different if query rewrite is applied, depending on the refresh settings of the
snapshot. Query rewrite is disabled by default.
The refresh clause

- REFRESH ?- FAST

- COMPLETE

- FORCE

- ON - DEMAND

- COMMIT ?

- START - WITH

- NEXT
? date

- NEVER - REFRESH

?
?

The refresh clause of a create snapshot statement determines when and how the contents of the
snapshot will be adjusted to the changes in its base tables.
FAST, COMPLETE, FORCE
Use FAST to specify that the snapshot should be refreshed incrementally. Use COMPLETE to
indicate that the snapshot has to be refreshed completely (by executing the associated query).
Specify FORCE (default) to indicate that when a refresh occurs, Oracle will perform a fast (incremental) refresh if possible or a complete refresh otherwise.
ON COMMIT, ON DEMAND
If ON COMMIT is specified, a fast refresh of the snapshot will occur whenever Oracle commits a
transaction that operates on the views base tables.
ON DEMAND (default) indicates that the snapshot will be refreshed on user request only.
START WITH, NEXT
Use these options to set regular refresh times. The START WITH clause sets the first time to
refresh the snapshot. If it is omitted, the first refresh time is set to the time of creation. The
NEXT clause specifies the time interval between two consecutive refreshes.
NEVER REFRESH
Use this option to prevent the view from being refreshed with any refresh mechanism or procedure.
A refresh attempt will cause an error.

2.5.5

Alter materialized view

- ALTER - MATERIALIZED - VIEW

- SNAPSHOT
?- schema - . - view

2.6. SYNONYMS
- refresh_clause

23

- ENABLE

- DISABLE ? QUERY - REWRITE

- COMPILE
?

The alter materialized view statement is used to change the properties of a snapshot. It is clear that
most of the options for this statement are the same as in the create materialized view statement,
so they will not be explained again.
Use the keyword COMPILE to instruct Oracle to explicitly revalidate the view.

2.5.6

Drop materialized view

- DROP - MATERIALIZED - VIEW

- SNAPSHOT
?- schema - . - view

Use the drop materialized view to delete a snapshot.

2.6

Synonyms

Synonyms provide alternative names for database objects. Synonyms can be used for several goals:
Backwards compatibility: when a database is restructured, database objects will be renamed.
Instead of changing the dependent applications, a synonym can be used.
Information hiding: a synonym can be used to hide the real name and/or location of an
object.
Location transparency: with a synonym, the underlying object can be moved and renamed
without visible effects to the user. Location transparency is very useful in distributed
databases.

2.6.1

Create synonym

- CREATE - PUBLIC - SYNONYM - schema - . - synonym



6

- FOR - schema - . - object



6

- @ - dblink

If the create synonym statement begins with CREATE SYNONYM the synonym is created in a
specific schema and it will not be accessible outside this schema. If the statement begins with
CREATE PUBLIC SYNONYM, a general synonym is created. A general synonym has no schema,
so it is not allowed to specify a schema identifier before the schema name.
The object identifier after the FOR keyword specifies which object the synonym references to.

2.6.2

Drop synonym

- DROP - PUBLIC - SYNONYM - schema - . - synonym



6

24

CHAPTER 2. DATA DEFINITION LANGUAGE

Use this statement to remove a synonym.

2.7

Sequences

A sequence generates a serial list of unique integers for numeric columns in a database table.
Sequences simplify application programming by automatically generating unique numerical values
for the rows of a single table or multiple tables. For example, assume two users are simultaneously
inserting new employee rows into the EMP table. By using a sequence to generate unique employee
numbers for the EMPNO column, neither user has to wait for the other to enter the next available
employee number. The sequence automatically generates the correct values for each user. Sequence
numbers are independent of tables, so the same sequence can be used for one or more tables. After
creation, a sequence can be accessed by various users to generate actual sequence numbers.

2.7.1

Create sequence

- CREATE - SEQUENCE - schema - . - sequence


? - INCREMENT - BY

- START - WITH
? integer

- MAXVALUE - integer

- NOMAXVALUE
?

- MINVALUE - integer

- NOMINVALUE
?

- CYCLE

- NOCYCLE ?

- CACHE - integer

- NOCACHE
?

- ORDER

- NOORDER ?

Sequences have several properties that can be set by clauses in the create sequence statement:
INCREMENT BY
Specifies the interval sequence numbers. The interval can be negative or positive (but not zero).
The absolute of this value must be less than the difference between MAXVALUE and MINVALUE.
The Default interval is 1.
START WITH
By default the sequence starts with MINVALUE for ascending sequences and with MAXVALUE
for descending sequences. Use this clause if the sequence should start with another value.
MAXVALUE, MINVALUE
Use these clauses to set maximum resp. minimum value the sequence can generate. The specified
values should equal or greater resp less than the START WITH value. The MINVALUE must be
less than the MAXVALUE.

?-

2.7. SEQUENCES

25

NOMAXVALUE, NOMINVALUE
Use these clauses to indicate that MAXVALUE and MINVALUE should be default values. 1027
and 1 resp. for ascending sequences and -1 and 1026 resp. for descending sequences.
CYCLE, NOCYCLE
If the sequences cycles, it keeps generating values after reaching its maximum or minimum value.
When an ascending sequence reaches its maximum, it continues from the minimum value and vice
versa for descending sequences.
A non-cycling sequence can no longer generate values after reaching its maximum or minimum
value.
CACHE, NOCACHE
The CACHE clause specifies how many values should be preallocated for faster access. The
minimum is two.
If NOCACHE is specified, no values are preallocated.

2.7.2

Alter Sequence

- ALTER - SEQUENCE - schema - . - sequence


?- INCREMENT - BY - integer

- MAXVALUE - integer

- NOMAXVALUE
?

- MINVALUE - integer

- NOMINVALUE
?

- CYCLE

- NOCYCLE ?

- CACHE - integer

- NOCACHE
?

- ORDER

- NOORDER ?

?-

The properties of a sequence can be changed with this statement. The available options are exactly
the same as in the create sequence statement, except that the START WITH property cannot be
set here.

2.7.3

Drop sequence

- DROP - SEQUENCE - schema - . - sequence

Use this statement to drop a sequence.

26

2.8

CHAPTER 2. DATA DEFINITION LANGUAGE

Programmable objects

Most database systems nowadays offer a wide range of possibilities to enhance the database with
user programmed features. This programming is commonly done with a legacy language. In Oracle
this language is called PL/SQL where PL stands for PROCEDURAL LANGUAGE. PL/SQL code
is encapsulated in database objects that can be used in SQL statements.
It also possible to make calls to code libraries external to the database environment. Recently
(from version 8 on) Oracle introduced Java into its database environment.
Introducing the PL/SQL language here would not be appropriate. This section only explains
the SQL statements necessary to create and manage programmable database objects.

2.8.1

Stored procedures and user functions

A stored procedure is a procedure (as in common programming terminology) that is stored in the
database. It has a procedure header (or signature) consisting of a procedure name and a list of
parameters, and procedure body containing the programming code of the procedure.
A user defined function is very similar but, contrary to a stored procedure, returns a value.
Create procedure

- CREATE - OR - REPLACE - PROCEDURE - schema - . - procedure



6

- ( ? argument


- IN


- OUT

- IN - OUT ? - NOCOPY - datatype


6
6

- invoker_rights_clause

- IS
6

- AS

- ) 6

?- pl_sql_subprogram_body

- call_spec

This statement can be used to create or replace a stored procedure. After the name of the
procedure, comes the (optional) argument list. An argument can be used as input, output or
both. The keyword NOCOPY instructs Oracle to pass the argument as fast as possible (e.g. using
pass by reference instead of pass by value).
The procedure code is either a pl/sql block, or a call spec. A call spec is a call to an external
code base written in Java or C.
invoker rights clause

- AUTHID - CURRENT_USER

- DEFINER
?

This clause determines which privilege set is used when the procedure is executed. If the
current users rights are used, the procedure can only be executed by users who have the necessary

2.8. PROGRAMMABLE OBJECTS

27

privileges. If the definers rights are used, all user having the execute privilege on the procedure
can execute it (if the definer owns the necessary privileges).
Alter procedure

- ALTER - PROCEDURE - schema - . - procedure - COMPILE - DEBUG

The alter function statement explicitly recompiles a procedure. This avoids run-time recompilation.
Drop procedure

- DROP - PROCEDURE - scheme - . - procedure

Use this statement to drop a procedure.


Create function

- CREATE - OR - REPLACE - FUNCTION - schema - . - function



6

- ( ? argument

- RETURN - datatype


- IN


- OUT

- IN - OUT ? - NOCOPY - datatype


6
6

? - invoker_rights_clause

- DETERMINISTIC

- ) 6


? - AS

6

- IS ?- pl_sql_function_body

- call_spec

Use this statement to create or replace a function. The syntax and of this statement the same as
for the create procedure statement, except for some additional clauses.
One additional clause is the RETURN clause to specify the return type of the function.
Use the keyword DETERMINISTIC if the result of the function is fully determined by the
input arguments. This will allow the query optimizer to use stored result (for instance from
function based indexes or materialized views).
Alter function

- ALTER - FUNCTION - schema - . - function - COMPILE - DEBUG

28

CHAPTER 2. DATA DEFINITION LANGUAGE

The alter function statement explicitly recompiles a function. This avoids run-time recompilation.
Drop function

- DROP - FUNCTION - schema - . - function

Use this statement to drop a function.

2.8.2

Packages

Related procedures and functions can be stored together in a package. A package object only
contains the declaration of the package. The implementation should be stored in a package body
object.
Create package

- CREATE - OR - REPLACE - PACKAGE - schema - . - package



6

6
- invoker_rights_clause

- IS
6

- AS

? pl_sql_package_spec

Use this statement to create a package specification. The pl sql package spec clause contains only
the declaration of the procedures, functions and data structures of the package.
See section 2.8.1 for the invoker rights clause.
Create package body

- CREATE - OR - REPLACE - PACKAGE - BODY - schema - . - package



6

- IS

- AS

? pl_sql_package_body

This statement creates the body of a package.


Alter package

- ALTER - PACKAGE - schema - . - package - COMPILE - DEBUG


- PACKAGE

- SPECIFICATION

- BODY
?

This statement can be used to recompile the package. To change the code of a package, use the
OR REPLACE option of the create package and the create package body statements.

2.8. PROGRAMMABLE OBJECTS


Drop package

29

- DROP - PACKAGE - schema - . - package

Use this statement to drop a package (specification and body).

2.8.3

Triggers

Triggers are stored procedures, but they cannot be executed explicitly. Instead, they are executed
(triggered) by a given event (e.g. updates in tables or views) in the database.
Create trigger

- CREATE - OR - REPLACE - TRIGGER - schema - .


- BEFORE

- AFTER


- INSTEAD - OF ?


- dml_event_clause

OR

? ddl_event

OR

? database_event

- referencing_clause

? ON
- schema - . - SCHEMA

6

- DATABASE
??

- WHEN - ( - condition - )
- pl_sql_block


6
- call_procedure_spec

Use this statement to create or replace a trigger. The keywords BEFORE, AFTER and INSTEAD
OF determine when the trigger is executed. With INSTEAD OF, the event will be replaced by
this trigger. BEFORE and AFTER cannot be used for DML events on views, INSTEAD OF can
only be used for DML events on views.
Triggers can be triggered on DDL or on DML events. For more information on DDL event
triggers, see the Oracle SQL Reference.
dml event clause ::=
OR

?- DELETE

- INSERT


- UPDATE - OF ? column

?- OF - schema - .
- table
6
6
- view

30

CHAPTER 2. DATA DEFINITION LANGUAGE

Every DML update event (insert, delete and update) can trigger an event. If necessary, several
events can trigger the same trigger. Update triggers can be limited to one or more columns.
referencing clause ::=


- REFERENCING ?- OLD - AS - old

6

- NEW - AS - new
6


- PARENT - AS - parent



- FOR - EACH - ROW

6
6

Use this clause to specify correlation names for the old and new values of the updated data.
These names can be used in the trigger body.
WHEN
The when clause contains a condition. The trigger only launches if this condition is satisfied.
Alter trigger

- ALTER - TRIGGER - schema - . - trigger

- ENABLE

- DISABLE

- COMPILE - DEBUG
?

Use this statement to enable, disable or recompile a trigger.


Drop trigger

- DROP - TRIGGER - schema - . - trigger

Use this statement to drop a trigger.

2.9

Users, roles and privileges

Besides pure data storage, access control is an important issue in database systems. Access control
consists of two parts: authentication of the users and privilege assignment.
Authentication
Oracle allows three kinds of authentication:
Local: The passwords are stored and maintained by the Oracle database. This is a good
option if user access the system only through the Oracle database.
Externally: The authentication is not done by Oracle itself, but by an external service such
as the operating system it runs in. This allows the users to have the same password for the
oracle database and the system environment.

2.9. USERS, ROLES AND PRIVILEGES

31

Globally: The authentication is done by an enterprise directory service. This allows the
user to use the same password for several databases and related services.
Privilege assignment
A privilege is the right to do something in the database system. A user cannot launch a
database action if he/she does not have the proper privileges. For example to launch a select
statement, you need the select privilege on all the tables and views that are involved in the query.
As there are a lot of DDL statements, and since DML privileges can be assigned on per object
basis, it is clear that it is a huge job to manage the privileges in a database system, especially in
large environments.
That is why roles are useful. A role is a named set of privileges. A role can be granted to
a user or to another role. This means that the grantee (user or role) receives all the privileges
included in the granted role.
Typically a role includes the privileges that correspond with the needs of a group of users or
with the privileges necessary to run a database application.

2.9.1

Create user


- CREATE - USER - user - IDENTIFIED - BY - password

- EXTERNALLY


- GLOBALLY - AS - - external_name - ?

?- DEFAULT - TABLESPACE - tablespace

- TEMPORARY - TABLESPACE - tablespace

- QUOTA - integer - K

- M ?


- UNLIMITED
? ON - tablespace

- PROFILE - profile

- PASSWORD - EXPIRE

- ACCOUNT - LOCK

- UNLOCK ?

?-

After the user name comes the specification of the identification method. These methods correspond with the methods mentioned above. Then properties of the user can be set:
DEFAULT TABLESPACE
Use this property to set the default tablespace for the user. This is the tablespace where objects
created by this user are stored by default. By default, the default tablespace is SYSTEM.
TEMPORARY TABLESPACE
This property specifies the tablespace where temporary objects are stored by default. This property defaults to SYSTEM too.
QUOTA

32

CHAPTER 2. DATA DEFINITION LANGUAGE

With a quota clause the user is granted storage space in the specified tablespace. The granted
space can be unlimited or be a limited space specified in kilobyte or megabyte.
PROFILE
A profile is a set of properties that can be associated with users. A profile contains runtime settings
like the maximum number of simultaneous connections per user, available cpu time, available cache
space, etc...
If this clause is omitted, the new user gets the default profile. Statements exist to create, alter
and drop profiles, but they are not explained in this tutorial.
PASSWORD EXPIRE
This clause forces the user to change its password at first login.
ACCOUNT LOCK, UNLOCK
ACCOUNT LOCK disables the account until the account is unlocked. ACCOUNT UNLOCK
enables the access to the account.

2.9.2

Alter user

- ALTER - USER - user


?- IDENTIFIED - BY - password

- EXTERNALLY


- GLOBALLY - AS - - external_name - ?

- DEFAULT - TABLESPACE - tablespace

- TEMPORARY - TABLESPACE - tablespace

- QUOTA - integer - K

- M ?


- UNLIMITED
? ON - tablespace

- PROFILE - profile

- PASSWORD - EXPIRE

- ACCOUNT - LOCK

- UNLOCK ?
?

Use this statement to change the properties of a user. The semantics of the clauses is the same as
in the create user statement. There is one new clause:

2.9.3

Drop user

- DROP - USER - user - CASCADE

Use this statement to remove a user.

2.9. USERS, ROLES AND PRIVILEGES

2.9.4

33

Create role

- CREATE - ROLE - role

- NOT - IDENTIFIED


- IDENTIFIED - BY - password

- EXTERNALLY

- GLOBALLY

??6

A role can be created with or without authentication. In all cases, a role is only accessible by users
which have been granted the role. When an authenticated role is created, actually a new user
(with special behavior) is created. The authentication modes are the same as for normal users.

2.9.5

Alter role

- ALTER - ROLE - role

- NOT - IDENTIFIED


- IDENTIFIED - BY - password

- EXTERNALLY

- GLOBALLY

??6

Use this statement to change the identification method of a role.

2.9.6

Drop role

- DROP - ROLE - role

Use this statement to remove a role.

2.9.7

Grant privilege

- GRANT - grant_system_privlege_and_role_clause

- grant_object_privilege_clause

A grant privilege statement grants one or more privileges to a given user or role. The statement
syntax is divided in two parts. The first part is to assign system and role privileges, the second
part is to assign object privileges. Both parts have a common grantee clause. Privileges can be
granted to more than one user/role at once. If the grantee is PUBLIC, all users get the granted
privilege.

34

CHAPTER 2. DATA DEFINITION LANGUAGE

System and role privileges

?- system_privilege

- role
,



- ALL - PRIVILEGES ?- TO ?- user


- role

- PUBLIC ? - WITH - ADMIN - OPTION

A system privilege is a privilege that is not related with a specific object in the database. These
privileges are mostly related with DDL statements. Role privileges give the grantee the right to
use a role.
ALL PRIVILEGES is a shortcut to assign all the system privileges in one statement.
Use the WITH ADMIN OPTION to indicate that the grantee has the right to grant or revoke
the granted privilege to other users or roles. If the granted privilege is a role, the grantee can also
change the role privileges.
Object privileges

?- object_privilege
,

- ALL - PRIVILEGES
?- ( ? column - )

6


- ON - schema - . - object - TO ?- user


- role

- PUBLIC ? - WITH - ADMIN - OPTION

Object privileges are related to one specific object in the database (e.g. the right to select rows
from a table).
The object clause (after the keyword ON) specifies the object for which the privilege is granted.
If the object is a table or view, the INSERT, REFERENCES or UPDATE privilege can be limited
to a subset of the columns.
Use ALL PRIVILEGES to give the grantee the full right to use the specified object. The
WITH GRANT OPTION gives the grantee the right to give other users the same privilege.

2.9.8

Revoke privilege

- REVOKE ?- revoke_system_privileges_and_role_clause

- revoke_object_privleges_clause

?-

2.10. ORACLE BUILT-IN DATATYPES

35

The revoke statement is the counterpart of the grant statement. Instead of allowing a user to do
something it will rather prohibit
a user
to do so.
,

?- system_privilege

- role
,

- ALL - PRIVILEGES ?- FROM ?- user



- role

- PUBLIC ?

Just like the grant statement, this statement can be used for system privileges and object
privileges. The options are mainly the (although they have the opposite effect).
System privileges

?- object_privilege
,

- ALL - PRIVILEGES
?- ( ? column - )

6

6
Object privileges

- ON - schema - . - object - FROM ?- user


- role

- PUBLIC ? - CASCADE - CONSTRAINTS

The CASCADE CONSTRAINTS option can only be used when REFERENCES privileges are
revoked. As a result, all reference constraints created by this user using the reference privilege
will be dropped.

2.10

Oracle built-in datatypes

Built-in Datatype
VARCHAR2(size)
NVARCHAR2(size)

Description
Variable length character string having maximum length size bytes.
Maximum size is 4000, and minimum is 1. size has to be specified.
Variable length character string having maximum length size characters
or bytes, depending on the choice of national character set. Maximum
size is determined by the number bytes required to store each character,
with a maximum limit of 4000 bytes. size has to be specified.
Table 2.1: Built-in datatypes

36

CHAPTER 2. DATA DEFINITION LANGUAGE

Built-in Datatype
VARCHAR2(size)
NUMBER(p, s)

LONG
DATE
RAW(size)
LONGRAW
ROWID

CHAR(size)
NCHAR(size)

CLOB
NCLOB
BLOB
BFILE

Description
Variable length character string having maximum length size bytes.
Maximum size is 4000, and minimum is 1. size has to be specified.
Numbers are stored in BCD format. p determines the number of digits
and s determines the scale. p can range from 1 to 38 and s from -84 to
127.
Character data of variable length up to 2 gigabytes, or 231 1 bytes.
Valid data range from January 1, 4712 BC to December 31, 9999 AD.
Raw binary data of size bytes. sizehas to be specified.
Maximum size is 2000.
Raw binary data of variable length up to 2 gigabytes.
Hexadecimal string representing the unique address of a row in its table.
This datatype is primarily for values returned by the ROWID pseudocolumn.
Fixed-length character data of length size bytes. Maximum length is
2000 bytes. Default and minimum size is 1 byte.
Fixed-length character string of length size characters or bytes,
depending on the choice of national character set. Maximum size is
determined by the number bytes required to store each character, with a
maximum limit of 2000 bytes. Default and minimum size is 1 character.
A character large object containing single byte characters.
The maximum size is 4 gigabyte.
A character large object containing multi-byte characters. Maximum size
is 4 gigabyte. Stores national character set data.
A binary large object. Maximum size is 4 gigabyte.
Contains a locator for a large binary file stored outside the database.
Table 2.2: Built-in datatypes (continued)

2.11

The Data Dictionary

2.11.1

Introduction

Somewhere, a database system must keep the information about the structure of the database.
Oracle (and most other relational database systems) uses tables to keep this information. These
tables are exposed to the user through a number of views.
The collection of tables and views that contain information about the database structure (meta
data) is called the Data Dictionary. The Data Dictionary is always stored in the System tablespace.
Oracle divides the Data Dictionary in a static and a dynamic part. The static part contains the
information about the structure of the database. The dynamic part is used to keep track of the
performance of the database. Only the Static Data Dictionary will be discussed here.
The Data Dictionary is updated by the system when a DDL statement is executed. Users
should never update the Data Dictionary directly because this can result into system failure and
loss of data. To retrieve data from the Data Dictionary, use standard select statements (see section
3.1).
Only the most important parts of the dictionary will be discussed here. It are all views defined
for the users comfort, because the dictionary tables are normalized.
All of these views have three instances only different in the range of their content (not in the
type of content). The three instances have different prefixes that indicate this range:
An ALL view displays all the information accessible to the current user, including information
from the current users schema as well as information from objects in other schemas, if the
current user has access to those objects by way of grants of privileges or roles.

2.11. THE DATA DICTIONARY

37

A DBA view displays all relevant information in the entire database. DBA views are intended
only for administrators. They can be accessed only by users with the SELECT ANY TABLE
privilege.
A USER view displays all the information from the schema of the current user. No special
privileges are required to query these views.

2.11.2

Overview

This section gives an overview of the most important views in the Data Dictionary. A description
of the columns of these views can be found in
ALL ARGUMENTS, DBA ARGUMENTS, USER ARGUMENTS
These views contain information about the parameters of the stored procedures and functions.
ALL CATALOG, DBA CATALOG, USER CATALOG
The CATALOG views give a list of all tables, views, synonyms and sequences in the scope determined by the prefix.
ALL COL COMMENTS, DBA COL COMMENTS, USER COL COMMENTS
This view stores the comments attached to table or view columns.
ALL COL PRIVS, DBA COL PRIVS, USER COL PRIVS
These views show the privileges on single columns.
ALL CONSTRAINTS, DBA CONSTRAINTS, USER CONSTRAINTS
These views give information about constraints on tables.
ALL IND COLUMNS, DBA IND COLUMNS, USER IND COLUMNS
Describe the columns of indexes on tables.
ALL IND EXPRESSIONS, DBA IND EXPRESSIONS, USER IND EXPRESSIONS
Describe the expressions of function-based indexes on tables.
ALL INDEXES, DBA INDEXES, USER INDEXES
Contain information about indexes defined on tables.
ALL MVIEWS, DBA MVIEWS, USER MVIEWS
Describe materialized views.
ALL SEQUENCES, DBA SEQUENCES, USER SEQUENCES
Contain information about sequences.
ALL SNAPSHOTS, DBA SNAPSHOTS, USER SNAPSHOTS
See ALL MVIEWS, DBA MVIEWS, USER MVIEWS.

38

CHAPTER 2. DATA DEFINITION LANGUAGE

ALL SOURCE, DBA SOURCE, USER SOURCE


Contains the source code for programmed objects of type: PROCEDURE, PACKAGE, FUNCTION, PACKAGE BODY and TRIGGER.
ALL SYNONYMS, DBA SYNONYMS, USER SYNONYMS
Describe synonyms.
ALL TAB COLUMNS, DBA TAB COLUMNS, USER TAB COLUMNS
These views show information about the columns of tables and views.
ALL TAB COMMENTS, DBA TAB COMMENTS, USER TAB COMMENTS
Show the comments associated with tables.
ALL TABLES, DBA TABLES, USER TABLES
These views contain information about the tables in the database.
ALL TAB PRIVS, DBA TAB PRIVS, USER TAB PRIVS
List information about user or role privileges on tables.
ALL TRIGGERS, DBA TRIGGERS, USER TRIGGERS
Gives information about the triggers in the database.
ALL TRIGGER COLS, DBA TRIGGER COLS, USER TRIGGER COLS
Give an overview of the columns used in triggers.
ALL UPDATABLE COLUMNS, DBA UPDATABLE COLUMNS,
USER UPDATABLE COLUMNS
Give a list of columns that are resp. updatable by the current user, updatable by the database
administrator and owned and updatable by the current user.
ALL USERS, DBA USERS, USER USERS
Gives a list of users. These views do not list the properties of the users.
ALL VIEWS, DBA VIEWS, USER VIEWS
Contain information about views.

Chapter 3

Data Manipulation Language


Basically there are four operations to manipulate the data through SQL: SELECT, INSERT,
DELETE and UPDATE. The following sections will explain the syntax and the semantics of each
of them.

3.1

Retrieving data from the database

The SELECT statement is used to retrieve data; it does not change the content of the database.
Figure 3.1 shows the syntax of a select statement.
A select statement has several clauses. Some clauses are required, others are optional as can
be seen from the syntax diagram. The following sections explain the use and semantics of each
clause.

- SELECT
- DISTINCT

- UNIQUE

- ALL
? - *

6

? - schema - .
- table
6
- view

- snapshot ? .*

- expr
- AS - c_alias
??
6
6

- FROM ? query_table_expression
- where_clause
? group_by_clause

6
6
- UNION - ALL
6
- INTERSECT
- MINUS

? ( - subquery - )
- order_by_clause

6
Figure 3.1: Syntax of a SELECT statement
39

40

CHAPTER 3. DATA MANIPULATION LANGUAGE

- schema - .
- table
6
- view
- snapshot

?- @ - dblink

- ( - subquery - )

6
?- t_alias

Figure 3.2: query table expression

3.1.1

The select clause

The select clause is the first part of a select statement. It specifies the fields in the result of the
query. This can be done in three different ways.
The first option is to put * in the select clause. This option selects all the fields that are
in the scope of the query (specified by the from clause). With this option you cannot select any
additional fields.
The second option is to select all the fields of one table, view or snapshot. This is done by
specifying the tablename (or alias) suffixed by .*, and (if necessary) prefixed by a schema name.
Finally, the third way of specifying fields is to use expressions. The construction of expressions
is discussed in section 3.2. Each field can have an alias. This alias is used as a fieldname in the
result of the query.
The keywords UNIQUE, DISTINCT and ALL in the beginning of the select clause are used
to influence the output of rows. If you dont want the query to show duplicate rows in the result,
use DISTINCT or UNIQUE (which are synonyms). By default duplicate rows are shown, but the
keyword ALL can be used with the same result.

3.1.2

The from clause

The from clause specifies the scope of the query, i.e. the tables (or table equivalent objects, such
as views and subqueries) that are involved in the query. These tables are specified in a comma
separated list of query table expressions. Figure 3.2 shows the syntax for these expressions.
Note that it is possible to use subqueries directly in the from clause (most SQL implementations
dont allow this). A subquery in the from clause is called an inline view.

3.1.3

The where clause

The optional where clause contains a condition, which follows the WHERE keyword, that restricts
the rows selected by the query to those that satisfy the condition. The construction of a condition
is explained in section 3.3. The use of outer join conditions is explained in the next section.
The where clause can only contain so called single row conditions. These are conditions that
apply to a single row (of input), compared to group conditions that belong in the having clause
(see section 3.1.5 about grouping).
Although it is not possible according to the syntax diagram (taken from the Oracle 8i SQL Reference), outer join conditions and normal conditions can be combined using compound conditions
(see section 3.3.8).

- WHERE - condition

- outer_join
Figure 3.3: where clause

3.1. RETRIEVING DATA FROM THE DATABASE

3.1.4

41

Joining tables

To be able to construct correct queries, it is very important to understand how the data of different
tables are combined and how to influence this combination by defining the correct join conditions.
If the from clause of a query specifies more than one table, the rows are combined with each
other as a Cartesian product. This means that every row of one table is combined with every row
of every other table in the from clause.
The inner join of two tables
In most of the queries where more than one table is needed, we dont want to include all the rows
of the Cartesian product in the result. Most queries require an inner join of the tables.
A natural join of two tables means that only those rows are included where a key value of
the first table corresponds to a key value of the second table (e.g. a primary key - foreign key
correspondence). This restriction can be obtained by adding so called join conditions to the
where clause. A join condition looks like a = b with a the key attribute of one table and b the
corresponding key attribute of the other table.
If the key used to join the tables is composed (this means that the key exists of more than one
field), a join condition for each attribute of the key must be added.
The outer join of two tables
The outer join operation is based on the same principles as the natural join operation. The rows
of one table are combined with the rows of the other table based on an equivalence condition.
But in contrast to the natural join, the outer join is asymmetric. An outer join will return all
rows that match the join condition completed with all rows of one table that have no match in the
other table. The fields taken from the other table (the outer table) are filled with NULL values
in the result.


- table1 - . - column - = - table2 - . - column - ( - + - )

- ( - + - ) - = - table2 - . - column ?

Figure 3.4: Outer join condition


Figure 3.4 shows the syntax of an outer join condition. Use the + sign to mark the key field
of the outer table. Note that the syntax to construct outer joins varies a lot between different
database systems.
Self join
Sometimes it is necessary to join a table with itself. In this case, each occurrence of the table is
handled like a different table be it with the same structure and content.
The join of a table with itself is called a self join. This can be a natural or an outer join.

3.1.5

Grouping and aggregate functions

When grouping is used, the rows that pass through the where clause (if present) are put together
into groups of rows so that all rows of each group have the same value for the expressions mentioned
in the grouping clause. Each group is then summarized (aggregated) to one single row. Aggregate
functions can be used to compute single row results from groups of values. See section 3.2.3 for
an overview of the most important aggregate functions.
It should be clear that the use of grouping has implications for the fields of the select clause;
e.g. it is not allowed for the select clause to contain fields that (possibly) have different values for
rows of the same group.

42

CHAPTER 3. DATA MANIPULATION LANGUAGE


- GROUP - BY
? expr

? expr

- CUBE
,

- ROLLUP ?( ? expr - ) ?- HAVING - condition

Figure 3.5: The GROUP BY clause

The ROLLUP option


The ROLLUP option is used to produce subtotal values. A normal select statement with grouping
produces one row for each group. With the ROLLUP option some super aggregate rows, that
aggregate the data at higher grouping levels are added.
The having clause
The having clause has a similar function as the where clause. The main difference is that the
conditions of the where clause are evaluated before the grouping takes place whereas the conditions
in the having clause are evaluated after grouping the rows. This means that conditions that contain
aggregate functions go in the having clause.

3.1.6

Sorting the result of the query

In theory, the result of a query is a new relation, and by definition the tuples of a relation are
unordered. In practice however its often useful to have the results of a query ordered in some
way.


- ORDER - BY ?- expr


- position

- c_alias
? - ASC

- DESC ? - NULLS - FIRST

- NULLS - LAST
?

6
The order by clause can contain more than one field. If so, the precedence of the fields goes
from left to right. A sorting field can be every expression or the index of a field in the select clause.
The sorting order can be ascending (keyword ASC) or descending (keyword DESC). The default
sorting order is ascending. The place of null values can be specified by the use of the keywords
NULLS FIRST or NULLS LAST. The default is NULLS LAST for ascending order and NULLS
FIRST for descending order.

3.2

Expressions

As you can see in figure 3.6 there exist several types of expressions. It should be noted that not all
of these types are allowed in all situations. Furthermore, you have to make sure that the datatype

3.2. EXPRESSIONS

43

of the result of the expression is useful in its context. For instance, if the result of an expression
is added with a number, this result has to be numeric.
- simple_expression
- compound_expression
- built_in_function_expression
- user_defined_function_expression
- CAST_expression
- object_access_expression
- DECODE_expression
- CASE_expression
- expression_list

Figure 3.6: Different kind of expressions

3.2.1

Simple expressions

- schema - .
- table
6
- view
- snapshot

?.
- column
6
- pseudocolumn

- text
- number

- sequence - . - CURRVAL

- NEXTVAL ?

- NULL

Simple expressions can be each of the following:


Column reference
Refers to a (pseudo)column in the scope of the query.
Literal
Literal values can be text (string between single quotes) or numeric.
Sequence reference
Calls the current or the next value of the sequence at hand. Calling the next value of a sequence
increases this sequence with one step.
NULL
Represents an empty field.

44

CHAPTER 3. DATA MANIPULATION LANGUAGE

3.2.2

Compound expressions

3.2.3

Function expressions

- ( - expr - )

- +

- - ? expr

- expr - *

- /

- +

-

- || ? expr ?

A compound expression is used to combine one or more expressions with an operator. +, -, *, /
are arithmetic operators, k is the string concatenation operator.

- schema - .
- package - . - function
6
6
- user_defined_function

- (
- DISTINCT
,


- ALL
? ?- expr

6
- subquery

?- @ - dblink

?- ) 6

Function expressions call a built-in or user defined function. All functions should be single row
functions (this is: returning one value rather than a collection of values). The number and the
type of the provided parameters has to match the function definition.
Aggregate functions summarize a group of values into one value . The keywords DISTINCT and
ALL can be used to adjust the behavior of some aggregate functions. For instance COUNT(ALL
price) and COUNT(DISTINCT price) will return different results if duplicate prices occur, whereas
MAX(ALL price) and MAX(DISTINCT price) will always return the same value.
The following sections give an overview of the most common built-in functions of Oracle SQL.
Number functions
ABS(n)
BITAND(m,n)
CEIL(n)
COS(n)
EXP(n)
FLOOR(n)
LN(n)
LOG(m,n)
MOD(m,n)

Absolute value of n.
Bitwise AND
Computes the ceiling of a real number. Returns an integer.
Cosinus
Returns e raised to the nth power
Computes the floor of a real number. Returns an integer.
Takes the natural logarithm of n.
Returns the logarithm base m of n.
Returns the remainder of m divided by n.

3.2. EXPRESSIONS
POWER(m,n)
ROUND(n [,m])
SIGN(n)
SIN(n)
SQRT(n)
TAN(n)
TRUNC(n [,m])

45
Returns m raised to the nth power.
(if m is negative, n must be an integer)
Rounds n up to m places right of the decimal point
(default for m is 0).
Returns -1, 0, or 1 according to the sign of n.
Sinus.
Square root.
Tangens.
Truncates n to m places right of the decimal point
(default for m is 0).

Character functions returning characters


CHR(n)
CONCAT(c,d)
LOWER(c)
LTRIM(c)
REPLACE(c,s,r)
RTRIM(c)
SUBSTR(c,m [,n])
TRANSLATE(c,f ,t)
TRIM(c)
UPPER(c)

Returns the character with binary representation of n.


Concatenates two character strings. This function is equivalent to the
concatenation operator k.
Change all characters of c to lower case.
Removes blanks from the left of c.
Returns c with all occurrences of s replaced by r.
Removes blanks from the right of c.
Returns a portion of c beginning at character m of n characters long.
If n is omitted, all characters to the end of c are returned.
Every occurrence of a character of f in c is replaced by its
corresponding character in t.
Remove both leading and trailing blanks from c.
Change all characters of c to upper case.

Character functions returning numbers


ASCII(c)
INSTR(s1,s2 [,p [,n]])

LENGTH(c)

Returns the numeric value of the first character of c in the character set used.
Returns the positions of the occurrence of substring s2 in string s1.
p specifies a position to begin the search,
n specifies to look for the nth occurrence of s2.
Returns the number of characters of c.

Date functions
ADD MONTHS(d,n)
LAST DAY(d)
NEXT DAY(d,c)
ROUND(d [,u])
SYSDATE
TRUNC(d [,u])

Adds n months to date d.


Returns the date of the last day of the month that contains d.
Returns the date of the first weekday c following d.
Rounds d to the unit u (e.q. month).
Default for u is DDD (day).
Returns the current date and time.
Truncates d to the unit u (e.q. year)
Default for u is DDD.

Conversion functions
TO CHAR(d [,f ])
TO CHAR(n [,f ])
TO DATE(c [,f ])

Converts a date d to a string using format string f .


Converts a number to a string using format string f .
Converts a character string to a date using the format string f .

Table 3.1 shows the most important elements that can be used in format specifiers with date
functions.

46

CHAPTER 3. DATA MANIPULATION LANGUAGE


Element
- / , . ; : text
SS
SSSSS
MI
HH
HH12
HH24
D
DAY
DY
DD
DDD
IW
WW
W
MM
MON
MONTH
RM
Q
IYY, IY, I
IYYY
J
YEAR, SYEAR
YYYY, SYYYY
YYY, YY, Y

Description
Punctuation and quoted text is reproduced in the result.
Second (00-59).
Seconds past midnight (0-86399).
Minute (00-59).
Hour of day (01-12).
Hour of day (01-12).
Hour of day (00-23).
Day of week (1-7).
Name of day, padded with blanks to length of 9 characters.
Abbreviated name of day.
Day of month (01-31).
Day of year (001-366).
Week of year (01-52 or 01-53) based on the ISO standard.
Week of year (01-53) where week 1 starts on the first day
of the year and continues to the seventh day of the year.
Week of month (1-5) where week 1 starts on the first day
of the month and ends on the seventh.
Two-digit numeric abbreviation of month (01-12; JAN = 01)
Abbreviated name of month.
Name of month, padded with blanks to length of 9 characters.
Roman numeral month (I-XII; JAN = I).
Quarter of year (1, 2, 3, 4; JAN-MAR = 1)
Last 3, 2, or 1 digit(s) of ISO year.
4-digit year based on the ISO standard.
Julian day; the number of days since January 1, 4712 BC.
Year, spelled out. S prefixes BC dates with -.
4-digit year. S prefixes BC dates with -.
Last 3, 2, or 1 digit(s) of year.
Table 3.1: Format strings in date functions

Aggregate functions
AVG(n)
COUNT(x)
MAX(x)
MIN(x)
STD DEV(n)
SUM(n)
VARIANCE(n)

3.2.4

Computes the average of a set of numbers.


Counts the number of elements encountered.
Returns the maximum value of a group.
Returns the minimum value of a group.
Computes the standard deviation of a group of numbers.
Returns the sum of a group of numbers.
Computes the variance of group of numbers.

CAST expressions

- CAST - ( - expr

- ( - subquery - )


- MULTISET - ( - subquery - ) ? AS - type_name - )

A cast expression converts a value from one built-in datatype to another:

3.3. CONDITIONS

47

Of course it is not possible to do every casting, the table 3.2 shows what kind of conversions
have been supported. On the other hand, not every casting needs a casting expression, in some
situations, casting will occur automatically.
from/
to
CHAR,VARCHAR2
NUMBER
DATE
RAW
ROWID,UROWID
NCHAR,NVARCHAR2

CHAR,
VARCHAR2
X
X
X
X
X

NUMBER
X
X

DATE
X

RAW
X

ROWID,
UROWID
X

NCHAR,
NVARCHAR2

X
X
X

X
X

Table 3.2: Casting built-in datatypes

3.2.5

DECODE expressions

- DECODE - ( - expr - , ? search - , - result

- , - default

- )6

DECODE expressions are used to make a mapping of values. The first argument is an expression. The following arguments are (search, result) pairs. The evaluation of the first argument is
compared with the search values of these pairs (in left to right order). If a match is found, the
result value of the pair is returned. The last argument is an optional default value. This value is
returned if no matching search value is found. If there is no matching search value and the default
value is omitted, the result will be null.

3.2.6

CASE expressions

- CASE ? WHEN - condition - THEN - expr

- ELSE - expr


- END 6

CASE expressions are used to make the content of field dependent on some condition(s). The
CASE keyword is followed by one or more when - then clauses. The condition of the first when
clause is evaluated, if it is true, the expression of the then clause is evaluated else the condition of
the next when clause (if present) is evaluated, and so on. If the last condition fails, the expression
of the else clause is evaluated; if the else clause is omitted the result is null.

3.3

Conditions

Conditions are used at several places in an SQL statement. In fact, conditions are boolean expressions.

48

CHAPTER 3. DATA MANIPULATION LANGUAGE


- simple_comparison_condition
- group_comparison_condition
- membership_condition
- range_condition
- NULL_condition
- EXISTS_condition
- LIKE_conditon
- compound_condition

Figure 3.7: Different kind conditions

3.3.1

Simple comparison conditions

- =


- !=


- ^=


- <>

- >

- <


- >=


- <= ?- expr

- ( - subquery - ) ?

- expr_list - =


- !=


- ^=

- <> ? ( - subquery - ) ?

- expr

Simple conditions evaluate relational operators. They compare the results of two expressions.
With a simple comparison condition you can do single value or multi value (tuple) comparisons.
A tuple comparison compares the corresponding values of each each tuple (expression list). The
result will be true if and only if all comparisons are true. Note that only single-row subqueries are
allowed.

3.3. CONDITIONS

3.3.2

49

Group comparison conditions

- =


- !=


- ^=


- <>

- >

- <


- >=


- <= ?- ANY

- SOME


- ALL
?- expr_list

- ( - subquery - ) ?

- expr_list - =


- !=


- ^=


- <> ?- ANY

- SOME
,


- ALL
? ( ?- expr_list

- subquery
?- ) ?

- expr

Group comparison conditions are used to compare one value (or a value list) with each element of
a set of values (or a set of value lists). The keywords ALL, ANY and SOME determine when the
expression is true or false.
If the keyword ANY or SOME is used the expression is true if and only if at least one comparison
is true. This implies that the result is false if the subquery returns no rows.
If the keyword ALL is used the expression is true if and only if all comparisons are true. This
implies that the result is true if the subquery returns no rows.

3.3.3

Membership conditions

- NOT - IN - expr_list
6

- ( - subquery - ) ?


- expr_list - NOT - IN - ( ?- expr_list
6

- subquery
?- ) ?

- expr

50

CHAPTER 3. DATA MANIPULATION LANGUAGE

Membership conditions are used to test if a value (or value list) belongs (or does not belong) to
the result set of a subquery or a provided value (or value list) set.

3.3.4

Range conditions
- expr


- NOT - BETWEEN - expr - AND - expr 6

A range conditions is true if the value of the first expression is greater or equal than the value of
the second expression and if it is lower or equal than the value of the third expression.
In fact
expr1 BETWEEN expr2 AND expr3
means the same as
expr1 >= expr2 AND expr1 <= expr3
. if the evaluation of expr1 has no side effects.

3.3.5

Null conditions

- expr - IS - NOT - NULL 6

Null conditions are used to test if an expression is NULL or not.

3.3.6

Exists conditions


- EXISTS - ( - subquery - )

Exists conditions are used to test if the result set of a subquery is empty or not.

3.3.7

Like conditions
- char

- NOT - LIKE - char


6

- ESCAPE - char

Like conditions compare strings to a string pattern. Oracle has only two wildcard characters that
can be used in the pattern string: % (zero or more characters) and (exactly one character).

3.3.8

Compound conditions

- ( - condition - )


- NOT - condition


- condition - AND


- OR
? conditon

A combined condition is a combination of other conditions through brackets and/or boolean operators.

3.4. INSERTING DATA INTO THE DATABASE

3.4

51

Inserting data into the database

- INSERT - INTO - DML_table_expression

- ( ? column

- )
- value_clause
6
- subquery

Insert statements are used to create new data rows. First you have to specify where the new rows
have to be inserted. In most cases this will be a table or view, but it is also possible to use a
subquery.

- schema - .
- table
6
- view

- snapshot ?- @ - dblink

- ( - subquery - )
?- t_alias

6
Figure 3.8: DML table expression
The next part of the insert statement is the column list. This list contains the column names
that the insert statement provides values for. The other columns of the table (view, snapshot,
etc.) are filled with default values if present or null values else. If the column list is omitted, it is
assumed that the insert statement provides values for all columns.
There are two ways to provide the inserted data: the value clause or a subquery.

3.4.1

The value clause


- VALUES - ( ?- expr


- subquery

?- )

The value clause contains one value for each column in the column list. If the column list is
omitted, the value clause should contain a value for each column. Note that insert statements
with a value clause insert just one row.

3.4.2

Using a subquery

To insert more than one row at a time a subquery should be used. This query should have a
corresponding column for each column in the column list of the insert statement.
The new inserted rows are stored in the order specified by the order by clause of the subquery.
The order of the old rows is not changed and the new rows are not merged between.

3.5

Changing existing data

- UPDATE - DML_table_expression - set_clause

- where_clause

52

CHAPTER 3. DATA MANIPULATION LANGUAGE

With an update statement it is possible to change the data in a table (view, snapshot, etc.). An
update statement doesnt add or delete rows, it only changes existing rows.
After the specification of the table that has to be updated (see section 3.4 for the syntax of
DML table expression) comes the set clause. This clause tells the query engine which fields have
to be updated and how to compute their new values. Only single row subqueries can be used in
the set clause.

- SET ?- ( ? column - ) - = - ( - subquery - )



- column - = - expr

- ( - subquery - ) ?
?

Figure 3.9: set clause


Use the where clause to restrict the rows that are updated. If the where clause is omitted, all
rows of the table are updated, otherwise only those rows that satisfy the condition in the where
clause are updated.

3.6

Deleting data from the database

- DELETE - FROM - DML_table_expression

- where_clause

Use a delete statement to remove rows from a table. See section 3.4 for the syntax of
DML table expression. Only the rows that satisfy the condition in the where clause are deleted.
If the where clause is omitted, all rows are deleted.

S-ar putea să vă placă și