52
Computer Science Laboratory Ghent University, Faculty of Engineering Introduction to Oracle SQL October 2001

Tutorial de SQL Para Oracle

Embed Size (px)

DESCRIPTION

Tutorial de SQL para Oracle

Citation preview

Page 1: Tutorial de SQL Para Oracle

Computer Science Laboratory

Ghent University, Faculty of Engineering

Introduction to Oracle SQLOctober 2001

Page 2: Tutorial de SQL Para Oracle

2

Page 3: Tutorial de SQL Para Oracle

Contents

1 Introduction 51.1 An Oracle database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2 Data Definition Language 72.1 Databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

2.1.1 Create database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.1.2 Alter database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

2.2 Tablespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.2.1 Create tablespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.2.2 Alter tablespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.2.3 Drop tablespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

2.3 Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122.3.1 Create table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122.3.2 Alter table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152.3.3 Drop table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

2.4 Indexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182.4.1 Create index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182.4.2 Alter index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192.4.3 Drop index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

2.5 (Materialized) views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202.5.1 Create view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202.5.2 Alter view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212.5.3 Drop view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212.5.4 Create materialized view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212.5.5 Alter materialized view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222.5.6 Drop materialized view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

2.6 Synonyms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232.6.1 Create synonym . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232.6.2 Drop synonym . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

2.7 Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242.7.1 Create sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242.7.2 Alter Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252.7.3 Drop sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

2.8 Programmable objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262.8.1 Stored procedures and user functions . . . . . . . . . . . . . . . . . . . . . . 262.8.2 Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282.8.3 Triggers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

2.9 Users, roles and privileges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302.9.1 Create user . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312.9.2 Alter user . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322.9.3 Drop user . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322.9.4 Create role . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

3

Page 4: Tutorial de SQL Para Oracle

4 CONTENTS

2.9.5 Alter role . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332.9.6 Drop role . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332.9.7 Grant privilege . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332.9.8 Revoke privilege . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

2.10 Oracle built-in datatypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352.11 The Data Dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

2.11.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362.11.2 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

3 Data Manipulation Language 393.1 Retrieving data from the database . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

3.1.1 The select clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403.1.2 The from clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403.1.3 The where clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403.1.4 Joining tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413.1.5 Grouping and aggregate functions . . . . . . . . . . . . . . . . . . . . . . . 413.1.6 Sorting the result of the query . . . . . . . . . . . . . . . . . . . . . . . . . 42

3.2 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423.2.1 Simple expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433.2.2 Compound expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443.2.3 Function expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443.2.4 CAST expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463.2.5 DECODE expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473.2.6 CASE expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

3.3 Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473.3.1 Simple comparison conditions . . . . . . . . . . . . . . . . . . . . . . . . . . 483.3.2 Group comparison conditions . . . . . . . . . . . . . . . . . . . . . . . . . . 493.3.3 Membership conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493.3.4 Range conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503.3.5 Null conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503.3.6 Exists conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503.3.7 Like conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503.3.8 Compound conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

3.4 Inserting data into the database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513.4.1 The value clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513.4.2 Using a subquery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

3.5 Changing existing data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513.6 Deleting data from the database . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

Page 5: Tutorial de SQL Para Oracle

Chapter 1

Introduction

The Structured Query Language (SQL) is the standard language used to interact with relationaldatabase systems. All major database management systems support SQL. Most of these systemsimplement only part of the ISO standard, completed with their own extensions. This tutorial isbased on the Oracle implementation.

SQL consists of two parts. One part, the Data Definition Language (DDL), is used to defineand modify the structure of a database. Chapter 2 explains this part. The other part, the DataManipulation Language (DML), is used to query and to change the data in a database. This isexplained in chapter 3.

As this is only an introduction, many of the more advanced options are omitted. Especiallyfollowing 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 Oracledatabase. This will be helpful to understand some SQL constructs. Note the information in thissection is typical for Oracle. DBMS’s 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 isdisposed. An Oracle Instance provides access to exactly one database. On the other hand, severalinstances (generally running on different servers with shared storage facilities) can manage thesame database. This is possible using the Oracle Parallel Server option.

A database is identified by it’s own name and the domain name of the server it runs on ([email protected], 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 todivide the data of the database in logical units, for instance each application that uses the databasecould have it’s own tablespace. A lot of management operations (such as putting them online oroffline, move to another database) can be applied to tablespaces. Therefore a good separation ofthe data in tablespaces simplifies database management.

5

Page 6: Tutorial de SQL Para Oracle

6 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 goesoffline, this tablespace is always online. It contains the data dictionary tables and views. Theseare 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 apossible configuration of an Oracle database.

Apart from the tablespaces, each user has it’s own schema. This schema contains all thedatabase objects that are owned by this user. The name of the schema corresponds to the user-name. Schema’s and tablespaces are independent concepts.

The use of other objects in a database is explained in the next chapter together with the SQLstatement to handle them.

Page 7: Tutorial de SQL Para Oracle

Chapter 2

Data Definition Language

As mentioned before, the Data Definition Language is used to define or alter the structure of adatabase. In general the DDL has a CREATE, ALTER and DROP statement for each kind ofobject in the database. This chapter has one section for each kind of object, where the purposeof 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 seman-tic properties, because these commonly have counterparts in other relational DBMS’s. Propertiesconcerning physical storage are usually not discussed. Also note that not all of the object typesthat are available in Oracle are mentioned. After reading this tutorial, the reader should be ableto 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 thehelp of graphical tools. These tools allow the user to create, alter and drop database objects withno or little knowledge of SQL. Whether these tools use SQL to interact with the database or notdepends on the product. Typically Oracle tools do. In most cases the user can even see andmodify the created SQL code.

Although these tools are far more easier to use (compared to writing SQL code), it is oftenvery helpful to know how the underlying SQL statements work because this will provide a moreformal grip to interpret the options offered by a graphical user interface. Furthermore, a lot ofdatabase 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 arestored within a database. It is common that one server (or a cluster of servers) contains only onedatabase, especially in Oracle where a database can be logically divided in tablespaces (in othersystems databases have a similar function as tablespaces have in Oracle).

7

Page 8: Tutorial de SQL Para Oracle

8 CHAPTER 2. DATA DEFINITION LANGUAGE

2.1.1 Create database

-®­

©ªCREATE -

®­

©ªDATABASE - database -

®­

©ªCONTROLFILE -

®­

©ªREUSE

-®­

©ªLOGFILE -

®­

©ªGROUP - integer

6- 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 ?

66- REUSE

6-

Most of the properties available in this statement are related to the files used by the databaseto store data and logging information.

CONTROLFILE REUSEUse this clause to indicate that existing control files should be reused for the new database, ignoringand overwriting any information they currently contain. The control files contain informationabout all other files in the database, so they are the primary resource of information about adatabase for the Oracle system.

LOGFILE clauseThe 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.

MAXLOGFILESThis clause specifies the maximum number of log file groups in the database.

MAXLOGMEMBERSThis clause specifies the maximum numbers of files in one redo log file group.

Page 9: Tutorial de SQL Para Oracle

2.1. DATABASES 9

MAXDATAFILESDefines the initial maximum number of files for data storage. This parameter is only used todetermine the space needed for filenames in the control files. The control files are extendedautomatically if more data files are added to the database.

MAXINSTANCESThis parameter specifies how much instances can have this database mounted and opened.

ARCHIVELOG, NOARCHIVELOGSpecify 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 redolog files can be reused without archiving them. This is the default setting.

CHARACTER SETUse this property to specify the character set used to store data.

NATIONAL CHARACTER SETUse this property to specify the character set used to store data of the types NCHAR, NCLOBand NVARCHAR2.

2.1.2 Alter database

-®­

©ªALTER -

®­

©ªDATABASE - database -

- recover_clause

- datafile_tempfile_clauses

- logfile_clauses

- controlfile_clauses

-®­

©ªMOUNT

-®­

©ªOPEN -

®­

©ªREAD -

®­

©ªWRITE

-®­

©ªREAD -

®­

©ªONLY ?

6

-®­

©ª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 clauseThis clause is used for recovery operation.

Page 10: Tutorial de SQL Para Oracle

10 CHAPTER 2. DATA DEFINITION LANGUAGE

datafile tempfile clauses, logfile clausesThese clauses are used to add, drop or change data files, temp files and log files respectively.

MOUNTUse this clause to mount an unmounted database.

OPENUse 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. Tablespacescan be deleted, exported and imported in one single operation. When carefully chosen and man-aged, 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, NOLOGGINGThis clause determines the default logging behaviour of tables and indexes created in this ta-blespace.

ONLINE, OFFLINESpecify ONLINE to make the tablespace available immediately after creation. This is the defaultmode. Specify OFFLINE to make the tablespace unavailable immediately after creation.

PERMANENT, TEMPORARYSpecify PERMANENT if the tablespace will be used to store permanent objects. Specify TEM-PORARY if the tablespace will be used to hold temporary objects only.

2.2.2 Alter tablespace

-®­

©ªALTER -

®­

©ªTABLESPACE - tablespace -

Page 11: Tutorial de SQL Para Oracle

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 clausesThis clause is used to add or change (rename) the data files of the tablespace.

ONLINE, OFFLINEUse these clauses to put a tablespace online or offline.

BEGIN, END BACKUPUse the BEGIN BACKUP clause to indicate that an open backup is to be performed on the datafiles of the tablespace. Use END BACKUP after completion of the backup.

READ ONLY, READ WRITEChange the read/write mode of the tablespace.

PERMANENT, TEMPORARYUse 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 CONTENTSto drop all the contents of the tablespace too. If this clause is omitted and the tablespace is notempty, Oracle will rise an error.

Page 12: Tutorial de SQL Para Oracle

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 anda set of columns. Each column has a column name, a datatype and a width. The width can bepredetermined by the datatype, as in DATE. If columns are of the NUMBER datatype, precisionand scale need to be defined instead of width. A row is a collection of column informationcorresponding to a single record. You can specify rules for each column of a table. These rules arecalled integrity constraints. One example is a NOT NULL integrity constraint. This constraintforces the column to contain a non null value in every row. After a table is created, rows of datacan be inserted using SQL statements. Table data can then be queried, deleted, or updated usingSQL.

2.3.1 Create table-

®­

©ªCREATE -

®­

©ªGLOBAL -

®­

©ªTEMPORARY

6-

®­

©ªTABLE - schema -

®­

©ª.

6- table -

-®­

©ª( - relational_properties -

®­

©ª)

6-

®­

©ªON -

®­

©ªCOMMIT -

®­

©ªDELETE

-®­

©ªPRESERVE ?-

®­

©ªROWS

6-

-®­

©ªTABLESPACE - tablespace

6- table_properties

6- AS - subquery

6-

Specify the name of the new table after the TABLE keyword. Use a schema indicator if the tablehas to be created in a non default schema (the default is the current user’s schema).

The relational properties of the table (the content definition) is specified in the table propertiesclause. This clause is explained in the next subsection.

Use the tablespace clause to specify in which tablespace the table should be stored. If this clauseis omitted, the table is stored in the default tablespace for the current user. The table propertiesclause is explained in the last subsection.

The AS subquery clause can be used to fill the table with the results of a query immediatelyafter creation.

Relational properties

- column - datatype -®­

©ªDEFAULT - expr

6- column_constraint?

6

- table_constraint ?

®­

©ª,

?

-

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 thecolumn.

Column constraints

If there are column specific constraints (constraints which involve only one column), these have tobe specified immediately after the column specification.

Page 13: Tutorial de SQL Para Oracle

2.3. TABLES 13

-®­

©ªCONSTRAINT - constraint

6-

-®­

©ªNOT

6-

®­

©ªNULL

-®­

©ªUNIQUE

-®­

©ªPRIMARY -

®­

©ªKEY ?

-®­

©ªREFERENCES - schema -

®­

©ª.

6- table -

®­

©ª( - column -

®­

©ª)

6-

®­

©ªON -

®­

©ªDELETE -

®­

©ªCASCADE

-®­

©ªSET -

®­

©ªNULL ?

6

-®­

©ªCHECK -

®­

©ª( - condition -

®­

©ª) ?-

Use the CONSTRAINT keyword followed by a name to specify a name for the constraint. Ifthis 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 containnull values.

• REFERENCES:This column is a foreign key column. See table constraints for more information on foreignkeys.

• CHECK:A check constraint contains a condition that must be satisfied by all (non null) values in thiscolumn.

Table constraints

Table constraints have similar functions as the corresponding column constraints, but they (can)involve more than one column.

-®­

©ªCONSTRAINT - constraint

6-

®­

©ª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 systemgenerated name will be used.

• UNIQUE — PRIMARY KEY:Specifies a set of column that contain unique values. Primary keys cannot contain nullvalues. Oracle automatically creates an index for each unique or primary key constraint.

Page 14: Tutorial de SQL Para Oracle

14 CHAPTER 2. DATA DEFINITION LANGUAGE

• REFERENCES:

-®­

©ªFOREIGN -

®­

©ªKEY -

®­

©ª( - column

®­

©ª,

? -®­

©ª) -

®­

©ªREFERENCES - schema -

®­

©ª.

6-

- table -®­

©ª( - column

®­

©ª,

? -®­

©ª)

6-

®­

©ªON -

®­

©ªDELETE -

®­

©ªCASCADE

-®­

©ªSET -

®­

©ªNULL ?

6-

Specifies a set of columns that references another table. This constraint checks if the valueof 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 isdeleted. With the CASCADE option, the referencing rows will be deleted together with thereferenced row. With the SET NULL option, all references to the deleted row will be set tonull 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 ?

6-

®­

©ªMONITORING

-®­

©ªNOMONITORING ?

6- enable_diable_clause?

6-

CACHE, NOCACHEUsed to specify whether the data of this table should be cached or not. Caching will speed uprepeated access to the table, but may slow down access to other tables.

MONITORING, NOMONITORINGEnable or disable monitoring of this table. With monitoring enabled, Oracle will collect statisticsthat 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

6-

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

Page 15: Tutorial de SQL Para Oracle

2.3. TABLES 15

constraint is enabled, VALIDATE can be used to make sure that the existing content of the tablesatisfies the constraint. If NOVALIDATE is specified, the existing content of the table may violatethe constraint.

When disabling a constraint, CASCADE can be specified to disable all the constraint thatdepend on the disabled constraint.

2.3.2 Alter table

-®­

©ªALTER -

®­

©ªTABLE - schema -

®­

©ª.

6- table -

-®­

©ªADD -

®­

©ª( - add_column_options -

®­

©ª)

-®­

©ªMODIFY -

®­

©ª( - modify_column_options -

®­

©ª)

-®­

©ªMOVE -

®­

©ªONLINE

6-

®­

©ª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 tableproperties have been explained in the previous section, so they will only be mentioned here.

ADD clause

add column options ::=

Page 16: Tutorial de SQL Para Oracle

16 CHAPTER 2. DATA DEFINITION LANGUAGE

- column - datatype -®­

©ªDEFAULT - expr

6- col_ref_constraint

6- col_constraint?

6

- table_constraint

- table_ref_constraint ?

®­

©ª,

?

-

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

MODIFY clause

modify column options ::=

- column - datatype6-

®­

©ªDEFAULT - expr

6- col_constraint?

6

®­

©ª,

? -

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 beaccessible 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

6

-®­

©ªCONSTRAINT - constraint ?-

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

Drop column clause

Page 17: Tutorial de SQL Para Oracle

2.3. TABLES 17

-®­

©ªSET -

®­

©ªUNUSED -

®­

©ªCOLUMN - column

-®­

©ª( - column

®­

©ª,

? -®­

©ª) ? -

®­

©ªCASCADE -

®­

©ªCONSTRAINTS

-®­

©ªINVALIDATE ?

?

6

-®­

©ªDROP -

®­

©ªCOLUMN - column

-®­

©ª( - column

®­

©ª,

? -®­

©ª) ? -

®­

©ªCASCADE -

®­

©ªCONSTRAINTS

-®­

©ªINVALIDATE ?

?

6-

®­

©ªCHECKPOINT - integer

6

-®­

©ªDROP -

®­

©ªUNUSED -

®­

©ªCOLUMNS

-®­

©ªCOLUMNS -

®­

©ªCONTINUE ?-

®­

©ªCHECKPOINT - integer

6?-

There several ways to remove a column from the table definition. The most convenient way isto use the second option in the schema. Specify one column name after the COLUMN keywordor a list of column names to be removed.

Specify CASCADE CONSTRAINTS to remove constraints that depend on the removed col-umn(s). If this clause is omitted, and a constraints depending on a removed column exists, Oraclewill raise an error.

Specify INVALIDATE to automatically invalidate all objects (such as views, triggers, pro-grammed units, etc.) that reference the removed column.

The CHECKPOINT clause can be used to specify that Oracle has to take a checkpoint eachtime 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 thata full rollback of the operation is not possible. If the operation fails, the table remains in anunusable state. The unusable table can either be dropped or the DROP COLUMNS CONTINUEclause 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 clausedescribed above, but it does not physically remove the column from the database. This meansthat an unused column is not accessible (and not restorable), but that the data still exist. Usingthis way to remove a column results in a better response time, since Oracle does not have toreorganize the table.

The DROP UNUSED COLUMNS clause can be used to physically remove the unused col-umn(s) of the table.

RENAMEUse this clause to change the name of the table.

Enable, disable clauseCompared to the enable disable clause of the create table statement, two additional options areavailable. Table lock can be enabled or disabled. DDL statements executed on a table need tolock 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.

Page 18: Tutorial de SQL Para Oracle

18 CHAPTER 2. DATA DEFINITION LANGUAGE

2.3.3 Drop table

-®­

©ªDROP -

®­

©ªTABLE - schema -

®­

©ª.

6- table -

®­

©ªCASCADE -

®­

©ªCONSTRAINTS

6-

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 theperformance of data retrieval. When processing a request, Oracle can use some or all of theavailable indexes to locate the requested rows efficiently. Indexes are useful when applicationsoften 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 automaticallymaintained and used by Oracle. Changes to table data (such as adding new rows, updating rows, ordeleting rows) are automatically incorporated into all relevant indexes with complete transparencyto 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 createdany time with no effect on the tables or other indexes. If an index is dropped, all applicationscontinue to function. However, access to previously indexed data could be slower.

2.4.1 Create index

-®­

©ªCREATE -

®­

©ªUNIQUE

-®­

©ªBITMAP ?

6-

®­

©ªINDEX - schema -

®­

©ª.

6- index -

®­

©ªON -

- schema -®­

©ª.

6- table - t_alias -

®­

©ª( - column

- column_expression ? -®­

©ªASC

-®­

©ªDESC ?

6

®­

©ª,

?

-®­

©ª) -

-®­

©ªONLINE

-®­

©ªLOGGING

-®­

©ªNOLOGGING ?

-®­

©ªCOMPUTE -

®­

©ªSTATISTICS

-®­

©ªTABLESPACE - tablespace

-®­

©ªDEFAULT ?

-®­

©ªCOMPRESS - integer

-®­

©ªNOCOMPRESS ? ?

6

?

-

Page 19: Tutorial de SQL Para Oracle

2.4. INDEXES 19

Use the keyword UNIQUE to indicate that this index has to check a unique key constraint on it’sbase table. Normal indexes use a B-Tree to store the keys. If the keyword BITMAP is used, thekeys are stored in a bitmap like structure. Bitmap storage cannot be combined with a unique keyindex.

After the index name, the index content is specified: the name of the base table and a list ofexpressions which make up the index key. In general, the expressions are column names, but it ispossible to index on computed values. Use the ASC or DESC keywords to indicate that the keyvalues have to be indexed ascending or descending respectively.

The last part of this statement contains property settings that are not content related. Thetablespace clause specifies in which tablespace the index has to be stored.

The COMPRESS property tells Oracle to compress the index, by storing repeated key val-ues only once. The integer following the keywords specifies how much levels (= number of keycolumns) of compression Oracle may apply. This integer is minimum one and maximum the num-ber of key columns (minus one for unique indexes). Specify NOCOMPRESS (default) to prohibitcompression.

Specify the ONLINE keyword to indicate that the base should not be locked during the creationof the index.

Specify COMPUTE STATISTICS to collect statistics at relatively little cost during the creationof the index. These statistics are stored in the data dictionary for use by the query optimizer.

2.4.2 Alter index

-®­

©ªALTER -

®­

©ªINDEX - schema -

®­

©ª.

6- 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 torecreate the index entirely. The subclauses of the rebuild clause have the same meaning as in thecreate index statement.

The ENABLE clause enables a function based index that has been disabled because a user-defined function used by the index was dropped or replaced. The DISABLE clause disables afunction based index, so the function can be maintained.

Use the UNUSABLE clause to permanently disable an index. An unusable index can only beenabled by rebuilding it or it can be dropped and recreated.

The RENAME clause provides a new name for the index.

Page 20: Tutorial de SQL Para Oracle

20 CHAPTER 2. DATA DEFINITION LANGUAGE

2.4.3 Drop index

-®­

©ªDROP -

®­

©ªINDEX - schema -

®­

©ª.

6- 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. Aview takes the output of a query and treats it as a table. Therefore, a view can be thought of asa 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 defineviews with up to 1000 columns, just like a table. You can query views, and with some restrictionsyou can update, insert into, and delete from views. All operations performed on a view actuallyaffect data in some base table of the view and are subject to the integrity constraints and triggersof the base tables.

Views can be used for several reasons:

• Complexity hiding: the optimal storage format of the data (e.g. normalized tables) arerather complex and not very suitable for direct user access. For this reason views can becreated 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 basicqueries. If these basic queries are available as views, user do not have to recreate them allthe 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 userand the applications.

Whereas the data of a normal view is not stored in the database, but retrieved from the basetables when necessary, the data of a materialized view is stored as if it where a base table. Amaterialized view can allow updates or not. Update actions against materialized views are notpropagated in the base tables.

Materialized views are very useful in applications that regularly execute queries on big amountsof data, but don’t need to use the most recent data. Datamining and decision support system areexamples of such applications.

2.5.1 Create view-

®­

©ªCREATE -

®­

©ªOR -

®­

©ªREPLACE

6-

®­

©ªNO

6-

®­

©ªFORCE

6-

®­

©ªVIEW -

- schema -®­

©ª.

6- view -

®­

©ª( - alias

®­

©ª,

? -®­

©ª)

6-

®­

©ªAS - subquery -

The create view statement creates a new (non-materialized) view. If a view with the same namealready exists, the OR REPLACE clause can be inserted to replace the existing view definitionwith the new one.

Use the FORCE keyword if the view should be created regardless of whether the views basetables exist or the owner of the schema containing the view has privileges on them. Note that

Page 21: Tutorial de SQL Para Oracle

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 notexist or if the owner of the schema containing the view does not have the proper privileges toexecute the query associated with the view.

The view’s name specification is followed by an optional alias list. This alias list providesnames for the columns in the view. If this list is omitted, the columns get names generated fromthe subquery. If some column in the subquery is an expression rather than a column name, analias must be provided.

The last part of the statement is the subquery. This subquery specifies the columns of theview and how to retrieve the rows of the view.

2.5.2 Alter view-

®­

©ªALTER -

®­

©ªVIEW - schema -

®­

©ª.

6- view -

®­

©ªCOMPILE -

Contrary to other alter statements, the alter view statement is not meant to change the definitionof 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 checkif 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 -

®­

©ª.

6- view -

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

2.5.4 Create materialized view-

®­

©ªCREATE -

®­

©ªMATERIALIZED -

®­

©ªVIEW

-®­

©ªSNAPSHOT ?- schema -

®­

©ª.

6- view -

-®­

©ªBUILD -

®­

©ªIMMEDIATE

-®­

©ªDEFERRED ?

6- refresh_clause

6-

-®­

©ªFOR -

®­

©ªUPDATE

6-

®­

©ªDISABLE

-®­

©ªENABLE ?-

®­

©ªQUERY -

®­

©ªREWRITE

6-

®­

©ª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 bepopulated. 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 clauseis 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 thecreated view should be updatable.

Page 22: Tutorial de SQL Para Oracle

22 CHAPTER 2. DATA DEFINITION LANGUAGE

The rewrite clause can be used to specify that this snapshot can or cannot be used for queryrewrite. Query rewrite is a feature of the query optimizer. If a query (which does not use thesnapshot) could be executed faster by using the contents of the snapshot (instead of regeneratingit), the query optimizer will take advantage of this if query rewrite is enabled. Note that the resultsof the query might be different if query rewrite is applied, depending on the refresh settings of thesnapshot. 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 thesnapshot will be adjusted to the changes in its base tables.

FAST, COMPLETE, FORCEUse FAST to specify that the snapshot should be refreshed incrementally. Use COMPLETE toindicate 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 (in-cremental) refresh if possible or a complete refresh otherwise.

ON COMMIT, ON DEMANDIf ON COMMIT is specified, a fast refresh of the snapshot will occur whenever Oracle commits atransaction that operates on the views base tables.ON DEMAND (default) indicates that the snapshot will be refreshed on user request only.

START WITH, NEXTUse these options to set regular refresh times. The START WITH clause sets the first time torefresh the snapshot. If it is omitted, the first refresh time is set to the time of creation. TheNEXT clause specifies the time interval between two consecutive refreshes.

NEVER REFRESHUse 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 -

®­

©ª.

6- view -

Page 23: Tutorial de SQL Para Oracle

2.6. SYNONYMS 23

- refresh_clause6

-®­

©ªENABLE

-®­

©ªDISABLE ?-

®­

©ªQUERY -

®­

©ªREWRITE

-®­

©ªCOMPILE ?

6-

The alter materialized view statement is used to change the properties of a snapshot. It is clear thatmost 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 -

®­

©ª.

6- 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 anobject.

• Location transparency: with a synonym, the underlying object can be moved and renamedwithout visible effects to the user. Location transparency is very useful in distributeddatabases.

2.6.1 Create synonym

-®­

©ªCREATE -

®­

©ªPUBLIC

6-

®­

©ªSYNONYM - schema -

®­

©ª.

6- synonym -

-®­

©ªFOR - schema -

®­

©ª.

6- object -

®­

©ª@ - dblink

6-

If the create synonym statement begins with CREATE SYNONYM the synonym is created in aspecific schema and it will not be accessible outside this schema. If the statement begins withCREATE 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

6-

®­

©ªSYNONYM - schema -

®­

©ª.

6- synonym -

Page 24: Tutorial de SQL Para Oracle

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 valuesfor the rows of a single table or multiple tables. For example, assume two users are simultaneouslyinserting new employee rows into the EMP table. By using a sequence to generate unique employeenumbers for the EMPNO column, neither user has to wait for the other to enter the next availableemployee number. The sequence automatically generates the correct values for each user. Sequencenumbers are independent of tables, so the same sequence can be used for one or more tables. Aftercreation, a sequence can be accessed by various users to generate actual sequence numbers.

2.7.1 Create sequence

-®­

©ªCREATE -

®­

©ªSEQUENCE - schema -

®­

©ª.

6- 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 BYSpecifies 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 WITHBy default the sequence starts with MINVALUE for ascending sequences and with MAXVALUEfor descending sequences. Use this clause if the sequence should start with another value.

MAXVALUE, MINVALUEUse these clauses to set maximum resp. minimum value the sequence can generate. The specifiedvalues should equal or greater resp less than the START WITH value. The MINVALUE must beless than the MAXVALUE.

Page 25: Tutorial de SQL Para Oracle

2.7. SEQUENCES 25

NOMAXVALUE, NOMINVALUEUse these clauses to indicate that MAXVALUE and MINVALUE should be default values. 1027

and 1 resp. for ascending sequences and -1 and 10−26 resp. for descending sequences.

CYCLE, NOCYCLEIf 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 viceversa for descending sequences.A non-cycling sequence can no longer generate values after reaching its maximum or minimumvalue.

CACHE, NOCACHEThe CACHE clause specifies how many values should be preallocated for faster access. Theminimum is two.If NOCACHE is specified, no values are preallocated.

2.7.2 Alter Sequence

-®­

©ªALTER -

®­

©ªSEQUENCE - schema -

®­

©ª.

6- 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 exactlythe same as in the create sequence statement, except that the START WITH property cannot beset here.

2.7.3 Drop sequence

-®­

©ªDROP -

®­

©ªSEQUENCE - schema -

®­

©ª.

6- sequence -

Use this statement to drop a sequence.

Page 26: Tutorial de SQL Para Oracle

26 CHAPTER 2. DATA DEFINITION LANGUAGE

2.8 Programmable objects

Most database systems nowadays offer a wide range of possibilities to enhance the database withuser programmed features. This programming is commonly done with a legacy language. In Oraclethis language is called PL/SQL where PL stands for PROCEDURAL LANGUAGE. PL/SQL codeis 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 explainsthe 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 thedatabase. It has a procedure header (or signature) consisting of a procedure name and a list ofparameters, 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

6-

®­

©ªPROCEDURE - schema -

®­

©ª.

6- procedure -

-®­

©ª( - argument -

®­

©ªIN

-®­

©ªOUT

-®­

©ªIN -

®­

©ªOUT ?

6-

®­

©ªNOCOPY

6- datatype

®­

©ª,

?

-®­

©ª)

6-

- invoker_rights_clause6-

®­

©ªIS

-®­

©ªAS ?- pl_sql_subprogram_body

- call_spec ?-

This statement can be used to create or replace a stored procedure. After the name of theprocedure, comes the (optional) argument list. An argument can be used as input, output orboth. The keyword NOCOPY instructs Oracle to pass the argument as fast as possible (e.g. usingpass 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 externalcode 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 thecurrent user’s rights are used, the procedure can only be executed by users who have the necessary

Page 27: Tutorial de SQL Para Oracle

2.8. PROGRAMMABLE OBJECTS 27

privileges. If the definer’s rights are used, all user having the execute privilege on the procedurecan execute it (if the definer owns the necessary privileges).

Alter procedure

-®­

©ªALTER -

®­

©ªPROCEDURE - schema -

®­

©ª.

6- procedure -

®­

©ªCOMPILE -

®­

©ªDEBUG

6-

The alter function statement explicitly recompiles a procedure. This avoids run-time recompila-tion.

Drop procedure

-®­

©ªDROP -

®­

©ªPROCEDURE - scheme -

®­

©ª.

6- procedure -

Use this statement to drop a procedure.

Create function

-®­

©ªCREATE -

®­

©ªOR -

®­

©ªREPLACE

6-

®­

©ªFUNCTION - schema -

®­

©ª.

6- function -

-®­

©ª( - argument -

®­

©ªIN

-®­

©ªOUT

-®­

©ªIN -

®­

©ªOUT ?

6-

®­

©ªNOCOPY

6- datatype

®­

©ª,

?

-®­

©ª)

6-

-®­

©ªRETURN - datatype - invoker_rights_clause

-®­

©ªDETERMINISTIC ?

6

?

-®­

©ªAS

-®­

©ªIS ?- pl_sql_function_body

- call_spec ?-

Use this statement to create or replace a function. The syntax and of this statement the same asfor 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 fromfunction based indexes or materialized views).

Alter function

-®­

©ªALTER -

®­

©ªFUNCTION - schema -

®­

©ª.

6- function -

®­

©ªCOMPILE -

®­

©ªDEBUG

6-

Page 28: Tutorial de SQL Para Oracle

28 CHAPTER 2. DATA DEFINITION LANGUAGE

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

Drop function

-®­

©ªDROP -

®­

©ªFUNCTION - schema -

®­

©ª.

6- 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 onlycontains the declaration of the package. The implementation should be stored in a package bodyobject.

Create package

-®­

©ªCREATE -

®­

©ªOR -

®­

©ªREPLACE

6-

®­

©ªPACKAGE - schema -

®­

©ª.

6- package -

- invoker_rights_clause6-

®­

©ªIS

-®­

©ªAS ?- pl_sql_package_spec -

Use this statement to create a package specification. The pl sql package spec clause contains onlythe 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

6-

®­

©ªPACKAGE -

®­

©ªBODY - schema -

®­

©ª.

6- package -

-®­

©ªIS

-®­

©ªAS ?- pl_sql_package_body -

This statement creates the body of a package.

Alter package

-®­

©ªALTER -

®­

©ªPACKAGE - schema -

®­

©ª.

6- package -

®­

©ªCOMPILE -

®­

©ªDEBUG

6-

®­

©ªPACKAGE

-®­

©ªSPECIFICATION

-®­

©ªBODY ?-

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

Page 29: Tutorial de SQL Para Oracle

2.8. PROGRAMMABLE OBJECTS 29

Drop package

-®­

©ªDROP -

®­

©ªPACKAGE - schema -

®­

©ª.

6- 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

6-

®­

©ªTRIGGER - schema -

®­

©ª.

6-

®­

©ªBEFORE

-®­

©ªAFTER

-®­

©ªINSTEAD -

®­

©ªOF ?-

- dml_event_clause

- ddl_event

®­

©ªOR

?

- database_event

®­

©ªOR

? ?-®­

©ªON - schema -

®­

©ª.

6-

®­

©ªSCHEMA

-®­

©ªDATABASE ??-

- referencing_clause -®­

©ªWHEN -

®­

©ª( - condition -

®­

©ª)

6- pl_sql_block

- call_procedure_spec ?-

Use this statement to create or replace a trigger. The keywords BEFORE, AFTER and INSTEADOF determine when the trigger is executed. With INSTEAD OF, the event will be replaced bythis trigger. BEFORE and AFTER cannot be used for DML events on views, INSTEAD OF canonly be used for DML events on views.

Triggers can be triggered on DDL or on DML events. For more information on DDL eventtriggers, see the Oracle SQL Reference.

dml event clause ::=

-®­

©ªDELETE

-®­

©ªINSERT

-®­

©ªUPDATE -

®­

©ªOF - column

®­

©ª,

?6

?

®­

©ªOR

?

-®­

©ªOF - schema -

®­

©ª.

6- table

- view ?-

Page 30: Tutorial de SQL Para Oracle

30 CHAPTER 2. DATA DEFINITION LANGUAGE

Every DML update event (insert, delete and update) can trigger an event. If necessary, severalevents can trigger the same trigger. Update triggers can be limited to one or more columns.

referencing clause ::=

-®­

©ªREFERENCING -

®­

©ªOLD -

®­

©ªAS

6- old

-®­

©ªNEW -

®­

©ªAS

6- new

-®­

©ªPARENT -

®­

©ªAS - parent ?

?

6-

®­

©ªFOR -

®­

©ªEACH -

®­

©ªROW

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.

WHENThe when clause contains a condition. The trigger only launches if this condition is satisfied.

Alter trigger

-®­

©ªALTER -

®­

©ªTRIGGER - schema -

®­

©ª.

6- trigger -

®­

©ªENABLE

-®­

©ªDISABLE

-®­

©ªCOMPILE -

®­

©ªDEBUG

6?-

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

Drop trigger

-®­

©ªDROP -

®­

©ªTRIGGER - schema -

®­

©ª.

6- 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 controlconsists 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 goodoption if user access the system only through the Oracle database.

• Externally: The authentication is not done by Oracle itself, but by an external service suchas the operating system it runs in. This allows the users to have the same password for theoracle database and the system environment.

Page 31: Tutorial de SQL Para Oracle

2.9. USERS, ROLES AND PRIVILEGES 31

• Globally: The authentication is done by an enterprise directory service. This allows theuser 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 adatabase action if he/she does not have the proper privileges. For example to launch a selectstatement, 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 objectbasis, it is clear that it is a huge job to manage the privileges in a database system, especially inlarge environments.

That is why roles are useful. A role is a named set of privileges. A role can be granted toa user or to another role. This means that the grantee (user or role) receives all the privilegesincluded in the granted role.

Typically a role includes the privileges that correspond with the needs of a group of users orwith 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 corre-spond with the methods mentioned above. Then properties of the user can be set:

DEFAULT TABLESPACEUse this property to set the default tablespace for the user. This is the tablespace where objectscreated by this user are stored by default. By default, the default tablespace is SYSTEM.

TEMPORARY TABLESPACEThis property specifies the tablespace where temporary objects are stored by default. This prop-erty defaults to SYSTEM too.

QUOTA

Page 32: Tutorial de SQL Para Oracle

32 CHAPTER 2. DATA DEFINITION LANGUAGE

With a quota clause the user is granted storage space in the specified tablespace. The grantedspace can be unlimited or be a limited space specified in kilobyte or megabyte.

PROFILEA profile is a set of properties that can be associated with users. A profile contains runtime settingslike the maximum number of simultaneous connections per user, available cpu time, available cachespace, etc...

If this clause is omitted, the new user gets the default profile. Statements exist to create, alterand drop profiles, but they are not explained in this tutorial.

PASSWORD EXPIREThis clause forces the user to change its password at first login.

ACCOUNT LOCK, UNLOCKACCOUNT LOCK disables the account until the account is unlocked. ACCOUNT UNLOCKenables 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 asin 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.

Page 33: Tutorial de SQL Para Oracle

2.9. USERS, ROLES AND PRIVILEGES 33

2.9.4 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 userswhich 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 statementsyntax is divided in two parts. The first part is to assign system and role privileges, the secondpart is to assign object privileges. Both parts have a common grantee clause. Privileges can begranted to more than one user/role at once. If the grantee is PUBLIC, all users get the grantedprivilege.

Page 34: Tutorial de SQL Para Oracle

34 CHAPTER 2. DATA DEFINITION LANGUAGE

System and role privileges

- system_privilege

- role

-®­

©ªALL -

®­

©ªPRIVILEGES ?

®­

©ª,

?

-®­

©ªTO - user

- role

-®­

©ªPUBLIC ?

®­

©ª,

?

-®­

©ªWITH -

®­

©ªADMIN -

®­

©ªOPTION

6-

A system privilege is a privilege that is not related with a specific object in the database. Theseprivileges are mostly related with DDL statements. Role privileges give the grantee the right touse 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 alsochange the role privileges.

Object privileges

- object_privilege

-®­

©ªALL -

®­

©ªPRIVILEGES

6?-

®­

©ª( - column

®­

©ª,

? -®­

©ª)

6

®­

©ª,

?

-

-®­

©ªON - schema -

®­

©ª. - object -

®­

©ªTO - user

- role

-®­

©ªPUBLIC ?

®­

©ª,

?

-®­

©ªWITH -

®­

©ªADMIN -

®­

©ªOPTION

6-

Object privileges are related to one specific object in the database (e.g. the right to select rowsfrom 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 limitedto a subset of the columns.

Use ALL PRIVILEGES to give the grantee the full right to use the specified object. TheWITH 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 ?

®­

©ª,

?

-

Page 35: Tutorial de SQL Para Oracle

2.10. ORACLE BUILT-IN DATATYPES 35

The revoke statement is the counterpart of the grant statement. Instead of allowing a user to dosomething 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 objectprivileges. The options are mainly the (although they have the opposite effect).

System privileges

- object_privilege

-®­

©ªALL -

®­

©ªPRIVILEGES

6?-

®­

©ª( - column

®­

©ª,

? -®­

©ª)

6

®­

©ª,

?

-

Object privileges

-®­

©ªON - schema -

®­

©ª. - object -

®­

©ªFROM - user

- role

-®­

©ªPUBLIC ?

®­

©ª,

?

-®­

©ªCASCADE -

®­

©ªCONSTRAINTS

6-

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

2.10 Oracle built-in datatypes

Built-in Datatype DescriptionVARCHAR2(size) Variable length character string having maximum length size bytes.

Maximum size is 4000, and minimum is 1. size has to be specified.NVARCHAR2(size) Variable length character string having maximum length size characters

or bytes, depending on the choice of national character set. Maximumsize 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

Page 36: Tutorial de SQL Para Oracle

36 CHAPTER 2. DATA DEFINITION LANGUAGE

Built-in Datatype DescriptionVARCHAR2(size) Variable length character string having maximum length size bytes.

Maximum size is 4000, and minimum is 1. size has to be specified.NUMBER(p, s) 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 to127.

LONG Character data of variable length up to 2 gigabytes, or 231 − 1 bytes.DATE Valid data range from January 1, 4712 BC to December 31, 9999 AD.RAW(size) Raw binary data of size bytes. sizehas to be specified.

Maximum size is 2000.LONGRAW Raw binary data of variable length up to 2 gigabytes.ROWID Hexadecimal string representing the unique address of a row in its table.

This datatype is primarily for values returned by the ROWID pseudo-column.

CHAR(size) Fixed-length character data of length size bytes. Maximum length is2000 bytes. Default and minimum size is 1 byte.

NCHAR(size) Fixed-length character string of length size characters or bytes,depending on the choice of national character set. Maximum size isdetermined by the number bytes required to store each character, with amaximum limit of 2000 bytes. Default and minimum size is 1 character.

CLOB A character large object containing single byte characters.The maximum size is 4 gigabyte.

NCLOB A character large object containing multi-byte characters. Maximum sizeis 4 gigabyte. Stores national character set data.

BLOB A binary large object. Maximum size is 4 gigabyte.BFILE 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. Thesetables are exposed to the user through a number of views.

The collection of tables and views that contain information about the database structure (metadata) 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 theinformation about the structure of the database. The dynamic part is used to keep track of theperformance 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. Usersshould never update the Data Dictionary directly because this can result into system failure andloss of data. To retrieve data from the Data Dictionary, use standard select statements (see section3.1).

Only the most important parts of the dictionary will be discussed here. It are all views definedfor 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 thetype 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 informationfrom the current user’s schema as well as information from objects in other schemas, if thecurrent user has access to those objects by way of grants of privileges or roles.

Page 37: Tutorial de SQL Para Oracle

2.11. THE DATA DICTIONARY 37

• A DBA view displays all relevant information in the entire database. DBA views are intendedonly for administrators. They can be accessed only by users with the SELECT ANY TABLEprivilege.

• A USER view displays all the information from the schema of the current user. No specialprivileges 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 descriptionof 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 deter-mined 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.

Page 38: Tutorial de SQL Para Oracle

38 CHAPTER 2. DATA DEFINITION LANGUAGE

ALL SOURCE, DBA SOURCE, USER SOURCE

Contains the source code for programmed objects of type: PROCEDURE, PACKAGE, FUNC-TION, 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 databaseadministrator 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.

Page 39: Tutorial de SQL Para Oracle

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 eachof 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 canbe seen from the syntax diagram. The following sections explain the use and semantics of eachclause.

-®­

©ªSELECT -

®­

©ªDISTINCT

-®­

©ªUNIQUE

-®­

©ªALL ?

6-

®­

©ª*

- schema -®­

©ª.

6- table

- view

- snapshot ?-®­

©ª.*

- expr - AS6- c_alias

6?

®­

©ª,

?

?-

-®­

©ªFROM - query_table_expression

®­

©ª,

? - where_clause6

- group_by_clause?6-

- UNION - ALL6

- INTERSECT

- MINUS ?-®­

©ª( - subquery -

®­

©ª)

6- order_by_clause

6-

Figure 3.1: Syntax of a SELECT statement

39

Page 40: Tutorial de SQL Para Oracle

40 CHAPTER 3. DATA MANIPULATION LANGUAGE

- schema -®­

©ª.

6- table

- view

- snapshot ?-®­

©ª@ - dblink

6

-®­

©ª( - subquery -

®­

©ª) ?- t_alias

6-

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 thequery. 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 arein the scope of the query (specified by the from clause). With this option you cannot select anyadditional fields.

The second option is to select all the fields of one table, view or snapshot. This is done byspecifying 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 expressionsis discussed in section 3.2. Each field can have an alias. This alias is used as a fieldname in theresult of the query.

The keywords UNIQUE, DISTINCT and ALL in the beginning of the select clause are usedto influence the output of rows. If you don’t want the query to show duplicate rows in the result,use DISTINCT or UNIQUE (which are synonyms). By default duplicate rows are shown, but thekeyword 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, suchas views and subqueries) that are involved in the query. These tables are specified in a commaseparated 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 implementationsdon’t 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 restrictsthe rows selected by the query to those that satisfy the condition. The construction of a conditionis 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 thatapply 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 Ref-erence), 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

Page 41: Tutorial de SQL Para Oracle

3.1. RETRIEVING DATA FROM THE DATABASE 41

3.1.4 Joining tables

To be able to construct correct queries, it is very important to understand how the data of differenttables 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 eachother as a Cartesian product. This means that every row of one table is combined with every rowof 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 don’t want to include all the rowsof 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 ofthe first table corresponds to a key value of the second table (e.g. a primary key - foreign keycorrespondence). This restriction can be obtained by adding so called join conditions to thewhere clause. A join condition looks like a = b with a the key attribute of one table and b thecorresponding 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 onefield), 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 rowsof 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 allrows that match the join condition completed with all rows of one table that have no match in theother table. The fields taken from the other table (the outer table) are filled with NULL valuesin 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 fieldof the outer table. Note that the syntax to construct outer joins varies a lot between differentdatabase systems.

Self join

Sometimes it is necessary to join a table with itself. In this case, each occurrence of the table ishandled 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 togetherinto groups of rows so that all rows of each group have the same value for the expressions mentionedin the grouping clause. Each group is then summarized (aggregated) to one single row. Aggregatefunctions can be used to compute single row results from groups of values. See section 3.2.3 foran 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 forrows of the same group.

Page 42: Tutorial de SQL Para Oracle

42 CHAPTER 3. DATA MANIPULATION LANGUAGE

-®­

©ªGROUP -

®­

©ªBY - expr

®­

©ª,

?

- expr

®­

©ª,

?6-

®­

©ªCUBE

-®­

©ªROLLUP ?-

®­

©ª( - expr

®­

©ª,

? -®­

©ª) ?-

®­

©ªHAVING - condition

6-

Figure 3.5: The GROUP BY clause

The ROLLUP option

The ROLLUP option is used to produce subtotal values. A normal select statement with groupingproduces one row for each group. With the ROLLUP option some super aggregate rows, thataggregate 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 theconditions of the where clause are evaluated before the grouping takes place whereas the conditionsin the having clause are evaluated after grouping the rows. This means that conditions that containaggregate 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 areunordered. In practice however it’s often useful to have the results of a query ordered in someway.

-®­

©ªORDER -

®­

©ªBY - expr

- position

- c_alias ? -®­

©ªASC

-®­

©ªDESC ?

6-

®­

©ªNULLS -

®­

©ªFIRST

-®­

©ªNULLS -

®­

©ªLAST ?

6

®­

©ª,

?

-

The order by clause can contain more than one field. If so, the precedence of the fields goesfrom 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 defaultsorting order is ascending. The place of null values can be specified by the use of the keywordsNULLS FIRST or NULLS LAST. The default is NULLS LAST for ascending order and NULLSFIRST 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 allof these types are allowed in all situations. Furthermore, you have to make sure that the datatype

Page 43: Tutorial de SQL Para Oracle

3.2. EXPRESSIONS 43

of the result of the expression is useful in its context. For instance, if the result of an expressionis 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 -®­

©ª.

6- table

- view

- snapshot ?-®­

©ª.

6- column

- pseudocolumn ?

- text

- number

- sequence -®­

©ª. -

®­

©ªCURRVAL

-®­

©ªNEXTVAL ?

- NULL ?-

Simple expressions can be each of the following:Column referenceRefers to a (pseudo)column in the scope of the query.LiteralLiteral values can be text (string between single quotes) or numeric.Sequence referenceCalls the current or the next value of the sequence at hand. Calling the next value of a sequenceincreases this sequence with one step.NULLRepresents an empty field.

Page 44: Tutorial de SQL Para Oracle

44 CHAPTER 3. DATA MANIPULATION LANGUAGE

3.2.2 Compound expressions

-®­

©ª( - expr -

®­

©ª)

-®­

©ª+

-®­

©ª- ?- expr

- expr -®­

©ª*

-®­

©ª/

-®­

©ª+

-®­

©ª-

-®­

©ª|| ?- expr ?-

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

3.2.3 Function expressions

- schema -®­

©ª.

6- package -

®­

©ª.

6- function

- user_defined_function ?-®­

©ª@ - dblink

6-

-®­

©ª( -

®­

©ªDISTINCT

-®­

©ªALL ?

6- expr

- subquery ?

®­

©ª,

?

-®­

©ª)

6-

Function expressions call a built-in or user defined function. All functions should be single rowfunctions (this is: returning one value rather than a collection of values). The number and thetype of the provided parameters has to match the function definition.

Aggregate functions summarize a group of values into one value . The keywords DISTINCT andALL can be used to adjust the behavior of some aggregate functions. For instance COUNT(ALLprice) and COUNT(DISTINCT price) will return different results if duplicate prices occur, whereasMAX(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) Absolute value of n.BITAND(m,n) Bitwise ANDCEIL(n) Computes the ceiling of a real number. Returns an integer.COS(n) CosinusEXP(n) Returns e raised to the nth powerFLOOR(n) Computes the floor of a real number. Returns an integer.LN(n) Takes the natural logarithm of n.LOG(m,n) Returns the logarithm base m of n.MOD(m,n) Returns the remainder of m divided by n.

Page 45: Tutorial de SQL Para Oracle

3.2. EXPRESSIONS 45

POWER(m,n) Returns m raised to the nth power.(if m is negative, n must be an integer)

ROUND(n [,m]) Rounds n up to m places right of the decimal point(default for m is 0).

SIGN(n) Returns -1, 0, or 1 according to the sign of n.SIN(n) Sinus.SQRT(n) Square root.TAN(n) Tangens.TRUNC(n [,m]) Truncates n to m places right of the decimal point

(default for m is 0).

Character functions returning characters

CHR(n) Returns the character with binary representation of n.CONCAT(c,d) Concatenates two character strings. This function is equivalent to the

concatenation operator ‖.LOWER(c) Change all characters of c to lower case.LTRIM(c) Removes blanks from the left of c.REPLACE(c,s,r) Returns c with all occurrences of s replaced by r.RTRIM(c) Removes blanks from the right of c.SUBSTR(c,m [,n]) 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.TRANSLATE(c,f ,t) Every occurrence of a character of f in c is replaced by it’s

corresponding character in t.TRIM(c) Remove both leading and trailing blanks from c.UPPER(c) Change all characters of c to upper case.

Character functions returning numbers

ASCII(c) Returns the numeric value of the first character of c in the character set used.INSTR(s1,s2 [,p [,n]]) 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.

LENGTH(c) Returns the number of characters of c.

Date functions

ADD MONTHS(d,n) Adds n months to date d.LAST DAY(d) Returns the date of the last day of the month that contains d.NEXT DAY(d,c) Returns the date of the first weekday c following d.ROUND(d [,u]) Rounds d to the unit u (e.q. ’month’).

Default for u is ’DDD’ (day).SYSDATE Returns the current date and time.TRUNC(d [,u]) Truncates d to the unit u (e.q. ’year’)

Default for u is ’DDD’.

Conversion functions

TO CHAR(d [,f ]) Converts a date d to a string using format string f .TO CHAR(n [,f ]) Converts a number to a string using format string f .TO DATE(c [,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 datefunctions.

Page 46: Tutorial de SQL Para Oracle

46 CHAPTER 3. DATA MANIPULATION LANGUAGE

Element Description- / , . ; : ”text” Punctuation and quoted text is reproduced in the result.SS Second (00-59).SSSSS Seconds past midnight (0-86399).MI Minute (00-59).HH Hour of day (01-12).HH12 Hour of day (01-12).HH24 Hour of day (00-23).D Day of week (1-7).DAY Name of day, padded with blanks to length of 9 characters.DY Abbreviated name of day.DD Day of month (01-31).DDD Day of year (001-366).IW Week of year (01-52 or 01-53) based on the ISO standard.WW 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.W Week of month (1-5) where week 1 starts on the first day

of the month and ends on the seventh.MM Two-digit numeric abbreviation of month (01-12; JAN = 01)MON Abbreviated name of month.MONTH Name of month, padded with blanks to length of 9 characters.RM Roman numeral month (I-XII; JAN = I).Q Quarter of year (1, 2, 3, 4; JAN-MAR = 1)IYY, IY, I Last 3, 2, or 1 digit(s) of ISO year.IYYY 4-digit year based on the ISO standard.J Julian day; the number of days since January 1, 4712 BC.YEAR, SYEAR Year, spelled out. ”S” prefixes BC dates with ”-”.YYYY, SYYYY 4-digit year. ”S” prefixes BC dates with ”-”.YYY, YY, Y Last 3, 2, or 1 digit(s) of year.

Table 3.1: Format strings in date functions

Aggregate functions

AVG(n) Computes the average of a set of numbers.COUNT(x) Counts the number of elements encountered.MAX(x) Returns the maximum value of a group.MIN(x) Returns the minimum value of a group.STD DEV(n) Computes the standard deviation of a group of numbers.SUM(n) Returns the sum of a group of numbers.VARIANCE(n) Computes the variance of group of numbers.

3.2.4 CAST expressions

-®­

©ªCAST -

®­

©ª( - expr

-®­

©ª( - subquery -

®­

©ª)

-®­

©ªMULTISET -

®­

©ª( - subquery -

®­

©ª) ?-

®­

©ªAS - type_name -

®­

©ª) -

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

Page 47: Tutorial de SQL Para Oracle

3.3. CONDITIONS 47

Of course it is not possible to do every casting, the table 3.2 shows what kind of conversionshave been supported. On the other hand, not every casting needs a casting expression, in somesituations, casting will occur automatically.

from/ CHAR, ROWID, NCHAR,to VARCHAR2 NUMBER DATE RAW UROWID NVARCHAR2CHAR,VARCHAR2 X X X X XNUMBER X XDATE X XRAW X XROWID,UROWID X XNCHAR,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 expres-sion. The following arguments are (search, result) pairs. The evaluation of the first argument iscompared with the search values of these pairs (in left to right order). If a match is found, theresult value of the pair is returned. The last argument is an optional default value. This value isreturned if no matching search value is found. If there is no matching search value and the defaultvalue is omitted, the result will be null.

3.2.6 CASE expressions

-®­

©ªCASE -

®­

©ªWHEN - condition -

®­

©ªTHEN - expr? -

®­

©ªELSE - expr

6-

®­

©ªEND -

CASE expressions are used to make the content of field dependent on some condition(s). TheCASE keyword is followed by one or more when - then clauses. The condition of the first whenclause is evaluated, if it is true, the expression of the then clause is evaluated else the condition ofthe next when clause (if present) is evaluated, and so on. If the last condition fails, the expressionof 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 ex-pressions.

Page 48: Tutorial de SQL Para Oracle

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 -®­

©ª=

-®­

©ª!=

-®­

©ª^=

-®­

©ª<>

-®­

©ª>

-®­

©ª<

-®­

©ª>=

-®­

©ª<= ?- expr

-®­

©ª( - subquery -

®­

©ª) ?

- expr_list -®­

©ª=

-®­

©ª!=

-®­

©ª^=

-®­

©ª<> ?-

®­

©ª( - subquery -

®­

©ª) ?-

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). Theresult will be true if and only if all comparisons are true. Note that only single-row subqueries areallowed.

Page 49: Tutorial de SQL Para Oracle

3.3. CONDITIONS 49

3.3.2 Group comparison conditions

- expr -®­

©ª=

-®­

©ª!=

-®­

©ª^=

-®­

©ª<>

-®­

©ª>

-®­

©ª<

-®­

©ª>=

-®­

©ª<= ?-

®­

©ªANY

-®­

©ªSOME

-®­

©ªALL ?- expr_list

-®­

©ª( - subquery -

®­

©ª) ?

- expr_list -®­

©ª=

-®­

©ª!=

-®­

©ª^=

-®­

©ª<> ?-

®­

©ªANY

-®­

©ªSOME

-®­

©ªALL ?-

®­

©ª( - expr_list

- subquery ?

®­

©ª,

?

-®­

©ª) ?-

Group comparison conditions are used to compare one value (or a value list) with each element ofa set of values (or a set of value lists). The keywords ALL, ANY and SOME determine when theexpression is true or false.

If the keyword ANY or SOME is used the expression is true if and only if at least one comparisonis 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. Thisimplies that the result is true if the subquery returns no rows.

3.3.3 Membership conditions

- expr -®­

©ªNOT

6-

®­

©ªIN - expr_list

-®­

©ª( - subquery -

®­

©ª) ?

- expr_list -®­

©ªNOT

6-

®­

©ªIN -

®­

©ª( - expr_list

- subquery ?

®­

©ª,

?

-®­

©ª) ?-

Page 50: Tutorial de SQL Para Oracle

50 CHAPTER 3. DATA MANIPULATION LANGUAGE

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

3.3.4 Range conditions

- expr -®­

©ªNOT

6-

®­

©ªBETWEEN - expr -

®­

©ªAND - expr -

A range conditions is true if the value of the first expression is greater or equal than the value ofthe 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

6-

®­

©ªNULL -

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

6-

®­

©ªLIKE - char -

®­

©ªESCAPE - char

6-

Like conditions compare strings to a string pattern. Oracle has only two wildcard characters thatcan 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 op-erators.

Page 51: Tutorial de SQL Para Oracle

3.4. INSERTING DATA INTO THE DATABASE 51

3.4 Inserting data into the database

-®­

©ªINSERT -

®­

©ªINTO - DML_table_expression -

®­

©ª( - column

®­

©ª,

? -®­

©ª)

6- value_clause

- subquery ?-

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

- schema -®­

©ª.

6- table

- view

- snapshot ?-®­

©ª@ - dblink

6

-®­

©ª( - 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 namesthat 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 isassumed 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 isomitted, the value clause should contain a value for each column. Note that insert statementswith 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 acorresponding 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

6-

Page 52: Tutorial de SQL Para Oracle

52 CHAPTER 3. DATA MANIPULATION LANGUAGE

With an update statement it is possible to change the data in a table (view, snapshot, etc.). Anupdate statement doesn’t 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 ofDML table expression) comes the set clause. This clause tells the query engine which fields haveto be updated and how to compute their new values. Only single row subqueries can be used inthe 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, allrows of the table are updated, otherwise only those rows that satisfy the condition in the whereclause are updated.

3.6 Deleting data from the database

-®­

©ªDELETE -

®­

©ªFROM - DML_table_expression - where_clause

6-

Use a delete statement to remove rows from a table. See section 3.4 for the syntax ofDML 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.