SlideShare une entreprise Scribd logo
1  sur  135
Télécharger pour lire hors ligne
Published by CFS Documentation Cell
Centre for Electronics Design and Technology of India
An Autonomous Scientific Society under Department of Electronics,
Govt. of India,
New Delhi.




First Edition: 1999




TRADEMARKS: All brand name and product names mentioned in this book are trademarks or registered trademark of their
respective companies.

Every effort has been made to supply complete and accurate information. However, CEDTI assumes no responsibility for its
use, nor for any infringement of the intellectual property rights of third parties which would result from such use.

No part of this publication may be stored in a retrieval system, transmitted or reproduced in any forms or by any means,
electronic, photocopy, photograph, magnetic or otherwise, without written permission of CEDTI.



CEDTI/CFS/99/6/3.2/R1
FOREWORD

      The information technology and telecom sectors have suddenly opened up avenues,
which require a very large specially trained manpower. These sectors are highly dynamic and
need training and re-training of manpower at a rapid rate. The growing gap of requirement of
the industry and its fulfillment has created a challenging situation before manpower training
institutes of the country. To meet this challenge most effectively, Centre for Electronics Design
and Technology of India (CEDTI) has launched its nation-wide franchising scheme.

     Centre for Electronics Design and Technology of India (CEDTI) is an Autonomous
Scientific Society under the Govt. of India, Department of Electronics with its Headquarters at
New Delhi. It operates seven centres located at Aurangabad, Calicut, Gorakhpur, Imphal,
Mohali, Jammu and Tezpur. The scheme will be implemented and coordinated by these centres.

     The scheme endeavours to promote high quality computer and information technology
education in the country at an affordable cost while ensuring uniform standards in order to
build a national resource of trained manpower. Low course fees will make this education
available to people in relatively small, semi urban and rural areas. State-of-the-art training will
be provided keeping in view the existing and emerging needs of the industrial and Govt.
sectors. The examinations will be conducted by CEDTI and certificates will also be awarded
by CEDTI. The scheme will be operated through all the seven centres of CEDTI.

     The CEDTI functions under the overall control and guidance of the Governing Council
with Secretary, Department of Electronics as its Chairman. The members of the council are
drawn from scientific, government and industrial sectors. The Centres have separate executive
committees headed by Director General, CEDTI. The members of these committees are from
academic/professional institutes, state governments, industry and department of electronics.

      CEDTI is a quality conscious organisation and has taken steps to formally get recognition
of the quality and standards in various activities. CEDTI, Mohali was granted the prestigious
ISO 9002 certificate in 1997. The other centres have taken steps to obtain the certification as
early as possible. This quality consciousness will assist CEDTI in globalizing some of its
activities. In keeping with its philosophy of ‘Quality in every Activity’, CEDTI will endeavour to
impart state of the art – computer and IT training through its franchising scheme.

     The thrust of the Software Courses is to train the students at various levels to carry out
the Management Information System functions of a medium sized establishment, manufacture
Software for domestic and export use, make multimedia presentations for management and
effectively produce various manufacturing and architectural designs.
The thrust of the Hardware Courses at Technician and Telecommunication Equipment
Maintenance Course levels is to train the students to diagnose the faults and carry out repairs
at card level in computers, instruments, EPABX, Fax etc. and other office equipment. At
Engineer and Network Engineer levels the thrust is to train them as System Engineers to
install and supervise the Window NT, Netware and Unix Networking Systems and repair
Microcontrollers / Microprocessor based electronic applications.

      An Advisory Committee comprising eminent and expert personalities from the Information
Technology field have been constituted to advise CEDTI on introduction of new courses and
revising the syllabus of existing courses to meet the changing IT needs of the trade, industry
and service sectors. The ultimate objective is to provide industry-specific quality education in
modular form to supplement the formal education.

     The study material has been prepared by the CEDTI, document centre. It is based on
the vast and rich instructional experience of all the CEDTI centres. Any suggestions on the
improvement of the study material will be most welcome.



                                                                             (R. S. Khandpur)
                                                                     Director General (CEDTI)
TABLE OF CONTENTS

UNIT   CHAPTER NAME                 PAGE NO.


1      BASIC FEATURES OF ORACLE           11

2      SQL - AN INTRODUCTION              31

3      OPERATORS USED IN ORACLE           53

4      DATA MANIPULATION LANGUAGE         99

5      PL/SQL & ITS FEATURES             119
preface
BASIC FEATURES OF ORACLE




COMPETENCY OBJECTIVES

This chapter covers the following topics

      v        Basic features of oracle
      v        Oracle server – introduction
      v        Database – introduction
      v        Physical files
      v        Logical structure
      v        Memory structure
      v        Background processes
      v        SQL, PL/SQL – introduction
ORACLE




10
ORACLE


                                                                                   CHAPTER - 1




   BASIC FEATURES OF ORACLE


ORACLE SERVER - AN INTRODUCTION

The Oracle server is an object-relational database management system . It provides an open,
comprehensive, and integrated approach to information management. An Oracle server is combination
of an Oracle database and an Oracle server instance.

STRUCTURED QUERY LANGUAGE (SQL)

SQL is the programming language that defines and manipulates the database. SQL databases are
relational databases which implies that data is stored in a set of simple relations. A database can have
one or more tables. And each table has columns and rows.

In addition to SQL commands, the Oracle server has a procedural language called PL/SQL. PL/SQL
enables the programmer to program SQL statements. It allows you to control the flow of a SQL program,
to use variables, and to write error-handling procedures.

DATABASE ARCHITECTURE

                                             Database Structure




               Physical Database Structure                        Logical Database Structure

Database Structure

An Oracle database has both a physical and a logical structure. Because the physical and logical server
structure are separate, the physical storage of data can be managed without affecting the access to
logical storage structures.

Physical Database Structure

An Oracle database’s physical structure is determined by the operating system files that constitute the
database. Each Oracle database is made of three types of files: one or more datafiles, two or more redo

                                                   11
ORACLE

log files, and one or more control files. The files of an Oracle database provide the actual physical
storage for database information.

Logical Database Structure

An Oracle database’s logical structure is determined by:

•      one or more tablespaces
       A tablespace is a logical area of storage.
•      the database’s schema objects
       A schema is a collection of objects. Schema objects are the logical structures that directly refer
       to the database’s data. Schema objects include such structures as tables, views, sequences, stored
       procedures, synonyms, indexes, clusters, and database links.

The logical storage structures, including tablespaces, segments, and extents, dictate how the physical
space of a database is used. The schema objects and the relationships among them form the relational
design of a database.

AN ORACLE INSTANCE

Every time a database is started, a system global area (SGA) is allocated and Oracle background processes
are started. The system global area is a an area of memory used for database information shared by the
database users. The combination of the background processes and memory buffers is called an Oracle
instance.

An Oracle instance has two types of processes: user processes and Oracle processes.




                                     Fig. 1-1 : An Oracle Instance

•      A user process executes the code of an application program (such as an Oracle Forms applica-
       tion) or an Oracle Tool (such as Oracle Enterprise Manager).
•      Oracle processes are server processes that perform work for the user processes and background
       processes that perform maintenance work for the Oracle server.
Figure 1-1 illustrates a multiple-process Oracle instance.
                                                   12
ORACLE

ORACLE DATABASES

An Oracle database is the collection of data that is treated as a unit. The general purpose of a database
is to store and retrieve related information.

Open and Closed Databases

An Oracle database can be open (accessible) or closed (not accessible). In normal situations, the data-
base is open and available for use. However, the database is sometimes closed for specific administra-
tive functions that require the database’s data to be unavailable to users.

ARCHITECTURE OF DATABASE

The database has logical structures and physical structures.

Logical Database Structures

The following sections explain logical database structures, including tablespaces, schema objects, data
blocks, extents, and segments.

Tablespaces

A database is divided into logical storage units called tablespaces. A tablespace is used to group related
logical structures together. For example, tablespaces commonly group all of an application’s objects to
simplify some administrative operations.

Databases, Tablespaces, and Datafiles

The relationship among databases, tablespaces, and datafiles (datafiles are described in the next section)
is illustrated in Figure 1-2.




                           Figure 1-2 Databases, Tablespaces, and Datafiles

This figure illustrates the following:
•       Each database is logically divided into one or more tablespaces.
•       One or more datafiles are explicitly created for each tablespace to physically store the data of all
        logical structures in a tablespace.



                                                    13
ORACLE

Online and Offline Tablespaces

A tablespace can be online (accessible) or offline (not accessible). A tablespace is normally online so
that users can access the information within the tablespace. However, sometimes a tablespace may be
taken offline to make a portion of the database unavailable while allowing normal access to the remainder
of the database. This makes many administrative tasks easier to perform.

MEMORY STRUCTURE OF ORACLE DATABASE

An Oracle server uses memory structures and processes to manage and access the database. All memory
structures exist in the main memory of the computers that constitute the database system. Processes are
jobs or tasks that work in the memory of these computers. Figure 1-3 shows a typical variation of the
Oracle server memory and process structures.

Memory Structures

Oracle creates and uses memory structures to complete several jobs. For example, memory stores program
code being executed and data that is shared among users. Several basic memory structures are associated
with Oracle: the system global area (which includes the database buffers, redo log buffers, and the
shared pool) and the program global areas. The following subsections explain each in detail.




                        Figure 1-3 Memory Structures and Processes of Oracle
                                                   14
ORACLE

SYSTEM GLOBAL AREA

The System Global Area (SGA) is a shared memory region that contains data and control information
for one Oracle instance. An SGA and the Oracle background processes constitute an Oracle instance.
Oracle allocates the system global area when an instance starts and deallocates it when the instance
shuts down. Each instance has its own system global area.

Users currently connected to an Oracle server share the data in the system global area. For optimal
performance, the entire system global area should be as large as possible (while still fitting in real
memory) to store as much data in memory as possible and minimize disk I/O.
The information stored within the system global area is divided into several types of memory struc-
tures, including the database buffers, redo log buffer, and the shared pool. These areas have fixed sizes
and are created during instance startup.

Database Buffer Cache

Database buffers of the system global area store the most recently used blocks of database data; the set
of database buffers in an instance is the database buffer cache. The buffer cache contains modified as
well as unmodified blocks. Because the most recently (and often the most frequently) used data is kept
in memory, less disk I/O is necessary and performance is improved.

Redo Log Buffer

The redo log buffer of the system global area stores redo entries - a log of changes made to the database.
The redo entries stored in the redo log buffers are written to an online redo log file, which is used if
database recovery is necessary. Its size is static.

Shared Pool

The shared pool is a portion of the system global area that contains shared memory constructs such as
shared SQL areas. A shared SQL area is required to process every unique SQL statement submitted to
a database. A shared SQL area contains information such as the parse tree and execution plan for the
corresponding statement. A single shared SQL area is used by multiple applications that issue the same
statement, leaving more shared memory for other uses.

Statement Handles or Cursors

A cursor is a handle (a name or pointer) for the memory associated with a specific statement. (The
Oracle Call Interface, OCI, refers to these as statement handles.) Although most Oracle users rely on
the automatic cursor handling of the Oracle utilities, the programmatic interfaces offer application
designers more control over cursors.

For example, in precompiler application development, a cursor is a named resource available to a
program and can be specifically used for the parsing of SQL statements embedded within the application.
The application developer can code an application so that it controls the phases of SQL statement
execution and thus improve application performance.



                                                   15
ORACLE

BACKGROUND PROCESSES

Oracle creates a set of background processes for each instance. They consolidate functions that would
otherwise be handled by multiple Oracle programs running for each user process. The background
processes asynchronously perform I/O and monitor other Oracle processes to provide increased paral-
lelism for better performance and reliability.

An SGA and the set of Oracle background processes constitute an Oracle instance. Each Oracle in-
stance may use several background processes. The names of these processes are DBWn, LGWR, CKPT,
SMON, PMON, ARCH, RECO, Dnnn, LCKn, SNPn, and QMNn.

Database Writer (DBWn)

The Database Writer writes modified blocks from the database buffer cache to the datafiles. Although
one database writer process (DBW0) is sufficient for most systems, you can configure additional pro-
cesses (DBW1 through DBW9) to improve write performance for a system that modifies data heavily.
The initialization parameter DB_WRITER_PROCESSES specifies the number of DBWn processes.

Since Oracle uses write-ahead logging, DBWn does not need to write blocks when a transaction com-
mits. Instead, DBWn is designed to perform batched writes with high efficiency. In the most common
case, DBWn writes only when more data needs to be read into the system global area and too few
database buffers are free. The least recently used data is written to the datafiles first. DBWn also per-
forms writes for other functions such as checkpointing.

Log Writer (LGWR)

The Log Writer writes redo log entries to disk. Redo log data is generated in the redo log buffer of the
system global area. As transactions commit and the log buffer fills, LGWR writes redo log entries into
an online redo log file.

Checkpoint (CKPT)

At specific times, all modified database buffers in the system global area are written to the datafiles by
DBWn; this event is called a checkpoint. The Checkpoint process is responsible for signalling DBWn
at checkpoints and updating all the datafiles and control files of the database to indicate the most recent
checkpoint.

System Monitor (SMON)

The system monitor performs instance recovery at instance startup. In a multiple instance system (one
that uses Oracle Parallel Server), SMON of one instance can also perform instance recovery for other
instances that have failed. SMON also cleans up temporary segments that are no longer in use and
recovers dead transactions skipped during crash and instance recovery because of file-read or offline
errors. These transactions are eventually recovered by SMON when the tablespace or file is brought
back online. SMON also coalesces free extents within the database to make free space contiguous and
easier to allocate.



                                                    16
ORACLE

Process Monitor (PMON)

The process monitor performs process recovery when a user process fails. PMON is responsible for
cleaning up the cache and freeing resources that the process was using. PMON also checks on dispatcher
(see below) and server processes and restarts them if they have failed.

THE PROGRAM INTERFACE

The program interface is the mechanism by which a user process communicates with a server process.
It serves as a method of standard communication between any client tool or application (such as Oracle
Forms) and Oracle software. Its functions are to:

•      act as a communications mechanism, by formatting data requests, passing data, and trapping
       and returning errors
•      perform conversions and translations of data, particularly between different types of computers
       or to external user program datatypes

AN EXAMPLE OF HOW ORACLE WORKS

The following example illustrates an Oracle configuration where the user and associated server process
are on separate machines (connected via a network).

1.     An instance is currently running on the computer that is executing Oracle (often called the host
       or database server).
2.     A computer running an application (a local machine or client workstation) runs the application
       in a user process. The client application attempts to establish a connection to the server using
       the proper Net8 driver.
3.     The server is running the proper Net8 driver. The server detects the connection request from the
       application and creates a (dedicated) server process on behalf of the user process.
4.     The user executes a SQL statement and commits the transaction. For example, the user changes
       a name in a row of a table.
5.     The server process receives the statement and checks the shared pool for any shared SQL area
       that contains an identical SQL statement. If a shared SQL area is found, the server process
       checks the user’s access privileges to the requested data and the previously existing shared SQL
       area is used to process the statement; if not, a new shared SQL area is allocated for the statement
       so that it can be parsed and processed.
6.     The server process retrieves any necessary data values from the actual datafile (table) or those
       stored in the system global area.
7.     The server process modifies data in the system global area. The DBWn process writes modified
       blocks permanently to disk when doing so is efficient. Because the transaction committed, the
       LGWR process immediately records the transaction in the online redo log file.
8.     If the transaction is successful, the server process sends a message across the network to the
       application. If it is not successful, an appropriate error message is transmitted.
9.     Throughout this entire procedure, the other background processes run, watching for conditions
       that require intervention. In addition, the database server manages other users’ transactions and
       prevents contention between transactions that request the same data.

These steps describe only the most basic level of operations that Oracle performs.
                                                   17
ORACLE

DATA CONCURRENCY AND CONSISTENCY

This section explains the software mechanisms used by Oracle to fulfill the following important re-
quirements of an information management system:

•       Data must be read and modified in a consistent fashion.
•       Data concurrency of a multi-user system must be maximized.
•       High performance is required for maximum productivity from the many users of the database
        system.

Concurrency

A primary concern of a multiuser database management system is how to control concurrency, or the
simultaneous access of the same data by many users. Without adequate concurrency controls, data
could be updated or changed improperly, compromising data integrity.

If many people are accessing the same data, one way of managing data concurrency is to make each
user wait his or her turn. The goal of a database management system is to reduce that wait so it is either
non-existent or negligible to each user. All data manipulation (DML) statements should proceed with
as little interference as possible and destructive interactions between concurrent transactions must be
prevented. Destructive interaction is any interaction that incorrectly updates data or incorrectly alters
underlying data structures. Neither performance nor data integrity can be sacrificed.

Oracle resolves such issues by using various types of locks and a multiversion consistency model. Both
features are discussed later in this section. These features are based on the concept of a transaction. It is
the application designer’s responsibility to ensure that transactions fully exploit these concurrency and
consistency features.

READ CONSISTENCY

Read consistency, as supported by Oracle, does the following:

•       guarantees that the set of data seen by a statement is consistent with respect to a single point-in-
        time and does not change during statement execution (statement-level read consistency)
•       ensures that readers of database data do not wait for writers or other readers of the same data
•       ensures that writers of database data do not wait for readers of the same data
•       ensures that writers only wait for other writers if they attempt to update identical rows in con-
        current transactions

The simplest way to think of Oracle’s implementation of read consistency is to imagine each user
operating a private copy of the database, hence the multiversion consistency model.

Read Consistency, Rollback Segments, and Transactions

To manage the multiversion consistency model, Oracle must create a read-consistent set of data when
a table is being queried (read) and simultaneously updated (written). When an update occurs, the origi-
nal data values changed by the update are recorded in the database’s rollback segments. As long as this

                                                     18
ORACLE

update remains part of an uncommitted transaction, any user that later queries the modified data views
the original data values - Oracle uses current information in the system global area and information in
the rollback segments to construct a read-consistent view of a table’s data for a query.

Only when a transaction is committed are the changes of the transaction made permanent. Statements
that start after the user’s transaction is committed only see the changes made by the committed transac-
tion.

Note that a transaction is key to Oracle’s strategy for providing read consistency. This unit of commit-
ted (or uncommitted) SQL statements:

•      dictates the start point for read-consistent views generated on behalf of readers
•      controls when modified data can be seen by other transactions of the database for reading or
       updating.

Read-Only Transactions

By default, Oracle guarantees statement-level read consistency. The set of data returned by a single
query is consistent with respect to a single point in time. However, in some situations, you may also
require transaction-level read consistency - the ability to run multiple queries within a single transac-
tion, all of which are read-consistent with respect to the same point in time, so that queries in this
transaction do not see the effects of intervening committed transactions.

If you want to run a number of queries against multiple tables and if you are doing no updating, you
may prefer a read-only transaction. After indicating that your transaction is read-only, you can execute
as many queries as you like against any table, knowing that the results of each query are consistent with
respect to the same point in time.

LOCKING MECHANISMS

Oracle also uses locks to control concurrent access to data. Locks are mechanisms intended to prevent
destructive interaction between users accessing Oracle data.

Locks are used to achieve two important database goals:

consistency        Ensures that the data a user is viewing or changing is not changed (by other users)
                   until the user is finished with the data.
integrity          Ensures that the database’s data and structures reflect all changes made to them in
                   the correct sequence.

Locks guarantee data integrity while allowing maximum concurrent access to the data by unlimited
users.

Automatic Locking

Oracle locking is performed automatically and requires no user action. Implicit locking occurs for SQL
statements as necessary, depending on the action requested.

                                                   19
ORACLE

Oracle’s sophisticated lock manager automatically locks table data at the row level. By locking table
data at the row level, contention for the same data is minimized.

Oracle’s lock manager maintains several different types of row locks, depending on what type of opera-
tion established the lock. In general, there are two types of locks: exclusive locks and share locks. Only
one exclusive lock can be obtained on a resource (such as a row or a table); however, many share locks
can be obtained on a single resource. Both exclusive and share locks always allow queries on the
locked resource, but prohibit other activity on the resource (such as updates and deletes).

Manual Locking

Under some circumstances, a user may want to override default locking. Oracle allows manual over-
ride of automatic locking features at both the row level (by first querying for the rows that will be
updated in a subsequent statement) and the table level.

ORDBMS

Database management systems have evolved from hierarchical to network to relational models. The
most widely accepted database model is the relational model. Oracle extends the relational model to an
object-relational model, which makes it possible to store complex business models in a relational
database.

The Relational Model

The relational model has three major aspects:

structures         Structures are well-defined objects (such as tables, views, indexes, and so on) that
                   store or access the data of a database. Structures and the data contained within them
                   can be manipulated by operations.
operations         Operations are clearly defined actions that allow users to manipulate the data and
                   structures of a database. The operations on a database must adhere to a predefined
                   set of integrity rules.
integrity rules    Integrity rules are the laws that govern which operations are allowed on the data and
                   structures of a database. Integrity rules protect the data and the structures of a database.

Relational database management systems offer benefits such as:

•       independence of physical data storage and logical database structure
•       variable and easy access to all data
•       complete flexibility in database design
•       reduced data storage and redundancy

THE OBJECT-RELATIONAL MODEL

The object-relational model allows users to define object types, specifying both the structure of the data
and the methods of operating on the data, and to use these datatypes within the relational model.


                                                     20
ORACLE

Object types are abstractions of the real-world entities - for example, purchase orders - that application
programs deal with. An object type has three kinds of components:
•      A name, which serves to identify the object type uniquely.
•      Attributes, which are built-in datatypes or other user-defined types. Attributes model the struc-
       ture of the real world entity.
•      Methods, which are functions or procedures written in PL/SQL and stored in the database, or
       written in a language like C and stored externally. Methods implement specific operations that
       an application can perform on the data. Every object type has a constructor method that makes
       a new object according to the datatype’s specification.

SCHEMAS AND SCHEMA OBJECTS

A schema is a collection of database objects that are available to a user. Schema objects are the logical
structures that directly refer to the database’s data. Schema objects include such structures as tables,
views, sequences, stored procedures, synonyms, indexes, clusters, and database links. (There is no
relationship between a tablespace and a schema; objects in the same schema can be in different
tablespaces, and a tablespace can hold objects from different schemas.)

Tables

A table is the basic unit of data storage in an Oracle database. The tables of a database hold all of the
user-accessible data.

Table data is stored in rows and columns. Every table is defined with a table name and set of columns.
Each column is given a column name, a datatype (such as CHAR, DATE, or NUMBER), and a width
(which may be predetermined by the datatype, as in DATE) or scale and precision (for the NUMBER
datatype only). Once a table is created, valid rows of data can be inserted into it. The table’s rows can
then be queried, deleted, or updated.

Oracle8 provides for the partitioning of tables.

To enforce defined business rules on a table’s data, integrity constraints and triggers can also be defined
for a table.

Views

A view is a custom-tailored presentation of the data in one or more tables. A view can also be thought
of as a “stored query”.

Views do not actually contain or store data; rather, they derive their data from the tables on which they
are based, referred to as the base tables of the views. Base tables can in turn be tables or can themselves
be views.

Like tables, views can be queried, updated, inserted into, and deleted from, with some restrictions. All
operations performed on a view actually affect the base tables of the view.



                                                    21
ORACLE

Views are often used to do the following:
•      Provide an additional level of table security by restricting access to a predetermined set of rows
       and columns of a table. For example, a view of a table can be created so that columns with
       sensitive data (for example, salary information) are not included in the definition of the view.
•      Hide data complexity. For example, a single view can combine 12 monthly sales tables to pro-
       vide a year of data for analysis and reporting. A single view can also be used to create a join,
       which is a display of related columns or rows in multiple tables. However, the view hides the
       fact that this data actually originates from several tables.
•      Simplify commands for the user. For example, views allow users to select information from
       multiple tables without requiring the users to actually know how to perform a correlated subquery.
•      Present the data in a different perspective from that of the base table. For example, views pro-
       vide a means to rename columns without affecting the tables on which the view is based.
•      Store complex queries. For example, a query might perform extensive calculations with table
       information. By saving this query as a view, the calculations are performed only when the view
       is queried.

Views that involve a join (a SELECT statement that selects data from multiple tables) of two or more
tables can only be updated under certain conditions.

Sequences

A sequence generates a serial list of unique numbers for numeric columns of a database’s tables. Se-
quences simplify application programming by automatically generating unique numerical values for
the rows of a single table or multiple tables.

For example, assume two users are simultaneously inserting new employee rows into the EMP table.
By using a sequence to generate unique employee numbers for the EMPNO column, neither user has to
wait for the other to input the next available employee number. The sequence automatically generates
the correct values for each user.

Sequence numbers are independent of tables, so the same sequence can be used for one or more tables.
After creation, a sequence can be accessed by various users to generate actual sequence numbers.

Program Units

The term “program unit” is used in this manual to refer to stored procedures, functions, packages,
triggers, and anonymous blocks.

A procedure or function is a set of SQL and PL/SQL (Oracle’s procedural language extension to SQL)
statements grouped together as an executable unit to perform a specific task. Procedures and functions
allow you to combine the ease and flexibility of SQL with the procedural functionality of a structured
programming language. Using PL/SQL, such procedures and functions can be defined and stored in the
database for continued use. Procedures and functions are identical, except that functions always return
a single value to the caller, while procedures do not return a value to the caller.

Packages provide a method of encapsulating and storing related procedures, functions, and other pack-
age constructs together as a unit in the database. While packages provide the database administrator or

                                                   22
ORACLE

application developer organizational benefits, they also offer increased functionality and database per-
formance.

Synonyms

A synonym is an alias for a table, view, sequence, or program unit. A synonym is not actually a schema
object itself, but instead is a direct reference to a schema object. Synonyms are used to
•       mask the real name and owner of a schema object
•       provide public access to a schema object
•       provide location transparency for tables, views, or program units of a remote database
•       simplify the SQL statements for database users

A synonym can be public or private. An individual user can create a private synonym, which is avail-
able only to that user. Database administrators most often create public synonyms that make the base
schema object available for general, system-wide use by any database user.

THE DATA DICTIONARY

Each Oracle database has a data dictionary. An Oracle data dictionary is a set of tables and views that
are used as a read-only reference about the database. For example, a data dictionary stores information
about both the logical and physical structure of the database. In addition to this valuable information, a
data dictionary also stores such information as:
•       the valid users of an Oracle database
•       information about integrity constraints defined for tables in the database
•       how much space is allocated for a schema object and how much of it is in use

A data dictionary is created when a database is created. To accurately reflect the status of the database
at all times, the data dictionary is automatically updated by Oracle in response to specific actions (such
as when the structure of the database is altered). The data dictionary is critical to the operation of the
database, which relies on the data dictionary to record, verify, and conduct ongoing work. For example,
during database operation, Oracle reads the data dictionary to verify that schema objects exist and that
users have proper access to them.

DATA ACCESS

This section introduces how Oracle meets the general requirements for a DBMS to:
•      adhere to industry accepted standards for a data access language
•      control and preserve the consistency of a database’s information while manipulating its data
•      provide a system for defining and enforcing rules to maintain the integrity of a database’s
       information
•      provide high performance

SQL - THE STRUCTURED QUERY LANGUAGE

SQL is a simple, powerful database access language that is the standard language for relational data-
base management systems. The SQL implemented by Oracle Corporation for Oracle is 100 percent
compliant with the ANSI/ISO standard SQL data language.

                                                   23
ORACLE

SQL Statements

All operations on the information in an Oracle database are performed using SQL statements. A SQL
statement is a string of SQL text that is given to Oracle to execute. A statement must be the equivalent
of a complete SQL sentence, as in:

SELECT ename, deptno FROM emp;

Only a complete SQL statement can be executed, whereas a sentence fragment, such as the following,
generates an error indicating that more text is required before a SQL statement can execute:

SELECT ename

A SQL statement can be thought of as a very simple, but powerful, computer program or instruction.
SQL statements are divided into the following categories:
•     Data Definition Language (DDL) statements
•     Data Manipulation Language (DML) statements
•     transaction control statements
•     session control statements
•     system control statements
•     embedded SQL statements

Data Definition Statements (DDL)

DDL statements define, maintain, and drop schema objects when they are no longer needed. DDL
statements also include statements that permit a user to grant other users the privileges, or rights, to
access the database and specific objects within the database.

Data Manipulation Statements (DML)

DML statements manipulate the database’s data. For example, querying, inserting, updating, and delet-
ing rows of a table are all DML operations; locking a table or view and examining the execution plan of
an SQL statement are also DML operations.

Transaction Control Statements

Transaction control statements manage the changes made by DML statements. They allow the user or
application developer to group changes into logical transactions.

Session Control Statements

Session control statements allow a user to control the properties of his current session, including en-
abling and disabling roles and changing language settings. The two session control statements are
ALTER SESSION and SET ROLE.




                                                  24
ORACLE

System Control Statements

System control commands change the properties of the Oracle server instance. The only system control
command is ALTER SYSTEM; it allows you to change such settings as the minimum number of
shared servers, to kill a session, and to perform other tasks.

Embedded SQL Statements

Embedded SQL statements incorporate DDL, DML, and transaction control statements in a procedural
language program (such as those used with the Oracle Precompilers). Examples include OPEN, CLOSE,
FETCH, and EXECUTE.

PL/SQL

PL/SQL is Oracle’s procedural language extension to SQL. PL/SQL combines the ease and flexibility
of SQL with the procedural functionality of a structured programming language, such as IF ... THEN,
WHILE, and LOOP.

When designing a database application, a developer should consider the advantages of using stored PL/
SQL:
•     Because PL/SQL code can be stored centrally in a database, network traffic between applica-
      tions and the database is reduced, so application and system performance increases.
•     Data access can be controlled by stored PL/SQL code. In this case, the users of PL/SQL can
      access data only as intended by the application developer (unless another access route is granted).
•     PL/SQL blocks can be sent by an application to a database, executing complex operations with-
      out excessive network traffic.

Even when PL/SQL is not stored in the database, applications can send blocks of PL/SQL to the data-
base rather than individual SQL statements, thereby again reducing network traffic.

The following sections describe the different program units that can be defined and stored centrally in
a database.

Procedures and Functions

Procedures and functions consist of a set of SQL and PL/SQL statements that are grouped together as a
unit to solve a specific problem or perform a set of related tasks. A procedure is created and stored in
compiled form in the database and can be executed by a user or a database application. Procedures and
functions are identical except that functions always return a single value to the caller, while procedures
do not return values to the caller.

Packages

Packages provide a method of encapsulating and storing related procedures, functions, variables, and
other package constructs together as a unit in the database. While packages allow the administrator or
application developer the ability to organize such routines, they also offer increased functionality (for
example, global package variables can be declared and used by any procedure in the package) and
performance (eg. all objects of the package are parsed, compiled, and loaded into memory once).
                                                   25
ORACLE

Database Triggers

Oracle allows you to write procedures that are automatically executed as a result of an insert in, update
to, or delete from a table. These procedures are called database triggers.

Database triggers can be used in a variety of ways for the information management of your database.
For example, they can be used to automate data generation, audit data modifications, enforce complex
integrity constraints, and customize complex security authorizations.

Methods

A method is a procedure or function that is part of the definition of a user-defined datatype (object type,
nested table, or variable array).

Methods are different from stored procedures in two ways:
•     You invoke a method by referring to an object of its associated type.
•     A method has complete access to the attributes of its associated object and to information about
      its type.

Every user-defined datatype has a system-defined constructor method, that is, a method that makes a
new object according to the datatype’s specification. The name of the constructor method is the name
of the user-defined type. In the case of an object type, the constructor method’s parameters have the
names and types of the object type’s attributes. The constructor method is a function that returns the
new object as its value. Nested tables and arrays also have constructor methods.

Comparison methods define an order relationship among objects of a given object type. A map method
uses Oracle’s ability to compare built-in types. For example, Oracle can compare two rectangles by
comparing their areas if an object type called RECTANGLE has attributes HEIGHT and WIDTH and
you define a map method area that returns a number, namely the product of the rectangle’s HEIGHT
and WIDTH attributes. An order method uses its own internal logic to compare two objects of a given
object type. It returns a value that encodes the order relationship. For example, it may return -1 if the
first is smaller, 0 if they are equal, and 1 if the first is larger.

DATA INTEGRITY

It is very important to guarantee that data adheres to certain business rules, as determined by the data-
base administrator or application developer. For example, assume that a business rule says that no row
in the INVENTORY table can contain a numeric value greater than 9 in the SALE_DISCOUNT col-
umn. If an INSERT or UPDATE statement attempts to violate this integrity rule, Oracle must roll back
the invalid statement and return an error to the application. Oracle provides integrity constraints and
database triggers as solutions to manage a database’s data integrity rules.

Integrity Constraints

An integrity constraint is a declarative way to define a business rule for a column of a table. An integrity
constraint is a statement about a table’s data that is always true:


                                                    26
ORACLE

•       If an integrity constraint is created for a table and some existing table data does not satisfy the
        constraint, the constraint cannot be enforced.
•       After a constraint is defined, if any of the results of a DML statement violate the integrity
        constraint, the statement is rolled back and an error is returned.

Integrity constraints are defined with a table and are stored as part of the table’s definition, centrally in
the database’s data dictionary, so that all database applications must adhere to the same set of rules. If
a rule changes, it need only be changed once at the database level and not many times for each applica-
tion.

The following integrity constraints are supported by Oracle:

NOT NULL                Disallows nulls (empty entries) in a table’s column.
UNIQUE                  Disallows duplicate values in a column or set of columns.
PRIMARY KEY             Disallows duplicate values and nulls in a column or set of columns.
FOREIGN KEY             Requires each value in a column or set of columns match a value in a related
                        table’s UNIQUE or PRIMARY KEY (FOREIGN KEY integrity constraints also
                        define referential integrity actions that dictate what Oracle should do with
                        dependent data if the data it references is altered).
CHECK                   Disallows values that do not satisfy the logical expression of the constraint.

Keys

The term “key” is used in the definitions of several types of integrity constraints. A key is the column or
set of columns included in the definition of certain types of integrity constraints. Keys describe the
relationships between the different tables and columns of a relational database. The different types of
keys include:

primary key         The column or set of columns included in the definition of a table’s PRIMARY
                    KEY constraint. A primary key’s values uniquely identify the rows in a table. Only
                    one primary key may be defined per table.
unique key          The column or set of columns included in the definition of a UNIQUE constraint.

foreign key         The column or set of columns included in the definition of a referential integrity
                    constraint.
Referenced key      The unique key or primary key of the same or different table that is referenced by a
                    foreign key.

Individual values in a key are called key values.

Database Triggers

Centralized actions can be defined using a non-declarative approach (writing PL/SQL code) with database
triggers. A database trigger is a stored procedure that is fired (implicitly executed) when an INSERT,
UPDATE, or DELETE statement is issued against the associated table. Database triggers can be used to
customize a database management system with such features as value-based auditing and the enforcement

                                                     27
ORACLE

of complex security checks and integrity rules. For example, a database trigger might be created to
allow a table to be modified only during normal business hours.

Note:
While database triggers allow you to define and enforce integrity rules, a database trigger is not the
same as an integrity constraint. Among other things, a database trigger defined to enforce an integrity
rule does not check data already loaded into a table. Therefore, it is strongly recommended that you use
database triggers only when the integrity rule cannot be enforced by integrity constraints.




                                                  28
ORACLE




                    SQL - AN INTRODUCTION




COMPETENCY OBJECTIVES

This chapter covers the following topics

      v        SQL - An Introduction
      v        Data types in SQL
      v        SQL - Queries
      v        SQL Commands




                                           29
ORACLE




30
ORACLE


                                                                               CHAPTER - 2




   SQL - AN INTRODUCTION


The language, Structured English Query Language (“SEQUEL”) was developed by IBM Corporation,
Inc., to use Codd’s model. SEQUEL later became SQL (still pronounced “sequel”). In 1979, Relational
Software, Inc. (now Oracle Corporation) introduced the first commercially available implementation
of SQL. Today, SQL is accepted as the standard RDBMS language.

Working of SQL

The strengths of SQL benefit all types of users, including application programmers, database adminis-
trators, management, and end users. Technically speaking, SQL is a data sublanguage: the purpose of
SQL is to provide an interface to a relational database such as Oracle, and all SQL statements are
instructions to the database. In this it differs from general-purpose programming languages like C and
BASIC. Among the features of SQL are the following:
•        It processes sets of data as groups rather than as individual units.
•        It provides automatic navigation to the data.

Essentially, SQL lets you work with data at the logical level. You need to be concerned with the imple-
mentation details only when you want to manipulate the data. For example, to retrieve a set of rows
from a table, you define a condition used to filter the rows. All rows satisfying the condition are re-
trieved in a single step and can be passed as a unit to the user, to another SQL statement, or to an
application. You need not deal with the rows one by one, nor do you have to worry about how they are
physically stored or retrieved. All SQL statements use the optimizer, a part of Oracle that determines a
fast means of accessing the specified data. Oracle also provides techniques you can use to make the
optimizer perform its job better.

SQL provides commands for a variety of tasks, including:
•     querying data
•     inserting, updating, and deleting rows in a table
•     creating, replacing, altering, and dropping objects
•     controlling access to the database and its objects
•     guaranteeing database consistency and integrity

SQL unifies all of the above tasks in one consistent language.



                                                  31
ORACLE

Language for All Relational Databases

All major relational database management systems support SQL, so you can transfer all skills you have
gained with SQL from one database to another. In addition, all programs written in SQL are portable:
they can often be moved from one database to another with very little modification.

EMBEDDED SQL

Embedded SQL refers to the use of standard SQL commands embedded within a procedural programming
language. Embedded SQL is a collection of these commands:
•      all SQL commands, such as SELECT and INSERT, available with SQL with interactive tools
•      dynamic SQL execution commands, such as PREPARE and OPEN, which integrate the standard
       SQL commands with a procedural programming language

Embedded SQL also includes extensions to some standard SQL commands. Embedded SQL is supported
by the Oracle precompilers. The Oracle precompilers interpret embedded SQL statements and translate
them into statements that can be understood by procedural language compilers.

Each of these Oracle precompilers translates embedded SQL programs into a different procedural
language:
•      the Pro*C/C++ precompiler
•      the Pro*COBOL precompiler
•      the Pro*FORTRAN precompiler
•      the SQL*Module for ADA

ELEMENTS OF SQL LANGUAGE

Basic elements of Oracle SQL :
•      Literals
•      Text
•      Integer
•      Number
•      Datatypes
•      Nulls
•      Pseudocolumns
•      Comments


Literals

The terms literal and constant value are synonymous and refer to a fixed data value. For example,
‘JACK’, ‘BLUE ISLAND’, and ‘101’ are all character literals; 5001 is a numeric literal. Note that
character literals are enclosed in single quotation marks, which enable Oracle to distinguish them from
schema object names.

Many SQL statements and functions require you to specify character and numeric literal values. You
can also specify literals as part of expressions and conditions. You can specify character literals with

                                                  32
ORACLE

the ‘text’ notation, national character literals with the N’text’ notation, and numeric literals with the
integer or number notation, depending on the context of the literal. The syntactic forms of these notations
appear in the following sections.

Text

Text specifies a text or character literal. You must use this notation to specify values whenever ‘text’ or
char appear in expressions, conditions, SQL functions, and SQL commands in other parts of this refer-
ence.

A text literal must be enclosed in single quotation marks. This reference uses the terms text literal and
character literal interchangeably.

Text literals have properties of both the CHAR and VARCHAR2 datatypes:
•       Within expressions and conditions, Oracle treats text literals as though they have the datatype
        CHAR by comparing them using blank-padded comparison semantics.
•       A text literal can have a maximum length of 4000 bytes.

Here are some valid text literals:
‘Hello’
‘ORACLE.dbs’
‘Jackie’’s raincoat’
’09-MAR-92'
N’nchar literal’

Integer

You must use the integer notation to specify an integer whenever integer appears in expressions,
conditions, SQL functions, and SQL commands described in other parts of this reference.

An integer can store a maximum of 38 digits of precision.
Here are some valid integers:
7
+255

Number

You must use the number notation to specify values whenever number appears in expressions, condi-
tions, SQL functions, and SQL commands in other parts of this reference.

A number can store a maximum of 38 digits of precision.

If you have established a decimal character other than a period (.) with the initialization parameter
NLS_NUMERIC_CHARACTERS, you must specify numeric literals with ‘text’ notation. In such cases,
Oracle automatically converts the text literal to a numeric value.



                                                    33
ORACLE

For example, if the NLS_NUMERIC_CHARACTERS parameter specifies a decimal character of
comma, specify the number 5.123 as follows:

‘5,123’

Here are some valid representations of number:

25
+6.34
0.5
25e-03
-1

Datatypes

Each literal or column value manipulated by Oracle has a datatype. A value’s datatype associates a
fixed set of properties with the value. These properties cause Oracle to treat values of one datatype
differently from values of another. For example, you can add values of NUMBER datatype, but not
values of RAW datatype.

When you create a table or cluster, you must specify an internal datatype for each of its columns. When
you create a procedure or stored function, you must specify an internal datatype for each of its arguments.
These datatypes define the domain of values that each column can contain or each argument can have.
For example, DATE columns cannot accept the value February 29 (except for a leap year) or the values
2 or ‘SHOE’. Each value subsequently placed in a column assumes the column’s datatype. For example,
if you insert ’01-JAN-92' into a DATE column, Oracle treats the ’01-JAN-92' character string as a
DATE value after verifying that it translates to a valid date.

Table 2-1 summarizes Oracle internal datatypes. The rest of this section describes these datatypes in
detail.




                                                    34
ORACLE

Table 2-1 : Internal Datatype Summary



                    INTERNAL
      CODE          DATATYPE                                 DESCRIPTION
                                     Variable-length character string having maximum length
         1       VARCHAR2(size) size bytes. Maximum size is 4000, and minimum is 1. You
                                must specify size for a VARCHAR2.
                                Variable-length character string having maximum length
                                size characters or bytes, depending on the choice of
                NVARCHAR2(size)
                                national character set. Maximum size is determined by the
                                number of bytes required to store each character, with an
                                upper limit of 4000 bytes. You must specify size for
                                NVARCHAR2.
                                Number having precision p and scale s. The precision p can
         2        NUMBER(p,s)
                                range from 1 to 38. The scale s can range from -84 to 127.
                                Character data of variable length up to 2 gigabytes, or 231 -
         8           LONG
                                1 bytes.
                                Valid date range from January 1, 4712 BC to December 31,
         12          DATE
                                4712 AD.
                                Raw binary data of length size bytes. Maximum size is
         23        RAW(size)
                                2000 bytes. You must specify size for a RAW value.
         24        LONG RAW     Raw binary data of variable length up to 2 gigabytes.
                                Hexadecimal string representing the unique address of a
         69          ROWID      row in its table. This datatype is primarily for values
                                returned by the ROWID pseudocolumn.
                                Fixed length character data of length size bytes. Maximum
         96        CHAR(size)
                                size is 2000 bytes. Default and minimum size is 1 byte.



Character Datatypes

Character datatypes store character (alphanumeric) data-words and free-form text-in the database or
national character set. They are less restrictive than other datatypes and consequently have fewer
properties. For example, character columns can store all alphanumeric values, but NUMBER columns
can store only numeric values.

Character data is stored in strings with byte values corresponding to one of the character sets, such as 7-
bit ASCII or EBCDIC Code , specified when the database was created. Oracle supports both single-
byte and multibyte character sets.
These datatypes are used for character data:

These datatypes are used for character data:
•      CHAR Datatype
•      VARCHAR2 Datatype
                                                    35
ORACLE

CHAR Datatype

The CHAR datatype specifies a fixed-length character string. When you create a table with a CHAR
column, you supply the column length in bytes. Oracle subsequently ensures that all values stored in
that column have this length. If you insert a value that is shorter than the column length, Oracle blank-
pads the value to column length. If you try to insert a value that is too long for the column, Oracle
returns an error.

The default length for a CHAR column is 1 character and the maximum allowed is 2000 characters. A
zero-length string can be inserted into a CHAR column, but the column is blank-padded to 1 character
when used in comparisons.

VARCHAR2 Datatype

The VARCHAR2 datatype specifies a variable-length character string. When you create a VARCHAR2
column, you can supply the maximum number of bytes of data that it can hold. Oracle subsequently
stores each value in the column exactly as you specify it, provided it does not exceed the column’s
maximum length. This maximum must be at least 1 byte, although the actual length of the string stored
is permitted to be zero. If you try to insert a value that exceeds the specified length, Oracle returns an
error.

You must specify a maximum length for a VARCHAR2 column. The maximum length of VARCHAR2
data is 4000 bytes. Oracle compares VARCHAR2 values using nonpadded comparison semantics.

VARCHAR Datatype

The VARCHAR datatype is currently synonymous with the VARCHAR2 datatype. Oracle recommends
that you use VARCHAR2 rather than VARCHAR. In the future, VARCHAR might be defined as a
separate datatype used for variable-length character strings compared with different comparison
semantics.

NUMBER Datatype

The NUMBER datatype stores zero, positive and negative fixed and floating-point numbers with
magnitudes between 1.0 x 10-130 and 9.9...9 x 10125 (38 nines followed by 88 zeroes) with 38 digits of
precision. If you specify an arithmetic expression whose value has a magnitude greater than or equal to
1.0 x 10126, Oracle returns an error.

Specify a fixed-point number using the following form:
NUMBER(p,s)

where:

s              is the scale, or the number of digits to the right of the decimal point. The scale can range
               from -84 to 127.



                                                   36
ORACLE

Specify an integer using the following form:
NUMBER(p) is a fixed-point number with precision p and scale 0. This is equivalent to NUMBER(p,0).
Specify a floating-point number using the following form:
NUMBER          is a floating-point number with decimal precision 38. Note that a scale value is not
                applicable for floating-point numbers.

Scale and Precision

Specify the scale and precision of a fixed-point number column for extra integrity checking on input.
Specifying scale and precision does not force all values to a fixed length. If a value exceeds the precision,
Oracle returns an error. If a value exceeds the scale, Oracle rounds it.

The following examples show how Oracle stores data using different precisions and scales.

                7456123.89                  NUMBER                      7456123.89
                7456123.89                  NUMBER(9)                   7456124
                7456123.89                  NUMBER(9,2)                 7456123.89
                7456123.89                  NUMBER(9,1)                 7456123.9
                7456123.89                  NUMBER(6)                   exceeds precision
                7456123.89                  NUMBER(7,-2)                7456100
                7456123.89                  NUMBER(-7,2)                exceeds precision

Negative Scale

If the scale is negative, the actual data is rounded to the specified number of places to the left of the
decimal point. For example, a specification of (10,-2) means to round to hundreds.

Scale Greater than Precision

You can specify a scale that is greater than precision, although it is uncommon. In this case, the precision
specifies the maximum number of digits to the right of the decimal point. As with all number datatypes,
if the value exceeds the precision, Oracle returns an error message. If the value exceeds the scale,
Oracle rounds the value. For example, a column defined as NUMBER(4,5) requires a zero for the first
digit after the decimal point and rounds all values past the fifth digit after the decimal point. The
following examples show the effects of a scale greater than precision:

                 Actual Data                        Specified As                      Stored As
                     .01234                        NUMBER(4,5)                             .01234
                     .00012                        NUMBER(4,5)                             .00012
                    .000127                        NUMBER(4,5)                             .00013
                   .0000012                        NUMBER(2,7)                          .0000012
                  .00000123                        NUMBER(2,7)                          .0000012




                                                     37
ORACLE

Floating-Point Numbers

Oracle allows you to specify floating-point numbers, which can have a decimal point anywhere from
the first to the last digit or can have no decimal point at all. A scale value is not applicable to floating-
point numbers, because the number of digits that can appear after the decimal point is not restricted.

Oracle also supports the ANSI datatype FLOAT. You can specify this datatype using one of these
syntactic forms:

FLOAT           specifies a floating-point number with decimal precision 38, or binary precision 126.

FLOAT(b)        specifies a floating-point number with binary precision b. The precision b can range
                from 1 to 126. To convert from binary to decimal precision, multiply b by 0.30103. To
                convert from decimal to binary precision, multiply the decimal precision by 3.32193.
                The maximum of 126 digits of binary precision is roughly equivalent to 38 digits of
                decimal precision.

LONG Datatype

LONG columns store variable length character strings containing up to 2 gigabytes, or 231-1 bytes.
LONG columns have many of the characteristics of VARCHAR2 columns. You can use LONG columns
to store long text strings. Oracle uses LONG columns in the data dictionary to store the text of view
definitions. The length of LONG values may be limited by the memory available on your computer.
You can reference LONG columns in SQL statements in these places:
•       SELECT lists
•       SET clauses of UPDATE statements
•       VALUES clauses of INSERT statements

The use of LONG values are subject to some restrictions:
•      A table cannot contain more than one LONG column.
•      LONG columns cannot appear in integrity constraints (except for NULL and NOT NULL
       constraints).
•      LONG columns cannot be indexed.
•      A stored function cannot return a LONG value.
•      Within a single SQL statement, all LONG columns, updated tables, and locked tables must be
       located on the same database.

LONG columns cannot appear in certain parts of SQL statements:
•    WHERE, GROUP BY, ORDER BY, or CONNECT BY clauses or with the DISTINCT operator
     in SELECT statements
•    the UNIQUE clause of a SELECT statement
•    the column list of a CREATE CLUSTER statement
•    the CLUSTER clause of a CREATE SNAPSHOT statement
•    SQL functions (such as SUBSTR or INSTR)
•    expressions or conditions
•    SELECT lists of queries containing GROUP BY clauses

                                                     38
ORACLE

•      SELECT lists of subqueries or queries combined by set operators
•      SELECT lists of CREATE TABLE ... AS SELECT statements
•      SELECT lists in subqueries in INSERT statements

Triggers can use the LONG datatype in the following manner:
•      A SQL statement within a trigger can insert data into a LONG column.
•      If data from a LONG column can be converted to a constrained datatype (such as CHAR and
       VARCHAR2), a LONG column can be referenced in a SQL statement within a trigger. Note
       that the maximum length for these datatypes is 32K.
•      Variables in triggers cannot be declared using the LONG datatype.
•      :NEW and :OLD cannot be used with LONG columns.
.
DATE DATATYPE

The DATE datatype stores date and time information. Although date and time information can be
represented in both CHAR and NUMBER datatypes, the DATE datatype has special associated properties.
For each DATE value, Oracle stores the following information: century, year, month, day, hour, minute,
and second.

To specify a date value, you must convert a character or numeric value to a date value with the TO_DATE
function. Oracle automatically converts character values that are in the default date format into date
values when they are used in date expressions. The default date format is specified by the initialization
parameter NLS_DATE_FORMAT and is a string such as ‘DD-MON-YY’. This example date format
includes a two-digit number for the day of the month, an abbreviation of the month name, and the last
two digits of the year.

If you specify a date value without a time component, the default time is 12:00:00 am (midnight). If you
specify a date value without a date, the default date is the first day of the current month.

The date function SYSDATE returns the current date and time. For information on the SYSDATE and
TO_DATE functions and the default date format.

Date Arithmetic

You can add and subtract number constants as well as other dates from dates. Oracle interprets number
constants in arithmetic date expressions as numbers of days. For example, SYSDATE + 1 is tomorrow.
SYSDATE - 7 is one week ago. SYSDATE + (10/1440) is ten minutes from now. Subtracting the
HIREDATE column of the EMP table from SYSDATE returns the number of days since each employee
was hired. You cannot multiply or divide DATE values.

Oracle provides functions for many of the common date operations. For example, the ADD_MONTHS
function allows you to add or subtract months from a date. The MONTHS_BETWEEN function returns
the number of months between two dates. The fractional portion of the result represents that portion of
a 31-day month. Because each date contains a time component, most results of date operations include
a fraction. This fraction means a portion of one day. For example, 1.5 days is 36 hours.



                                                   39
ORACLE

Using Julian Dates

A Julian date is the number of days since January 1, 4712 bc. Julian dates allow continuous dating from
a common reference. You can use the date format model “J” with date functions TO_DATE and
TO_CHAR to convert between Oracle DATE values and their Julian equivalents.

Example
This statement returns the Julian equivalent of January 1, 1997:
SELECT TO_CHAR(TO_DATE(’01-01-1997', ‘MM-DD-YYYY’),’J’)
      FROM DUAL;

TO_CHAR
————
2450450

RAW and LONG RAW Datatypes

The RAW and LONG RAW datatypes store data that is not to be interpreted (not explicitly converted
when moving data between different systems) by Oracle. These datatypes are intended for binary data
or byte strings. For example, you can use LONG RAW to store graphics, sound, documents, or arrays of
binary data; the interpretation is dependent on the use.

RAW is a variable-length datatype like the VARCHAR2 character datatype, except that Net8 (which
connects user sessions to the instance) and the Import and Export utilities do not perform character
conversion when transmitting RAW or LONG RAW data. In contrast, Net8 and Import/Export auto-
matically convert CHAR, VARCHAR2, and LONG data from the database character set to the user
session character set (set by the NLS_LANGUAGE parameter of the ALTER SESSION command), if
the two character sets are different.

When Oracle automatically converts RAW or LONG RAW data to and from CHAR data, the binary
data is represented in hexadecimal form with one hexadecimal character representing every four bits of
RAW data. For example, one byte of RAW data with bits 11001011 is displayed and entered as ‘CB’.

You can index RAW data, but not LONG RAW data.

ROWID Datatype

Each row in the database has an address. You can examine a row’s address by querying the pseudocolumn
ROWID. Values of this pseudocolumn are hexadecimal strings representing the address of each row.
These strings have the datatype ROWID. You can also create tables and clusters that contain actual
columns having the ROWID datatype. Oracle does not guarantee that the values of such columns are
valid ROWIDs.

Datatype Comparison Rules

This section describes how Oracle compares values of each datatype.

                                                  40
ORACLE

Number Values

A larger value is considered greater than a smaller one. All negative numbers are less than zero and all
positive numbers. Thus, -1 is less than 100; -100 is less than -1.

Date Values

A later date is considered greater than an earlier one. For example, the date equivalent of ’29-MAR-
1991' is less than that of ’05-JAN-1992' and ’05-JAN-1992 1:35pm’ is greater than ’05-JAN-1992
10:09am’.

Character String Values

Character values are compared using one of these comparison rules:
•      blank-padded comparison semantics
•      nonpadded comparison semantics

The following sections explain these comparison semantics. The results of comparing two character
values using different comparison semantics may be different. Table 2-5 shows the results of compar-
ing five pairs of character values using each comparison semantic. Usually, the results of blank-padded
and nonpadded comparisons are the same.The last comparison in the table illustrates the differences
between the blank-padded and nonpadded comparison semantics.
                                Blank-Padded                  Nonpadded
                                'ab' > 'aa'                  'ab' > 'aa'
                                'ab' > 'a '                  'ab' > 'a '
                                 'ab' > 'a'                   'ab' > 'a'
                                'ab' = 'ab'                  'ab' = 'ab'
                                    'a ' = 'a'                   'a ' > 'a'

Blank-Padded Comparison Semantics

If the two values have different lengths, Oracle first adds blanks to the end of the shorter one so their
lengths are equal. Oracle then compares the values character by character up to the first character that
differs. The value with the greater character in the first differing position is considered greater. If two
values have no differing characters, then they are considered equal. This rule means that two values are
equal if they differ only in the number of trailing blanks. Oracle uses blank-padded comparison seman-
tics only when both values in the comparison are either expressions of datatype CHAR, NCHAR, text
literals, or values returned by the USER function.

Nonpadded Comparison Semantics

Oracle compares two values character by character up to the first character that differs. The value with
the greater character in that position is considered greater. If two values of different length are identical
up to the end of the shorter one, the longer value is considered greater. If two values of equal length
have no differing characters, then the values are considered equal. Oracle uses nonpadded comparison
semantics whenever one or both values in the comparison have the datatype VARCHAR2 or
NVARCHAR2.

                                                     41
ORACLE

Single Characters

Oracle compares single characters according to their numeric values in the database character set. One
character is greater than another if it has a greater numeric value than the other in the character set.
Oracle considers blanks to be less than any character, which is true in most character sets.

These are some common character sets:
•      7-bit ASCII (American Standard Code for Information Interchange)
•      EBCDIC Code (Extended Binary Coded Decimal Interchange Code)
•      ISO 8859/1 (International Standards Organization)
•      JEUC Japan Extended UNIX

Portions of the ASCII and EBCDIC character sets appear in Table 2-6 and Table 2-7. Note that upper-
case and lowercase letters are not equivalent. Also, note that the numeric values for the characters of a
character set may not match the linguistic sequence for a particular language.

Table 2-6: ASCII Character Set



                   Symbol        Decimal value          Symbol         Decimal value
                   blank              32                   ;                 59
                     !                33                   <                 60
                     "                34                   =                 61
                     #                35                   >                 62
                     $                36                   ?                 63
                     %                37                   @                 64
                     &                38                 A-Z               65-90
                     '                39                   [                 91
                     (                40                                    92
                     )                41                   ]                 93
                     *                42                  ^^                 94
                     +                43                   _                 95
                     ,                44                   `                 96
                     -                45                 a-z              97-122
                     .                46                  {                 123
                     /                47                  |                 124
                    0-9             48-57                  }                125
                     :                58                  ~                 126




                                                   42
ORACLE




                       Symbol     Decimal value        Symbol   Decimal value
                       blank           64                %         108
                         ¢             74                _         109
                         .             75                >         110
                         <             76                ?         111
                         (             77                :         122
                         +             78                #         123
                         |             79                @         124
                         &             80                '         125
                         !             90                =         126
                         $             91                "         127
                         *             92               a-i      129-137
                         )             93               j-r      145-153
                         ;             94               s-z      162-169
                         ÿ             95               A-I      193-201
                         -             96               J-R      209-217
                         /             97               S-Z      226-233


Data Conversion

Generally an expression cannot contain values of different datatypes. For example, an expression can-
not multiply 5 by 10 and then add ‘JAMES’. However, Oracle supports both implicit and explicit
conversion of values from one datatype to another.

Implicit Data Conversion

Oracle automatically converts a value from one datatype to another when such a conversion makes
sense. Oracle performs conversions in these cases:
•      When an INSERT or UPDATE statement assigns a value of one datatype to a column of an-
       other, Oracle converts the value to the datatype of the column.
•      When you use a SQL function or operator with an argument with a datatype other than the one
       it accepts, Oracle converts the argument to the accepted datatype.
•      When you use a comparison operator on values of different datatypes, Oracle converts one of
       the expressions to the datatype of the other.

Example 1
The text literal ‘10’ has datatype CHAR. Oracle implicitly converts it to the NUMBER datatype if it
appears in a numeric expression as in the following statement:
SELECT sal + ‘10’
      FROM emp;

Example 2
When a condition compares a character value and a NUMBER value, Oracle implicitly converts the
character value to a NUMBER value, rather than converting the NUMBER value to a character value.

                                                  43
ORACLE

In the following statement, Oracle implicitly converts ‘7936’ to 7936:
SELECT ename
      FROM emp
      WHERE empno = ‘7936’;

Example 3

In the following statement, Oracle implicitly converts ’12-MAR-1993' to a DATE value using the
default date format ‘DD-MON-YYYY’:
SELECT ename
      FROM emp
      WHERE hiredate = ’12-MAR-1993';

Example 4

In the following statement, Oracle implicitly converts the text literal ‘AAAAZ8AABAAABvlAAA’ to
a ROWID value:
SELECT ename
       FROM emp
       WHERE ROWID = ‘AAAAZ8AABAAABvlAAA’;

Explicit Data Conversion

You can also explicitly specify datatype conversions using SQL conversion functions. Table 2-8 shows
SQL functions that explicitly convert a value from one datatype to another

Table 2-8 SQL Functions for Datatype Conversion

     TO: FROM:         CHAR            NUMBER           DATE          RAW            ROWID
      CHAR              -           TO_NUMBER          TO_DATE HEXTORAW CHARTOROWID
     NUMBER          TO_CHAR            -              TO_DATE
                                                      (number,
                                                        'J')
       DATE          TO_CHAR          TO_CHAR             -
                                    (date,'J')
       RAW          RAWTOHEX                                             -
      ROWID       ROWIDTOCHAR                                                           -

Implicit vs. Explicit Data Conversion

Oracle recommends that you specify explicit conversions rather than rely on implicit or automatic
conversions for these reasons:
•      SQL statements are easier to understand when you use explicit datatype conversions functions.
•      Automatic datatype conversion can have a negative impact on performance, especially if the
       datatype of a column value is converted to that of a constant rather than the other way around.


                                                 44
ORACLE

•       Implicit conversion depends on the context in which it occurs and may not work the same way
        in every case.
•       Algorithms for implicit conversion are subject to change across software releases and among
        Oracle products. Behavior of explicit conversions is more predictable.

Nulls

If a column in a row has no value, then column is said to be null, or to contain a null. Nulls can appear
in columns of any datatype that are not restricted by NOT NULL or PRIMARY KEY integrity constraints.
Use a null when the actual value is not known or when a value would not be meaningful.

Do not use null to represent a value of zero, because they are not equivalent. (Oracle currently treats a
character value with a length of zero as null. However, this may not continue to be true in future
releases, and Oracle recommends that you do not treat empty strings the same as NULLs.) Any arithmetic
expression containing a null always evaluates to null. For example, null added to 10 is null. In fact, all
operators (except concatenation) return null when given a null operand.

Nulls in SQL Functions

All scalar functions (except NVL and TRANSLATE) return null when given a null argument. The NVL
function can be used to return a value when a null occurs. For example, the expression NVL(COMM,0)
returns 0 if COMM is null or the value of COMM if it is not null.

Most group functions ignore nulls. For example, consider a query that averages the five values 1000,
null, null, null, and 2000. Such a query ignores the nulls and calculates the average to be (1000+2000)/
2 = 1500.

Nulls with Comparison Operators

To test for nulls, use only the comparison operators IS NULL and IS NOT NULL. If you use any other
operator with nulls and the result depends on the value of the null, the result is UNKNOWN. Because
null represents a lack of data, a null cannot be equal or unequal to any value or to another null. However,
note that Oracle considers two nulls to be equal when evaluating a DECODE expression.

Oracle also considers two nulls to be equal if they appear in compound keys. That is, Oracle considers
identical two compound keys containing nulls if all the non-null components of the keys are equal.

Nulls in Conditions

A condition that evaluates to UNKNOWN acts almost like FALSE. For example, a SELECT statement
with a condition in the WHERE clause that evaluates to UNKNOWN returns no rows. However, a
condition evaluating to UNKNOWN differs from FALSE in that further operations on an UNKNOWN
condition evaluation will evaluate to UNKNOWN. Thus, NOT FALSE evaluates to TRUE, but NOT
UNKNOWN evaluates to UNKNOWN.




                                                    45
ORACLE

Table 2-9 shows examples of various evaluations involving nulls in conditions. If the conditions
evaluating to UNKNOWN were used in a WHERE clause of a SELECT statement, then no rows would
be returned for that query.

Table 2-9: Conditions containing Nulls


                         If A is:           Condition            Evaluates to:
                            10              a IS NULL               FALSE
                            10           a IS NOT NULL              TRUE
                          NULL              a IS NULL               TRUE
                          NULL           a IS NOT NULL              FALSE
                            10               a = NULL             UNKNOWN
                            10              a != NULL             UNKNOWN
                          NULL               a = NULL             UNKNOWN
                          NULL              a != NULL             UNKNOWN
                          NULL                 a = 10             UNKNOWN
                          NULL                 a != 10            UNKNOWN

PSEUDOCOLUMNS

A pseudocolumn behaves like a table column, but is not actually stored in the table. You can select from
pseudocolumns, but you cannot insert, update, or delete their values. This section describes these
pseudocolumns:
•      CURRVAL and NEXTVAL
•      LEVEL
•      ROWID
•      ROWNUM

CURRVAL and NEXTVAL

A sequence is a schema object that can generate unique sequential values. These values are often used
for primary and unique keys. You can refer to sequence values in SQL statements with these
pseudocolumns:

CURRVAL returns the current value of a sequence.

NEXTVAL increments the sequence and returns the next value.

You must qualify CURRVAL and NEXTVAL with the name of the sequence:
sequence.CURRVAL
sequence.NEXTVAL

To refer to the current or next value of a sequence in the schema of another user, you must have been
granted either SELECT object privilege on the sequence or SELECT ANY SEQUENCE system privi-
lege, and you must qualify the sequence with the schema containing it:

                                                  46
ORACLE

schema.sequence.CURRVAL
schema.sequence.NEXTVAL

To refer to the value of a sequence on a remote database, you must qualify the sequence with a complete
or partial name of a database link:
schema.sequence.CURRVAL@dblink
schema.sequence.NEXTVAL@dblink

Where to Use Sequence Values

You can use CURRVAL and NEXTVAL in these places:
•     the SELECT list of a SELECT statement that is not contained in a subquery, snapshot, or view
•     the SELECT list of a subquery in an INSERT statement
•     the VALUES clause of an INSERT statement
•     the SET clause of an UPDATE statement

You cannot use CURRVAL and NEXTVAL in these places:
•     a subquery in a DELETE, SELECT, or UPDATE statement
•     a view’s query or snapshot’s query
•     a SELECT statement with the DISTINCT operator
•     a SELECT statement with a GROUP BY or ORDER BY clause
•     a SELECT statement that is combined with another SELECT statement with the UNION, IN-
      TERSECT, or MINUS set operator
•     the WHERE clause of a SELECT statement
•     DEFAULT value of a column in a CREATE TABLE or ALTER TABLE statement
•     the condition of a CHECK constraint

Also, within a single SQL statement that uses CURVAL or NEXTVAL, all referenced LONG columns,
updated tables, and locked tables must be located on the same database.

How to Use Sequence Values

When you create a sequence, you can define its initial value and the increment between its values. The
first reference to NEXTVAL returns the sequence’s initial value. Subsequent references to NEXTVAL
increment the sequence value by the defined increment and return the new value. Any reference to
CURRVAL always returns the sequence’s current value, which is the value returned by the last refer-
ence to NEXTVAL. Note that before you use CURRVAL for a sequence in your session, you must first
initialize the sequence with NEXTVAL.

Within a single SQL statement, Oracle will increment the sequence only once. If a statement contains
more than one reference to NEXTVAL for a sequence, Oracle increments the sequence once and re-
turns the same value for all occurrences of NEXTVAL. If a statement contains references to both
CURRVAL and NEXTVAL, Oracle increments the sequence and returns the same value for both
CURRVAL and NEXTVAL regardless of their order within the statement.

A sequence can be accessed by many users concurrently with no waiting or locking.

                                                  47
ORACLE

Example 1
This example selects the current value of the employee sequence:
SELECT empseq.currval
      FROM DUAL;

Example 2
This example increments the employee sequence and uses its value for a new employee inserted into
the employee table:
INSERT INTO emp
      VALUES (empseq.nextval, ‘LEWIS’, ‘CLERK’,
                   7902, SYSDATE, 1200, NULL, 20);

Example 3
This example adds a new order with the next order number to the master order table. It then adds
suborders with this number to the detail order table:
INSERT INTO master_order(orderno, customer, orderdate)
      VALUES (orderseq.nextval, ‘Al’’s Auto Shop’, SYSDATE);

INSERT INTO detail_order (orderno, part, quantity)
    VALUES (orderseq.currval, ‘SPARKPLUG’, 4);

INSERT INTO detail_order (orderno, part, quantity)
    VALUES (orderseq.currval, ‘FUEL PUMP’, 1);

INSERT INTO detail_order (orderno, part, quantity)
  VALUES (orderseq.currval, ‘TAILPIPE’, 2);

LEVEL

For each row returned by a hierarchical query, the LEVEL pseudocolumn returns 1 for a root node, 2 for
a child of a root, and so on. A root node is the highest node within an inverted tree. A child node is any
nonroot node. A parent node is any node that has children. A leaf node is any node without children.
Figure 2-1 shows the nodes of an inverted tree with their LEVEL values




Fig. 2-1 : Hierarchical Tree

To define a hierarchical relationship in a query, you must use the START WITH and CONNECT BY
clauses.

                                                   48
ORACLE

ROWID

For each row in the database, the ROWID pseudocolumn returns a row’s address. ROWID values
contain information necessary to locate a row:
•      the data object number of the object
•      which data block in the datafile
•      which row in the data block (first row is 0)
•      which datafile (first file is 1). The file number is relative to the tablespace.

Usually, a ROWID value uniquely identifies a row in the database. However, rows in different tables
that are stored together in the same cluster can have the same ROWID.

Values of the ROWID pseudocolumn have the datatype ROWID.

ROWID values have several important uses:
•   They are the fastest way to access a single row.
•   They can show you how a table’s rows are stored.
•   They are unique identifiers for rows in a table.

You should not use ROWID as a table’s primary key. If you delete and reinsert a row with the Import
and Export utilities, for example, its ROWID may change. If you delete a row, Oracle may reassign its
ROWID to a new row inserted later.

Although you can use the ROWID pseudocolumn in the SELECT and WHERE clauses of a query,
these pseudocolumn values are not actually stored in the database. You cannot insert, update, or delete
a value of the ROWID pseudocolumn.

Example

This statement selects the address of all rows that contain data for employees in department 20:
SELECT ROWID, ename
      FROM emp
      WHERE deptno = 20;

ROWID                        ENAME
————————— ———-—-
AAAAfSAABAAAClaAAA           SMITH
AAAAfSAABAAAClaAAD           JONES
AAAAfSAABAAAClaAAH           SCOTT
AAAAfSAABAAAClaAAK           ADAMS
AAAAfSAABAAAClaAAM           FORD

ROWNUM

For each row returned by a query, the ROWNUM pseudocolumn returns a number indicating the order
in which Oracle selects the row from a table or set of joined rows. The first row selected has a ROWNUM
of 1, the second has 2, and so on.
                                                  49
ORACLE

You can use ROWNUM to limit the number of rows returned by a query, as in this example:
SELECT *
     FROM emp
     WHERE ROWNUM < 10;

Note that conditions testing for ROWNUM values greater than a positive integer are always false. For
example, this query returns no rows:
SELECT * FROM emp
      WHERE ROWNUM > 1;

The first row fetched is assigned a ROWNUM of 1 and makes the condition false. The second row to be
fetched is now the first row and is also assigned a ROWNUM of 1 and makes the condition false. All
rows subsequently fail to satisfy the condition, so no rows are returned.

You can also use ROWNUM to assign unique values to each row of a table, as in this example:
UPDATE tabx
     SET col1 = ROWNUM;

Oracle assigns a ROWNUM value to each row as it is retrieved, before rows are sorted for an ORDER
BY clause, so an ORDER BY clause normally does not affect the ROWNUM of each row. However, if
an ORDER BY clause causes Oracle to use an index to access the data, Oracle may retrieve the rows in
a different order than without the index, so the ROWNUMs may be different than they would be
without the ORDER BY clause.




                                                50
ORACLE




                    SQL - AN INTRODUCTION




COMPETENCY OBJECTIVES

This chapter covers the following topics

      v        SQL Operators
      v        SQL Functions
      v        SQL Queries




                                           51
ORACLE




52
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle
Oracle

Contenu connexe

Tendances (10)

Oracle DB 11g R2 Research (Installation, Users and Privileges, Audit Trail, E...
Oracle DB 11g R2 Research (Installation, Users and Privileges, Audit Trail, E...Oracle DB 11g R2 Research (Installation, Users and Privileges, Audit Trail, E...
Oracle DB 11g R2 Research (Installation, Users and Privileges, Audit Trail, E...
 
Ebs idm con9020_pdf_9020_0001
Ebs idm con9020_pdf_9020_0001Ebs idm con9020_pdf_9020_0001
Ebs idm con9020_pdf_9020_0001
 
SREEPURAM CHARAN KUMAR_DBA_SYSTEM_ENGINEER_3_yrs
SREEPURAM CHARAN KUMAR_DBA_SYSTEM_ENGINEER_3_yrsSREEPURAM CHARAN KUMAR_DBA_SYSTEM_ENGINEER_3_yrs
SREEPURAM CHARAN KUMAR_DBA_SYSTEM_ENGINEER_3_yrs
 
Md arshad ali
Md arshad aliMd arshad ali
Md arshad ali
 
Sql server difference faqs- 6
Sql server difference faqs- 6Sql server difference faqs- 6
Sql server difference faqs- 6
 
Deploying opetus
Deploying opetusDeploying opetus
Deploying opetus
 
IT6701-Information management question bank
IT6701-Information management question bankIT6701-Information management question bank
IT6701-Information management question bank
 
Ebook4
Ebook4Ebook4
Ebook4
 
121admp
121admp121admp
121admp
 
Ebook10
Ebook10Ebook10
Ebook10
 

En vedette (10)

notes4
notes4notes4
notes4
 
Giao_trinh_CSDL
Giao_trinh_CSDLGiao_trinh_CSDL
Giao_trinh_CSDL
 
Building_a_database_with_PHP_and_SQL
Building_a_database_with_PHP_and_SQLBuilding_a_database_with_PHP_and_SQL
Building_a_database_with_PHP_and_SQL
 
DetaiBTL
DetaiBTLDetaiBTL
DetaiBTL
 
Introduction to EIGRP  [IP Routing] - Cisco Systems
Introduction to EIGRP  [IP Routing] - Cisco SystemsIntroduction to EIGRP  [IP Routing] - Cisco Systems
Introduction to EIGRP  [IP Routing] - Cisco Systems
 
RTS introduction
RTS introductionRTS introduction
RTS introduction
 
MySQL-PHP
MySQL-PHPMySQL-PHP
MySQL-PHP
 
Chapter 6-Remoting
Chapter 6-RemotingChapter 6-Remoting
Chapter 6-Remoting
 
How to tell engaging stories for non-profits, charities, and causes
How to tell engaging stories for non-profits, charities, and causesHow to tell engaging stories for non-profits, charities, and causes
How to tell engaging stories for non-profits, charities, and causes
 
DichCanKinh_thuchanh
DichCanKinh_thuchanhDichCanKinh_thuchanh
DichCanKinh_thuchanh
 

Similaire à Oracle

11g-sql-fundamentals-ppt.pdf
11g-sql-fundamentals-ppt.pdf11g-sql-fundamentals-ppt.pdf
11g-sql-fundamentals-ppt.pdf
firasatsayyed1
 

Similaire à Oracle (20)

Handy annotations-within-oracle-10g
Handy annotations-within-oracle-10gHandy annotations-within-oracle-10g
Handy annotations-within-oracle-10g
 
The oracle database architecture
The oracle database architectureThe oracle database architecture
The oracle database architecture
 
Introduction to Oracle Database
Introduction to Oracle DatabaseIntroduction to Oracle Database
Introduction to Oracle Database
 
Oracle DBA Tutorial for Beginners -Oracle training institute in bangalore
Oracle DBA Tutorial for Beginners -Oracle training institute in bangaloreOracle DBA Tutorial for Beginners -Oracle training institute in bangalore
Oracle DBA Tutorial for Beginners -Oracle training institute in bangalore
 
Kultam MM UI - MySQL for Data Analytics and Business Intelligence.pdf
Kultam MM UI - MySQL for Data Analytics and Business Intelligence.pdfKultam MM UI - MySQL for Data Analytics and Business Intelligence.pdf
Kultam MM UI - MySQL for Data Analytics and Business Intelligence.pdf
 
A42525
A42525A42525
A42525
 
ORACLE Architechture.ppt
ORACLE Architechture.pptORACLE Architechture.ppt
ORACLE Architechture.ppt
 
Mustafa_CV
Mustafa_CVMustafa_CV
Mustafa_CV
 
11g-sql-fundamentals-ppt.pdf
11g-sql-fundamentals-ppt.pdf11g-sql-fundamentals-ppt.pdf
11g-sql-fundamentals-ppt.pdf
 
Presenter manual oracle dba (specially for summer interns)
Presenter manual oracle dba (specially for summer interns)Presenter manual oracle dba (specially for summer interns)
Presenter manual oracle dba (specially for summer interns)
 
A Survey And Comparison Of Relational And Non-Relational Database
A Survey And Comparison Of Relational And Non-Relational DatabaseA Survey And Comparison Of Relational And Non-Relational Database
A Survey And Comparison Of Relational And Non-Relational Database
 
Veera Narayanaswamy_PLSQL_Profile
Veera Narayanaswamy_PLSQL_ProfileVeera Narayanaswamy_PLSQL_Profile
Veera Narayanaswamy_PLSQL_Profile
 
PHP Oracle
PHP OraclePHP Oracle
PHP Oracle
 
Less 01 introduction
Less 01   introductionLess 01   introduction
Less 01 introduction
 
MOHAMMED VIKHAR AHMED
MOHAMMED VIKHAR AHMEDMOHAMMED VIKHAR AHMED
MOHAMMED VIKHAR AHMED
 
Vineet Kurrewar
Vineet KurrewarVineet Kurrewar
Vineet Kurrewar
 
Shrikanth
ShrikanthShrikanth
Shrikanth
 
Ilm
IlmIlm
Ilm
 
notes
notesnotes
notes
 
Lecture2 oracle ppt
Lecture2 oracle pptLecture2 oracle ppt
Lecture2 oracle ppt
 

Plus de Hoàng Hải Nguyễn

CCNA Security Lab 9 - Enabling SSH and HTTPS access to Cisco IOS Routers - CLI
CCNA Security Lab 9 - Enabling SSH and HTTPS access to Cisco IOS Routers - CLICCNA Security Lab 9 - Enabling SSH and HTTPS access to Cisco IOS Routers - CLI
CCNA Security Lab 9 - Enabling SSH and HTTPS access to Cisco IOS Routers - CLI
Hoàng Hải Nguyễn
 
RFC 1058 - Routing Information Protocol
RFC 1058 - Routing Information ProtocolRFC 1058 - Routing Information Protocol
RFC 1058 - Routing Information Protocol
Hoàng Hải Nguyễn
 
Enhanced Interior Gateway Routing Protocol - Wikipedia, the free encyclopedia
Enhanced Interior Gateway Routing Protocol - Wikipedia, the free encyclopediaEnhanced Interior Gateway Routing Protocol - Wikipedia, the free encyclopedia
Enhanced Interior Gateway Routing Protocol - Wikipedia, the free encyclopedia
Hoàng Hải Nguyễn
 
Configuring Secure Shell on Routers and Switches Running Cisco IO
Configuring Secure Shell on Routers and Switches Running Cisco IOConfiguring Secure Shell on Routers and Switches Running Cisco IO
Configuring Secure Shell on Routers and Switches Running Cisco IO
Hoàng Hải Nguyễn
 
Giao trinh phan tich thiet ke he thong pdf
Giao trinh phan tich thiet ke he thong pdfGiao trinh phan tich thiet ke he thong pdf
Giao trinh phan tich thiet ke he thong pdf
Hoàng Hải Nguyễn
 

Plus de Hoàng Hải Nguyễn (20)

CCNA S3 - Chapter 04 - VTP
CCNA S3 - Chapter 04 - VTPCCNA S3 - Chapter 04 - VTP
CCNA S3 - Chapter 04 - VTP
 
DiemGiuaky(cnpm)
DiemGiuaky(cnpm)DiemGiuaky(cnpm)
DiemGiuaky(cnpm)
 
CCNA Security Lab 9 - Enabling SSH and HTTPS access to Cisco IOS Routers - CLI
CCNA Security Lab 9 - Enabling SSH and HTTPS access to Cisco IOS Routers - CLICCNA Security Lab 9 - Enabling SSH and HTTPS access to Cisco IOS Routers - CLI
CCNA Security Lab 9 - Enabling SSH and HTTPS access to Cisco IOS Routers - CLI
 
Quan ly bo nho trong C#
Quan ly bo nho trong C#Quan ly bo nho trong C#
Quan ly bo nho trong C#
 
notes5
notes5notes5
notes5
 
OOP1_K51
OOP1_K51OOP1_K51
OOP1_K51
 
RFC 1058 - Routing Information Protocol
RFC 1058 - Routing Information ProtocolRFC 1058 - Routing Information Protocol
RFC 1058 - Routing Information Protocol
 
Enhanced Interior Gateway Routing Protocol - Wikipedia, the free encyclopedia
Enhanced Interior Gateway Routing Protocol - Wikipedia, the free encyclopediaEnhanced Interior Gateway Routing Protocol - Wikipedia, the free encyclopedia
Enhanced Interior Gateway Routing Protocol - Wikipedia, the free encyclopedia
 
Phan tich QL ban va mua hang
Phan tich QL ban va mua hangPhan tich QL ban va mua hang
Phan tich QL ban va mua hang
 
notes2
notes2notes2
notes2
 
Giao trinh thuc hanh SQL
Giao trinh thuc hanh SQLGiao trinh thuc hanh SQL
Giao trinh thuc hanh SQL
 
Configuring Secure Shell on Routers and Switches Running Cisco IO
Configuring Secure Shell on Routers and Switches Running Cisco IOConfiguring Secure Shell on Routers and Switches Running Cisco IO
Configuring Secure Shell on Routers and Switches Running Cisco IO
 
Ch3-2
Ch3-2Ch3-2
Ch3-2
 
Bao cao thuc tap co so
Bao cao thuc tap co soBao cao thuc tap co so
Bao cao thuc tap co so
 
Giao trinh phan tich thiet ke he thong pdf
Giao trinh phan tich thiet ke he thong pdfGiao trinh phan tich thiet ke he thong pdf
Giao trinh phan tich thiet ke he thong pdf
 
ShellProgramming
ShellProgrammingShellProgramming
ShellProgramming
 
01. Giới thiệu về AHRP 2011
01. Giới thiệu về AHRP 201101. Giới thiệu về AHRP 2011
01. Giới thiệu về AHRP 2011
 
Tu hoc SQL 2000
Tu hoc SQL 2000Tu hoc SQL 2000
Tu hoc SQL 2000
 
Giao trinh SQL(DHHUE)
Giao trinh SQL(DHHUE)Giao trinh SQL(DHHUE)
Giao trinh SQL(DHHUE)
 
OSPF
OSPFOSPF
OSPF
 

Dernier

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Dernier (20)

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 

Oracle

  • 1.
  • 2. Published by CFS Documentation Cell Centre for Electronics Design and Technology of India An Autonomous Scientific Society under Department of Electronics, Govt. of India, New Delhi. First Edition: 1999 TRADEMARKS: All brand name and product names mentioned in this book are trademarks or registered trademark of their respective companies. Every effort has been made to supply complete and accurate information. However, CEDTI assumes no responsibility for its use, nor for any infringement of the intellectual property rights of third parties which would result from such use. No part of this publication may be stored in a retrieval system, transmitted or reproduced in any forms or by any means, electronic, photocopy, photograph, magnetic or otherwise, without written permission of CEDTI. CEDTI/CFS/99/6/3.2/R1
  • 3. FOREWORD The information technology and telecom sectors have suddenly opened up avenues, which require a very large specially trained manpower. These sectors are highly dynamic and need training and re-training of manpower at a rapid rate. The growing gap of requirement of the industry and its fulfillment has created a challenging situation before manpower training institutes of the country. To meet this challenge most effectively, Centre for Electronics Design and Technology of India (CEDTI) has launched its nation-wide franchising scheme. Centre for Electronics Design and Technology of India (CEDTI) is an Autonomous Scientific Society under the Govt. of India, Department of Electronics with its Headquarters at New Delhi. It operates seven centres located at Aurangabad, Calicut, Gorakhpur, Imphal, Mohali, Jammu and Tezpur. The scheme will be implemented and coordinated by these centres. The scheme endeavours to promote high quality computer and information technology education in the country at an affordable cost while ensuring uniform standards in order to build a national resource of trained manpower. Low course fees will make this education available to people in relatively small, semi urban and rural areas. State-of-the-art training will be provided keeping in view the existing and emerging needs of the industrial and Govt. sectors. The examinations will be conducted by CEDTI and certificates will also be awarded by CEDTI. The scheme will be operated through all the seven centres of CEDTI. The CEDTI functions under the overall control and guidance of the Governing Council with Secretary, Department of Electronics as its Chairman. The members of the council are drawn from scientific, government and industrial sectors. The Centres have separate executive committees headed by Director General, CEDTI. The members of these committees are from academic/professional institutes, state governments, industry and department of electronics. CEDTI is a quality conscious organisation and has taken steps to formally get recognition of the quality and standards in various activities. CEDTI, Mohali was granted the prestigious ISO 9002 certificate in 1997. The other centres have taken steps to obtain the certification as early as possible. This quality consciousness will assist CEDTI in globalizing some of its activities. In keeping with its philosophy of ‘Quality in every Activity’, CEDTI will endeavour to impart state of the art – computer and IT training through its franchising scheme. The thrust of the Software Courses is to train the students at various levels to carry out the Management Information System functions of a medium sized establishment, manufacture Software for domestic and export use, make multimedia presentations for management and effectively produce various manufacturing and architectural designs.
  • 4. The thrust of the Hardware Courses at Technician and Telecommunication Equipment Maintenance Course levels is to train the students to diagnose the faults and carry out repairs at card level in computers, instruments, EPABX, Fax etc. and other office equipment. At Engineer and Network Engineer levels the thrust is to train them as System Engineers to install and supervise the Window NT, Netware and Unix Networking Systems and repair Microcontrollers / Microprocessor based electronic applications. An Advisory Committee comprising eminent and expert personalities from the Information Technology field have been constituted to advise CEDTI on introduction of new courses and revising the syllabus of existing courses to meet the changing IT needs of the trade, industry and service sectors. The ultimate objective is to provide industry-specific quality education in modular form to supplement the formal education. The study material has been prepared by the CEDTI, document centre. It is based on the vast and rich instructional experience of all the CEDTI centres. Any suggestions on the improvement of the study material will be most welcome. (R. S. Khandpur) Director General (CEDTI)
  • 5. TABLE OF CONTENTS UNIT CHAPTER NAME PAGE NO. 1 BASIC FEATURES OF ORACLE 11 2 SQL - AN INTRODUCTION 31 3 OPERATORS USED IN ORACLE 53 4 DATA MANIPULATION LANGUAGE 99 5 PL/SQL & ITS FEATURES 119
  • 6.
  • 8.
  • 9. BASIC FEATURES OF ORACLE COMPETENCY OBJECTIVES This chapter covers the following topics v Basic features of oracle v Oracle server – introduction v Database – introduction v Physical files v Logical structure v Memory structure v Background processes v SQL, PL/SQL – introduction
  • 11. ORACLE CHAPTER - 1 BASIC FEATURES OF ORACLE ORACLE SERVER - AN INTRODUCTION The Oracle server is an object-relational database management system . It provides an open, comprehensive, and integrated approach to information management. An Oracle server is combination of an Oracle database and an Oracle server instance. STRUCTURED QUERY LANGUAGE (SQL) SQL is the programming language that defines and manipulates the database. SQL databases are relational databases which implies that data is stored in a set of simple relations. A database can have one or more tables. And each table has columns and rows. In addition to SQL commands, the Oracle server has a procedural language called PL/SQL. PL/SQL enables the programmer to program SQL statements. It allows you to control the flow of a SQL program, to use variables, and to write error-handling procedures. DATABASE ARCHITECTURE Database Structure Physical Database Structure Logical Database Structure Database Structure An Oracle database has both a physical and a logical structure. Because the physical and logical server structure are separate, the physical storage of data can be managed without affecting the access to logical storage structures. Physical Database Structure An Oracle database’s physical structure is determined by the operating system files that constitute the database. Each Oracle database is made of three types of files: one or more datafiles, two or more redo 11
  • 12. ORACLE log files, and one or more control files. The files of an Oracle database provide the actual physical storage for database information. Logical Database Structure An Oracle database’s logical structure is determined by: • one or more tablespaces A tablespace is a logical area of storage. • the database’s schema objects A schema is a collection of objects. Schema objects are the logical structures that directly refer to the database’s data. Schema objects include such structures as tables, views, sequences, stored procedures, synonyms, indexes, clusters, and database links. The logical storage structures, including tablespaces, segments, and extents, dictate how the physical space of a database is used. The schema objects and the relationships among them form the relational design of a database. AN ORACLE INSTANCE Every time a database is started, a system global area (SGA) is allocated and Oracle background processes are started. The system global area is a an area of memory used for database information shared by the database users. The combination of the background processes and memory buffers is called an Oracle instance. An Oracle instance has two types of processes: user processes and Oracle processes. Fig. 1-1 : An Oracle Instance • A user process executes the code of an application program (such as an Oracle Forms applica- tion) or an Oracle Tool (such as Oracle Enterprise Manager). • Oracle processes are server processes that perform work for the user processes and background processes that perform maintenance work for the Oracle server. Figure 1-1 illustrates a multiple-process Oracle instance. 12
  • 13. ORACLE ORACLE DATABASES An Oracle database is the collection of data that is treated as a unit. The general purpose of a database is to store and retrieve related information. Open and Closed Databases An Oracle database can be open (accessible) or closed (not accessible). In normal situations, the data- base is open and available for use. However, the database is sometimes closed for specific administra- tive functions that require the database’s data to be unavailable to users. ARCHITECTURE OF DATABASE The database has logical structures and physical structures. Logical Database Structures The following sections explain logical database structures, including tablespaces, schema objects, data blocks, extents, and segments. Tablespaces A database is divided into logical storage units called tablespaces. A tablespace is used to group related logical structures together. For example, tablespaces commonly group all of an application’s objects to simplify some administrative operations. Databases, Tablespaces, and Datafiles The relationship among databases, tablespaces, and datafiles (datafiles are described in the next section) is illustrated in Figure 1-2. Figure 1-2 Databases, Tablespaces, and Datafiles This figure illustrates the following: • Each database is logically divided into one or more tablespaces. • One or more datafiles are explicitly created for each tablespace to physically store the data of all logical structures in a tablespace. 13
  • 14. ORACLE Online and Offline Tablespaces A tablespace can be online (accessible) or offline (not accessible). A tablespace is normally online so that users can access the information within the tablespace. However, sometimes a tablespace may be taken offline to make a portion of the database unavailable while allowing normal access to the remainder of the database. This makes many administrative tasks easier to perform. MEMORY STRUCTURE OF ORACLE DATABASE An Oracle server uses memory structures and processes to manage and access the database. All memory structures exist in the main memory of the computers that constitute the database system. Processes are jobs or tasks that work in the memory of these computers. Figure 1-3 shows a typical variation of the Oracle server memory and process structures. Memory Structures Oracle creates and uses memory structures to complete several jobs. For example, memory stores program code being executed and data that is shared among users. Several basic memory structures are associated with Oracle: the system global area (which includes the database buffers, redo log buffers, and the shared pool) and the program global areas. The following subsections explain each in detail. Figure 1-3 Memory Structures and Processes of Oracle 14
  • 15. ORACLE SYSTEM GLOBAL AREA The System Global Area (SGA) is a shared memory region that contains data and control information for one Oracle instance. An SGA and the Oracle background processes constitute an Oracle instance. Oracle allocates the system global area when an instance starts and deallocates it when the instance shuts down. Each instance has its own system global area. Users currently connected to an Oracle server share the data in the system global area. For optimal performance, the entire system global area should be as large as possible (while still fitting in real memory) to store as much data in memory as possible and minimize disk I/O. The information stored within the system global area is divided into several types of memory struc- tures, including the database buffers, redo log buffer, and the shared pool. These areas have fixed sizes and are created during instance startup. Database Buffer Cache Database buffers of the system global area store the most recently used blocks of database data; the set of database buffers in an instance is the database buffer cache. The buffer cache contains modified as well as unmodified blocks. Because the most recently (and often the most frequently) used data is kept in memory, less disk I/O is necessary and performance is improved. Redo Log Buffer The redo log buffer of the system global area stores redo entries - a log of changes made to the database. The redo entries stored in the redo log buffers are written to an online redo log file, which is used if database recovery is necessary. Its size is static. Shared Pool The shared pool is a portion of the system global area that contains shared memory constructs such as shared SQL areas. A shared SQL area is required to process every unique SQL statement submitted to a database. A shared SQL area contains information such as the parse tree and execution plan for the corresponding statement. A single shared SQL area is used by multiple applications that issue the same statement, leaving more shared memory for other uses. Statement Handles or Cursors A cursor is a handle (a name or pointer) for the memory associated with a specific statement. (The Oracle Call Interface, OCI, refers to these as statement handles.) Although most Oracle users rely on the automatic cursor handling of the Oracle utilities, the programmatic interfaces offer application designers more control over cursors. For example, in precompiler application development, a cursor is a named resource available to a program and can be specifically used for the parsing of SQL statements embedded within the application. The application developer can code an application so that it controls the phases of SQL statement execution and thus improve application performance. 15
  • 16. ORACLE BACKGROUND PROCESSES Oracle creates a set of background processes for each instance. They consolidate functions that would otherwise be handled by multiple Oracle programs running for each user process. The background processes asynchronously perform I/O and monitor other Oracle processes to provide increased paral- lelism for better performance and reliability. An SGA and the set of Oracle background processes constitute an Oracle instance. Each Oracle in- stance may use several background processes. The names of these processes are DBWn, LGWR, CKPT, SMON, PMON, ARCH, RECO, Dnnn, LCKn, SNPn, and QMNn. Database Writer (DBWn) The Database Writer writes modified blocks from the database buffer cache to the datafiles. Although one database writer process (DBW0) is sufficient for most systems, you can configure additional pro- cesses (DBW1 through DBW9) to improve write performance for a system that modifies data heavily. The initialization parameter DB_WRITER_PROCESSES specifies the number of DBWn processes. Since Oracle uses write-ahead logging, DBWn does not need to write blocks when a transaction com- mits. Instead, DBWn is designed to perform batched writes with high efficiency. In the most common case, DBWn writes only when more data needs to be read into the system global area and too few database buffers are free. The least recently used data is written to the datafiles first. DBWn also per- forms writes for other functions such as checkpointing. Log Writer (LGWR) The Log Writer writes redo log entries to disk. Redo log data is generated in the redo log buffer of the system global area. As transactions commit and the log buffer fills, LGWR writes redo log entries into an online redo log file. Checkpoint (CKPT) At specific times, all modified database buffers in the system global area are written to the datafiles by DBWn; this event is called a checkpoint. The Checkpoint process is responsible for signalling DBWn at checkpoints and updating all the datafiles and control files of the database to indicate the most recent checkpoint. System Monitor (SMON) The system monitor performs instance recovery at instance startup. In a multiple instance system (one that uses Oracle Parallel Server), SMON of one instance can also perform instance recovery for other instances that have failed. SMON also cleans up temporary segments that are no longer in use and recovers dead transactions skipped during crash and instance recovery because of file-read or offline errors. These transactions are eventually recovered by SMON when the tablespace or file is brought back online. SMON also coalesces free extents within the database to make free space contiguous and easier to allocate. 16
  • 17. ORACLE Process Monitor (PMON) The process monitor performs process recovery when a user process fails. PMON is responsible for cleaning up the cache and freeing resources that the process was using. PMON also checks on dispatcher (see below) and server processes and restarts them if they have failed. THE PROGRAM INTERFACE The program interface is the mechanism by which a user process communicates with a server process. It serves as a method of standard communication between any client tool or application (such as Oracle Forms) and Oracle software. Its functions are to: • act as a communications mechanism, by formatting data requests, passing data, and trapping and returning errors • perform conversions and translations of data, particularly between different types of computers or to external user program datatypes AN EXAMPLE OF HOW ORACLE WORKS The following example illustrates an Oracle configuration where the user and associated server process are on separate machines (connected via a network). 1. An instance is currently running on the computer that is executing Oracle (often called the host or database server). 2. A computer running an application (a local machine or client workstation) runs the application in a user process. The client application attempts to establish a connection to the server using the proper Net8 driver. 3. The server is running the proper Net8 driver. The server detects the connection request from the application and creates a (dedicated) server process on behalf of the user process. 4. The user executes a SQL statement and commits the transaction. For example, the user changes a name in a row of a table. 5. The server process receives the statement and checks the shared pool for any shared SQL area that contains an identical SQL statement. If a shared SQL area is found, the server process checks the user’s access privileges to the requested data and the previously existing shared SQL area is used to process the statement; if not, a new shared SQL area is allocated for the statement so that it can be parsed and processed. 6. The server process retrieves any necessary data values from the actual datafile (table) or those stored in the system global area. 7. The server process modifies data in the system global area. The DBWn process writes modified blocks permanently to disk when doing so is efficient. Because the transaction committed, the LGWR process immediately records the transaction in the online redo log file. 8. If the transaction is successful, the server process sends a message across the network to the application. If it is not successful, an appropriate error message is transmitted. 9. Throughout this entire procedure, the other background processes run, watching for conditions that require intervention. In addition, the database server manages other users’ transactions and prevents contention between transactions that request the same data. These steps describe only the most basic level of operations that Oracle performs. 17
  • 18. ORACLE DATA CONCURRENCY AND CONSISTENCY This section explains the software mechanisms used by Oracle to fulfill the following important re- quirements of an information management system: • Data must be read and modified in a consistent fashion. • Data concurrency of a multi-user system must be maximized. • High performance is required for maximum productivity from the many users of the database system. Concurrency A primary concern of a multiuser database management system is how to control concurrency, or the simultaneous access of the same data by many users. Without adequate concurrency controls, data could be updated or changed improperly, compromising data integrity. If many people are accessing the same data, one way of managing data concurrency is to make each user wait his or her turn. The goal of a database management system is to reduce that wait so it is either non-existent or negligible to each user. All data manipulation (DML) statements should proceed with as little interference as possible and destructive interactions between concurrent transactions must be prevented. Destructive interaction is any interaction that incorrectly updates data or incorrectly alters underlying data structures. Neither performance nor data integrity can be sacrificed. Oracle resolves such issues by using various types of locks and a multiversion consistency model. Both features are discussed later in this section. These features are based on the concept of a transaction. It is the application designer’s responsibility to ensure that transactions fully exploit these concurrency and consistency features. READ CONSISTENCY Read consistency, as supported by Oracle, does the following: • guarantees that the set of data seen by a statement is consistent with respect to a single point-in- time and does not change during statement execution (statement-level read consistency) • ensures that readers of database data do not wait for writers or other readers of the same data • ensures that writers of database data do not wait for readers of the same data • ensures that writers only wait for other writers if they attempt to update identical rows in con- current transactions The simplest way to think of Oracle’s implementation of read consistency is to imagine each user operating a private copy of the database, hence the multiversion consistency model. Read Consistency, Rollback Segments, and Transactions To manage the multiversion consistency model, Oracle must create a read-consistent set of data when a table is being queried (read) and simultaneously updated (written). When an update occurs, the origi- nal data values changed by the update are recorded in the database’s rollback segments. As long as this 18
  • 19. ORACLE update remains part of an uncommitted transaction, any user that later queries the modified data views the original data values - Oracle uses current information in the system global area and information in the rollback segments to construct a read-consistent view of a table’s data for a query. Only when a transaction is committed are the changes of the transaction made permanent. Statements that start after the user’s transaction is committed only see the changes made by the committed transac- tion. Note that a transaction is key to Oracle’s strategy for providing read consistency. This unit of commit- ted (or uncommitted) SQL statements: • dictates the start point for read-consistent views generated on behalf of readers • controls when modified data can be seen by other transactions of the database for reading or updating. Read-Only Transactions By default, Oracle guarantees statement-level read consistency. The set of data returned by a single query is consistent with respect to a single point in time. However, in some situations, you may also require transaction-level read consistency - the ability to run multiple queries within a single transac- tion, all of which are read-consistent with respect to the same point in time, so that queries in this transaction do not see the effects of intervening committed transactions. If you want to run a number of queries against multiple tables and if you are doing no updating, you may prefer a read-only transaction. After indicating that your transaction is read-only, you can execute as many queries as you like against any table, knowing that the results of each query are consistent with respect to the same point in time. LOCKING MECHANISMS Oracle also uses locks to control concurrent access to data. Locks are mechanisms intended to prevent destructive interaction between users accessing Oracle data. Locks are used to achieve two important database goals: consistency Ensures that the data a user is viewing or changing is not changed (by other users) until the user is finished with the data. integrity Ensures that the database’s data and structures reflect all changes made to them in the correct sequence. Locks guarantee data integrity while allowing maximum concurrent access to the data by unlimited users. Automatic Locking Oracle locking is performed automatically and requires no user action. Implicit locking occurs for SQL statements as necessary, depending on the action requested. 19
  • 20. ORACLE Oracle’s sophisticated lock manager automatically locks table data at the row level. By locking table data at the row level, contention for the same data is minimized. Oracle’s lock manager maintains several different types of row locks, depending on what type of opera- tion established the lock. In general, there are two types of locks: exclusive locks and share locks. Only one exclusive lock can be obtained on a resource (such as a row or a table); however, many share locks can be obtained on a single resource. Both exclusive and share locks always allow queries on the locked resource, but prohibit other activity on the resource (such as updates and deletes). Manual Locking Under some circumstances, a user may want to override default locking. Oracle allows manual over- ride of automatic locking features at both the row level (by first querying for the rows that will be updated in a subsequent statement) and the table level. ORDBMS Database management systems have evolved from hierarchical to network to relational models. The most widely accepted database model is the relational model. Oracle extends the relational model to an object-relational model, which makes it possible to store complex business models in a relational database. The Relational Model The relational model has three major aspects: structures Structures are well-defined objects (such as tables, views, indexes, and so on) that store or access the data of a database. Structures and the data contained within them can be manipulated by operations. operations Operations are clearly defined actions that allow users to manipulate the data and structures of a database. The operations on a database must adhere to a predefined set of integrity rules. integrity rules Integrity rules are the laws that govern which operations are allowed on the data and structures of a database. Integrity rules protect the data and the structures of a database. Relational database management systems offer benefits such as: • independence of physical data storage and logical database structure • variable and easy access to all data • complete flexibility in database design • reduced data storage and redundancy THE OBJECT-RELATIONAL MODEL The object-relational model allows users to define object types, specifying both the structure of the data and the methods of operating on the data, and to use these datatypes within the relational model. 20
  • 21. ORACLE Object types are abstractions of the real-world entities - for example, purchase orders - that application programs deal with. An object type has three kinds of components: • A name, which serves to identify the object type uniquely. • Attributes, which are built-in datatypes or other user-defined types. Attributes model the struc- ture of the real world entity. • Methods, which are functions or procedures written in PL/SQL and stored in the database, or written in a language like C and stored externally. Methods implement specific operations that an application can perform on the data. Every object type has a constructor method that makes a new object according to the datatype’s specification. SCHEMAS AND SCHEMA OBJECTS A schema is a collection of database objects that are available to a user. Schema objects are the logical structures that directly refer to the database’s data. Schema objects include such structures as tables, views, sequences, stored procedures, synonyms, indexes, clusters, and database links. (There is no relationship between a tablespace and a schema; objects in the same schema can be in different tablespaces, and a tablespace can hold objects from different schemas.) Tables A table is the basic unit of data storage in an Oracle database. The tables of a database hold all of the user-accessible data. Table data is stored in rows and columns. Every table is defined with a table name and set of columns. Each column is given a column name, a datatype (such as CHAR, DATE, or NUMBER), and a width (which may be predetermined by the datatype, as in DATE) or scale and precision (for the NUMBER datatype only). Once a table is created, valid rows of data can be inserted into it. The table’s rows can then be queried, deleted, or updated. Oracle8 provides for the partitioning of tables. To enforce defined business rules on a table’s data, integrity constraints and triggers can also be defined for a table. Views A view is a custom-tailored presentation of the data in one or more tables. A view can also be thought of as a “stored query”. Views do not actually contain or store data; rather, they derive their data from the tables on which they are based, referred to as the base tables of the views. Base tables can in turn be tables or can themselves be views. Like tables, views can be queried, updated, inserted into, and deleted from, with some restrictions. All operations performed on a view actually affect the base tables of the view. 21
  • 22. ORACLE Views are often used to do the following: • Provide an additional level of table security by restricting access to a predetermined set of rows and columns of a table. For example, a view of a table can be created so that columns with sensitive data (for example, salary information) are not included in the definition of the view. • Hide data complexity. For example, a single view can combine 12 monthly sales tables to pro- vide a year of data for analysis and reporting. A single view can also be used to create a join, which is a display of related columns or rows in multiple tables. However, the view hides the fact that this data actually originates from several tables. • Simplify commands for the user. For example, views allow users to select information from multiple tables without requiring the users to actually know how to perform a correlated subquery. • Present the data in a different perspective from that of the base table. For example, views pro- vide a means to rename columns without affecting the tables on which the view is based. • Store complex queries. For example, a query might perform extensive calculations with table information. By saving this query as a view, the calculations are performed only when the view is queried. Views that involve a join (a SELECT statement that selects data from multiple tables) of two or more tables can only be updated under certain conditions. Sequences A sequence generates a serial list of unique numbers for numeric columns of a database’s tables. Se- quences simplify application programming by automatically generating unique numerical values for the rows of a single table or multiple tables. For example, assume two users are simultaneously inserting new employee rows into the EMP table. By using a sequence to generate unique employee numbers for the EMPNO column, neither user has to wait for the other to input the next available employee number. The sequence automatically generates the correct values for each user. Sequence numbers are independent of tables, so the same sequence can be used for one or more tables. After creation, a sequence can be accessed by various users to generate actual sequence numbers. Program Units The term “program unit” is used in this manual to refer to stored procedures, functions, packages, triggers, and anonymous blocks. A procedure or function is a set of SQL and PL/SQL (Oracle’s procedural language extension to SQL) statements grouped together as an executable unit to perform a specific task. Procedures and functions allow you to combine the ease and flexibility of SQL with the procedural functionality of a structured programming language. Using PL/SQL, such procedures and functions can be defined and stored in the database for continued use. Procedures and functions are identical, except that functions always return a single value to the caller, while procedures do not return a value to the caller. Packages provide a method of encapsulating and storing related procedures, functions, and other pack- age constructs together as a unit in the database. While packages provide the database administrator or 22
  • 23. ORACLE application developer organizational benefits, they also offer increased functionality and database per- formance. Synonyms A synonym is an alias for a table, view, sequence, or program unit. A synonym is not actually a schema object itself, but instead is a direct reference to a schema object. Synonyms are used to • mask the real name and owner of a schema object • provide public access to a schema object • provide location transparency for tables, views, or program units of a remote database • simplify the SQL statements for database users A synonym can be public or private. An individual user can create a private synonym, which is avail- able only to that user. Database administrators most often create public synonyms that make the base schema object available for general, system-wide use by any database user. THE DATA DICTIONARY Each Oracle database has a data dictionary. An Oracle data dictionary is a set of tables and views that are used as a read-only reference about the database. For example, a data dictionary stores information about both the logical and physical structure of the database. In addition to this valuable information, a data dictionary also stores such information as: • the valid users of an Oracle database • information about integrity constraints defined for tables in the database • how much space is allocated for a schema object and how much of it is in use A data dictionary is created when a database is created. To accurately reflect the status of the database at all times, the data dictionary is automatically updated by Oracle in response to specific actions (such as when the structure of the database is altered). The data dictionary is critical to the operation of the database, which relies on the data dictionary to record, verify, and conduct ongoing work. For example, during database operation, Oracle reads the data dictionary to verify that schema objects exist and that users have proper access to them. DATA ACCESS This section introduces how Oracle meets the general requirements for a DBMS to: • adhere to industry accepted standards for a data access language • control and preserve the consistency of a database’s information while manipulating its data • provide a system for defining and enforcing rules to maintain the integrity of a database’s information • provide high performance SQL - THE STRUCTURED QUERY LANGUAGE SQL is a simple, powerful database access language that is the standard language for relational data- base management systems. The SQL implemented by Oracle Corporation for Oracle is 100 percent compliant with the ANSI/ISO standard SQL data language. 23
  • 24. ORACLE SQL Statements All operations on the information in an Oracle database are performed using SQL statements. A SQL statement is a string of SQL text that is given to Oracle to execute. A statement must be the equivalent of a complete SQL sentence, as in: SELECT ename, deptno FROM emp; Only a complete SQL statement can be executed, whereas a sentence fragment, such as the following, generates an error indicating that more text is required before a SQL statement can execute: SELECT ename A SQL statement can be thought of as a very simple, but powerful, computer program or instruction. SQL statements are divided into the following categories: • Data Definition Language (DDL) statements • Data Manipulation Language (DML) statements • transaction control statements • session control statements • system control statements • embedded SQL statements Data Definition Statements (DDL) DDL statements define, maintain, and drop schema objects when they are no longer needed. DDL statements also include statements that permit a user to grant other users the privileges, or rights, to access the database and specific objects within the database. Data Manipulation Statements (DML) DML statements manipulate the database’s data. For example, querying, inserting, updating, and delet- ing rows of a table are all DML operations; locking a table or view and examining the execution plan of an SQL statement are also DML operations. Transaction Control Statements Transaction control statements manage the changes made by DML statements. They allow the user or application developer to group changes into logical transactions. Session Control Statements Session control statements allow a user to control the properties of his current session, including en- abling and disabling roles and changing language settings. The two session control statements are ALTER SESSION and SET ROLE. 24
  • 25. ORACLE System Control Statements System control commands change the properties of the Oracle server instance. The only system control command is ALTER SYSTEM; it allows you to change such settings as the minimum number of shared servers, to kill a session, and to perform other tasks. Embedded SQL Statements Embedded SQL statements incorporate DDL, DML, and transaction control statements in a procedural language program (such as those used with the Oracle Precompilers). Examples include OPEN, CLOSE, FETCH, and EXECUTE. PL/SQL PL/SQL is Oracle’s procedural language extension to SQL. PL/SQL combines the ease and flexibility of SQL with the procedural functionality of a structured programming language, such as IF ... THEN, WHILE, and LOOP. When designing a database application, a developer should consider the advantages of using stored PL/ SQL: • Because PL/SQL code can be stored centrally in a database, network traffic between applica- tions and the database is reduced, so application and system performance increases. • Data access can be controlled by stored PL/SQL code. In this case, the users of PL/SQL can access data only as intended by the application developer (unless another access route is granted). • PL/SQL blocks can be sent by an application to a database, executing complex operations with- out excessive network traffic. Even when PL/SQL is not stored in the database, applications can send blocks of PL/SQL to the data- base rather than individual SQL statements, thereby again reducing network traffic. The following sections describe the different program units that can be defined and stored centrally in a database. Procedures and Functions Procedures and functions consist of a set of SQL and PL/SQL statements that are grouped together as a unit to solve a specific problem or perform a set of related tasks. A procedure is created and stored in compiled form in the database and can be executed by a user or a database application. Procedures and functions are identical except that functions always return a single value to the caller, while procedures do not return values to the caller. Packages Packages provide a method of encapsulating and storing related procedures, functions, variables, and other package constructs together as a unit in the database. While packages allow the administrator or application developer the ability to organize such routines, they also offer increased functionality (for example, global package variables can be declared and used by any procedure in the package) and performance (eg. all objects of the package are parsed, compiled, and loaded into memory once). 25
  • 26. ORACLE Database Triggers Oracle allows you to write procedures that are automatically executed as a result of an insert in, update to, or delete from a table. These procedures are called database triggers. Database triggers can be used in a variety of ways for the information management of your database. For example, they can be used to automate data generation, audit data modifications, enforce complex integrity constraints, and customize complex security authorizations. Methods A method is a procedure or function that is part of the definition of a user-defined datatype (object type, nested table, or variable array). Methods are different from stored procedures in two ways: • You invoke a method by referring to an object of its associated type. • A method has complete access to the attributes of its associated object and to information about its type. Every user-defined datatype has a system-defined constructor method, that is, a method that makes a new object according to the datatype’s specification. The name of the constructor method is the name of the user-defined type. In the case of an object type, the constructor method’s parameters have the names and types of the object type’s attributes. The constructor method is a function that returns the new object as its value. Nested tables and arrays also have constructor methods. Comparison methods define an order relationship among objects of a given object type. A map method uses Oracle’s ability to compare built-in types. For example, Oracle can compare two rectangles by comparing their areas if an object type called RECTANGLE has attributes HEIGHT and WIDTH and you define a map method area that returns a number, namely the product of the rectangle’s HEIGHT and WIDTH attributes. An order method uses its own internal logic to compare two objects of a given object type. It returns a value that encodes the order relationship. For example, it may return -1 if the first is smaller, 0 if they are equal, and 1 if the first is larger. DATA INTEGRITY It is very important to guarantee that data adheres to certain business rules, as determined by the data- base administrator or application developer. For example, assume that a business rule says that no row in the INVENTORY table can contain a numeric value greater than 9 in the SALE_DISCOUNT col- umn. If an INSERT or UPDATE statement attempts to violate this integrity rule, Oracle must roll back the invalid statement and return an error to the application. Oracle provides integrity constraints and database triggers as solutions to manage a database’s data integrity rules. Integrity Constraints An integrity constraint is a declarative way to define a business rule for a column of a table. An integrity constraint is a statement about a table’s data that is always true: 26
  • 27. ORACLE • If an integrity constraint is created for a table and some existing table data does not satisfy the constraint, the constraint cannot be enforced. • After a constraint is defined, if any of the results of a DML statement violate the integrity constraint, the statement is rolled back and an error is returned. Integrity constraints are defined with a table and are stored as part of the table’s definition, centrally in the database’s data dictionary, so that all database applications must adhere to the same set of rules. If a rule changes, it need only be changed once at the database level and not many times for each applica- tion. The following integrity constraints are supported by Oracle: NOT NULL Disallows nulls (empty entries) in a table’s column. UNIQUE Disallows duplicate values in a column or set of columns. PRIMARY KEY Disallows duplicate values and nulls in a column or set of columns. FOREIGN KEY Requires each value in a column or set of columns match a value in a related table’s UNIQUE or PRIMARY KEY (FOREIGN KEY integrity constraints also define referential integrity actions that dictate what Oracle should do with dependent data if the data it references is altered). CHECK Disallows values that do not satisfy the logical expression of the constraint. Keys The term “key” is used in the definitions of several types of integrity constraints. A key is the column or set of columns included in the definition of certain types of integrity constraints. Keys describe the relationships between the different tables and columns of a relational database. The different types of keys include: primary key The column or set of columns included in the definition of a table’s PRIMARY KEY constraint. A primary key’s values uniquely identify the rows in a table. Only one primary key may be defined per table. unique key The column or set of columns included in the definition of a UNIQUE constraint. foreign key The column or set of columns included in the definition of a referential integrity constraint. Referenced key The unique key or primary key of the same or different table that is referenced by a foreign key. Individual values in a key are called key values. Database Triggers Centralized actions can be defined using a non-declarative approach (writing PL/SQL code) with database triggers. A database trigger is a stored procedure that is fired (implicitly executed) when an INSERT, UPDATE, or DELETE statement is issued against the associated table. Database triggers can be used to customize a database management system with such features as value-based auditing and the enforcement 27
  • 28. ORACLE of complex security checks and integrity rules. For example, a database trigger might be created to allow a table to be modified only during normal business hours. Note: While database triggers allow you to define and enforce integrity rules, a database trigger is not the same as an integrity constraint. Among other things, a database trigger defined to enforce an integrity rule does not check data already loaded into a table. Therefore, it is strongly recommended that you use database triggers only when the integrity rule cannot be enforced by integrity constraints. 28
  • 29. ORACLE SQL - AN INTRODUCTION COMPETENCY OBJECTIVES This chapter covers the following topics v SQL - An Introduction v Data types in SQL v SQL - Queries v SQL Commands 29
  • 31. ORACLE CHAPTER - 2 SQL - AN INTRODUCTION The language, Structured English Query Language (“SEQUEL”) was developed by IBM Corporation, Inc., to use Codd’s model. SEQUEL later became SQL (still pronounced “sequel”). In 1979, Relational Software, Inc. (now Oracle Corporation) introduced the first commercially available implementation of SQL. Today, SQL is accepted as the standard RDBMS language. Working of SQL The strengths of SQL benefit all types of users, including application programmers, database adminis- trators, management, and end users. Technically speaking, SQL is a data sublanguage: the purpose of SQL is to provide an interface to a relational database such as Oracle, and all SQL statements are instructions to the database. In this it differs from general-purpose programming languages like C and BASIC. Among the features of SQL are the following: • It processes sets of data as groups rather than as individual units. • It provides automatic navigation to the data. Essentially, SQL lets you work with data at the logical level. You need to be concerned with the imple- mentation details only when you want to manipulate the data. For example, to retrieve a set of rows from a table, you define a condition used to filter the rows. All rows satisfying the condition are re- trieved in a single step and can be passed as a unit to the user, to another SQL statement, or to an application. You need not deal with the rows one by one, nor do you have to worry about how they are physically stored or retrieved. All SQL statements use the optimizer, a part of Oracle that determines a fast means of accessing the specified data. Oracle also provides techniques you can use to make the optimizer perform its job better. SQL provides commands for a variety of tasks, including: • querying data • inserting, updating, and deleting rows in a table • creating, replacing, altering, and dropping objects • controlling access to the database and its objects • guaranteeing database consistency and integrity SQL unifies all of the above tasks in one consistent language. 31
  • 32. ORACLE Language for All Relational Databases All major relational database management systems support SQL, so you can transfer all skills you have gained with SQL from one database to another. In addition, all programs written in SQL are portable: they can often be moved from one database to another with very little modification. EMBEDDED SQL Embedded SQL refers to the use of standard SQL commands embedded within a procedural programming language. Embedded SQL is a collection of these commands: • all SQL commands, such as SELECT and INSERT, available with SQL with interactive tools • dynamic SQL execution commands, such as PREPARE and OPEN, which integrate the standard SQL commands with a procedural programming language Embedded SQL also includes extensions to some standard SQL commands. Embedded SQL is supported by the Oracle precompilers. The Oracle precompilers interpret embedded SQL statements and translate them into statements that can be understood by procedural language compilers. Each of these Oracle precompilers translates embedded SQL programs into a different procedural language: • the Pro*C/C++ precompiler • the Pro*COBOL precompiler • the Pro*FORTRAN precompiler • the SQL*Module for ADA ELEMENTS OF SQL LANGUAGE Basic elements of Oracle SQL : • Literals • Text • Integer • Number • Datatypes • Nulls • Pseudocolumns • Comments Literals The terms literal and constant value are synonymous and refer to a fixed data value. For example, ‘JACK’, ‘BLUE ISLAND’, and ‘101’ are all character literals; 5001 is a numeric literal. Note that character literals are enclosed in single quotation marks, which enable Oracle to distinguish them from schema object names. Many SQL statements and functions require you to specify character and numeric literal values. You can also specify literals as part of expressions and conditions. You can specify character literals with 32
  • 33. ORACLE the ‘text’ notation, national character literals with the N’text’ notation, and numeric literals with the integer or number notation, depending on the context of the literal. The syntactic forms of these notations appear in the following sections. Text Text specifies a text or character literal. You must use this notation to specify values whenever ‘text’ or char appear in expressions, conditions, SQL functions, and SQL commands in other parts of this refer- ence. A text literal must be enclosed in single quotation marks. This reference uses the terms text literal and character literal interchangeably. Text literals have properties of both the CHAR and VARCHAR2 datatypes: • Within expressions and conditions, Oracle treats text literals as though they have the datatype CHAR by comparing them using blank-padded comparison semantics. • A text literal can have a maximum length of 4000 bytes. Here are some valid text literals: ‘Hello’ ‘ORACLE.dbs’ ‘Jackie’’s raincoat’ ’09-MAR-92' N’nchar literal’ Integer You must use the integer notation to specify an integer whenever integer appears in expressions, conditions, SQL functions, and SQL commands described in other parts of this reference. An integer can store a maximum of 38 digits of precision. Here are some valid integers: 7 +255 Number You must use the number notation to specify values whenever number appears in expressions, condi- tions, SQL functions, and SQL commands in other parts of this reference. A number can store a maximum of 38 digits of precision. If you have established a decimal character other than a period (.) with the initialization parameter NLS_NUMERIC_CHARACTERS, you must specify numeric literals with ‘text’ notation. In such cases, Oracle automatically converts the text literal to a numeric value. 33
  • 34. ORACLE For example, if the NLS_NUMERIC_CHARACTERS parameter specifies a decimal character of comma, specify the number 5.123 as follows: ‘5,123’ Here are some valid representations of number: 25 +6.34 0.5 25e-03 -1 Datatypes Each literal or column value manipulated by Oracle has a datatype. A value’s datatype associates a fixed set of properties with the value. These properties cause Oracle to treat values of one datatype differently from values of another. For example, you can add values of NUMBER datatype, but not values of RAW datatype. When you create a table or cluster, you must specify an internal datatype for each of its columns. When you create a procedure or stored function, you must specify an internal datatype for each of its arguments. These datatypes define the domain of values that each column can contain or each argument can have. For example, DATE columns cannot accept the value February 29 (except for a leap year) or the values 2 or ‘SHOE’. Each value subsequently placed in a column assumes the column’s datatype. For example, if you insert ’01-JAN-92' into a DATE column, Oracle treats the ’01-JAN-92' character string as a DATE value after verifying that it translates to a valid date. Table 2-1 summarizes Oracle internal datatypes. The rest of this section describes these datatypes in detail. 34
  • 35. ORACLE Table 2-1 : Internal Datatype Summary INTERNAL CODE DATATYPE DESCRIPTION Variable-length character string having maximum length 1 VARCHAR2(size) size bytes. Maximum size is 4000, and minimum is 1. You must specify size for a VARCHAR2. Variable-length character string having maximum length size characters or bytes, depending on the choice of NVARCHAR2(size) national character set. Maximum size is determined by the number of bytes required to store each character, with an upper limit of 4000 bytes. You must specify size for NVARCHAR2. Number having precision p and scale s. The precision p can 2 NUMBER(p,s) range from 1 to 38. The scale s can range from -84 to 127. Character data of variable length up to 2 gigabytes, or 231 - 8 LONG 1 bytes. Valid date range from January 1, 4712 BC to December 31, 12 DATE 4712 AD. Raw binary data of length size bytes. Maximum size is 23 RAW(size) 2000 bytes. You must specify size for a RAW value. 24 LONG RAW Raw binary data of variable length up to 2 gigabytes. Hexadecimal string representing the unique address of a 69 ROWID row in its table. This datatype is primarily for values returned by the ROWID pseudocolumn. Fixed length character data of length size bytes. Maximum 96 CHAR(size) size is 2000 bytes. Default and minimum size is 1 byte. Character Datatypes Character datatypes store character (alphanumeric) data-words and free-form text-in the database or national character set. They are less restrictive than other datatypes and consequently have fewer properties. For example, character columns can store all alphanumeric values, but NUMBER columns can store only numeric values. Character data is stored in strings with byte values corresponding to one of the character sets, such as 7- bit ASCII or EBCDIC Code , specified when the database was created. Oracle supports both single- byte and multibyte character sets. These datatypes are used for character data: These datatypes are used for character data: • CHAR Datatype • VARCHAR2 Datatype 35
  • 36. ORACLE CHAR Datatype The CHAR datatype specifies a fixed-length character string. When you create a table with a CHAR column, you supply the column length in bytes. Oracle subsequently ensures that all values stored in that column have this length. If you insert a value that is shorter than the column length, Oracle blank- pads the value to column length. If you try to insert a value that is too long for the column, Oracle returns an error. The default length for a CHAR column is 1 character and the maximum allowed is 2000 characters. A zero-length string can be inserted into a CHAR column, but the column is blank-padded to 1 character when used in comparisons. VARCHAR2 Datatype The VARCHAR2 datatype specifies a variable-length character string. When you create a VARCHAR2 column, you can supply the maximum number of bytes of data that it can hold. Oracle subsequently stores each value in the column exactly as you specify it, provided it does not exceed the column’s maximum length. This maximum must be at least 1 byte, although the actual length of the string stored is permitted to be zero. If you try to insert a value that exceeds the specified length, Oracle returns an error. You must specify a maximum length for a VARCHAR2 column. The maximum length of VARCHAR2 data is 4000 bytes. Oracle compares VARCHAR2 values using nonpadded comparison semantics. VARCHAR Datatype The VARCHAR datatype is currently synonymous with the VARCHAR2 datatype. Oracle recommends that you use VARCHAR2 rather than VARCHAR. In the future, VARCHAR might be defined as a separate datatype used for variable-length character strings compared with different comparison semantics. NUMBER Datatype The NUMBER datatype stores zero, positive and negative fixed and floating-point numbers with magnitudes between 1.0 x 10-130 and 9.9...9 x 10125 (38 nines followed by 88 zeroes) with 38 digits of precision. If you specify an arithmetic expression whose value has a magnitude greater than or equal to 1.0 x 10126, Oracle returns an error. Specify a fixed-point number using the following form: NUMBER(p,s) where: s is the scale, or the number of digits to the right of the decimal point. The scale can range from -84 to 127. 36
  • 37. ORACLE Specify an integer using the following form: NUMBER(p) is a fixed-point number with precision p and scale 0. This is equivalent to NUMBER(p,0). Specify a floating-point number using the following form: NUMBER is a floating-point number with decimal precision 38. Note that a scale value is not applicable for floating-point numbers. Scale and Precision Specify the scale and precision of a fixed-point number column for extra integrity checking on input. Specifying scale and precision does not force all values to a fixed length. If a value exceeds the precision, Oracle returns an error. If a value exceeds the scale, Oracle rounds it. The following examples show how Oracle stores data using different precisions and scales. 7456123.89 NUMBER 7456123.89 7456123.89 NUMBER(9) 7456124 7456123.89 NUMBER(9,2) 7456123.89 7456123.89 NUMBER(9,1) 7456123.9 7456123.89 NUMBER(6) exceeds precision 7456123.89 NUMBER(7,-2) 7456100 7456123.89 NUMBER(-7,2) exceeds precision Negative Scale If the scale is negative, the actual data is rounded to the specified number of places to the left of the decimal point. For example, a specification of (10,-2) means to round to hundreds. Scale Greater than Precision You can specify a scale that is greater than precision, although it is uncommon. In this case, the precision specifies the maximum number of digits to the right of the decimal point. As with all number datatypes, if the value exceeds the precision, Oracle returns an error message. If the value exceeds the scale, Oracle rounds the value. For example, a column defined as NUMBER(4,5) requires a zero for the first digit after the decimal point and rounds all values past the fifth digit after the decimal point. The following examples show the effects of a scale greater than precision: Actual Data Specified As Stored As .01234 NUMBER(4,5) .01234 .00012 NUMBER(4,5) .00012 .000127 NUMBER(4,5) .00013 .0000012 NUMBER(2,7) .0000012 .00000123 NUMBER(2,7) .0000012 37
  • 38. ORACLE Floating-Point Numbers Oracle allows you to specify floating-point numbers, which can have a decimal point anywhere from the first to the last digit or can have no decimal point at all. A scale value is not applicable to floating- point numbers, because the number of digits that can appear after the decimal point is not restricted. Oracle also supports the ANSI datatype FLOAT. You can specify this datatype using one of these syntactic forms: FLOAT specifies a floating-point number with decimal precision 38, or binary precision 126. FLOAT(b) specifies a floating-point number with binary precision b. The precision b can range from 1 to 126. To convert from binary to decimal precision, multiply b by 0.30103. To convert from decimal to binary precision, multiply the decimal precision by 3.32193. The maximum of 126 digits of binary precision is roughly equivalent to 38 digits of decimal precision. LONG Datatype LONG columns store variable length character strings containing up to 2 gigabytes, or 231-1 bytes. LONG columns have many of the characteristics of VARCHAR2 columns. You can use LONG columns to store long text strings. Oracle uses LONG columns in the data dictionary to store the text of view definitions. The length of LONG values may be limited by the memory available on your computer. You can reference LONG columns in SQL statements in these places: • SELECT lists • SET clauses of UPDATE statements • VALUES clauses of INSERT statements The use of LONG values are subject to some restrictions: • A table cannot contain more than one LONG column. • LONG columns cannot appear in integrity constraints (except for NULL and NOT NULL constraints). • LONG columns cannot be indexed. • A stored function cannot return a LONG value. • Within a single SQL statement, all LONG columns, updated tables, and locked tables must be located on the same database. LONG columns cannot appear in certain parts of SQL statements: • WHERE, GROUP BY, ORDER BY, or CONNECT BY clauses or with the DISTINCT operator in SELECT statements • the UNIQUE clause of a SELECT statement • the column list of a CREATE CLUSTER statement • the CLUSTER clause of a CREATE SNAPSHOT statement • SQL functions (such as SUBSTR or INSTR) • expressions or conditions • SELECT lists of queries containing GROUP BY clauses 38
  • 39. ORACLE • SELECT lists of subqueries or queries combined by set operators • SELECT lists of CREATE TABLE ... AS SELECT statements • SELECT lists in subqueries in INSERT statements Triggers can use the LONG datatype in the following manner: • A SQL statement within a trigger can insert data into a LONG column. • If data from a LONG column can be converted to a constrained datatype (such as CHAR and VARCHAR2), a LONG column can be referenced in a SQL statement within a trigger. Note that the maximum length for these datatypes is 32K. • Variables in triggers cannot be declared using the LONG datatype. • :NEW and :OLD cannot be used with LONG columns. . DATE DATATYPE The DATE datatype stores date and time information. Although date and time information can be represented in both CHAR and NUMBER datatypes, the DATE datatype has special associated properties. For each DATE value, Oracle stores the following information: century, year, month, day, hour, minute, and second. To specify a date value, you must convert a character or numeric value to a date value with the TO_DATE function. Oracle automatically converts character values that are in the default date format into date values when they are used in date expressions. The default date format is specified by the initialization parameter NLS_DATE_FORMAT and is a string such as ‘DD-MON-YY’. This example date format includes a two-digit number for the day of the month, an abbreviation of the month name, and the last two digits of the year. If you specify a date value without a time component, the default time is 12:00:00 am (midnight). If you specify a date value without a date, the default date is the first day of the current month. The date function SYSDATE returns the current date and time. For information on the SYSDATE and TO_DATE functions and the default date format. Date Arithmetic You can add and subtract number constants as well as other dates from dates. Oracle interprets number constants in arithmetic date expressions as numbers of days. For example, SYSDATE + 1 is tomorrow. SYSDATE - 7 is one week ago. SYSDATE + (10/1440) is ten minutes from now. Subtracting the HIREDATE column of the EMP table from SYSDATE returns the number of days since each employee was hired. You cannot multiply or divide DATE values. Oracle provides functions for many of the common date operations. For example, the ADD_MONTHS function allows you to add or subtract months from a date. The MONTHS_BETWEEN function returns the number of months between two dates. The fractional portion of the result represents that portion of a 31-day month. Because each date contains a time component, most results of date operations include a fraction. This fraction means a portion of one day. For example, 1.5 days is 36 hours. 39
  • 40. ORACLE Using Julian Dates A Julian date is the number of days since January 1, 4712 bc. Julian dates allow continuous dating from a common reference. You can use the date format model “J” with date functions TO_DATE and TO_CHAR to convert between Oracle DATE values and their Julian equivalents. Example This statement returns the Julian equivalent of January 1, 1997: SELECT TO_CHAR(TO_DATE(’01-01-1997', ‘MM-DD-YYYY’),’J’) FROM DUAL; TO_CHAR ———— 2450450 RAW and LONG RAW Datatypes The RAW and LONG RAW datatypes store data that is not to be interpreted (not explicitly converted when moving data between different systems) by Oracle. These datatypes are intended for binary data or byte strings. For example, you can use LONG RAW to store graphics, sound, documents, or arrays of binary data; the interpretation is dependent on the use. RAW is a variable-length datatype like the VARCHAR2 character datatype, except that Net8 (which connects user sessions to the instance) and the Import and Export utilities do not perform character conversion when transmitting RAW or LONG RAW data. In contrast, Net8 and Import/Export auto- matically convert CHAR, VARCHAR2, and LONG data from the database character set to the user session character set (set by the NLS_LANGUAGE parameter of the ALTER SESSION command), if the two character sets are different. When Oracle automatically converts RAW or LONG RAW data to and from CHAR data, the binary data is represented in hexadecimal form with one hexadecimal character representing every four bits of RAW data. For example, one byte of RAW data with bits 11001011 is displayed and entered as ‘CB’. You can index RAW data, but not LONG RAW data. ROWID Datatype Each row in the database has an address. You can examine a row’s address by querying the pseudocolumn ROWID. Values of this pseudocolumn are hexadecimal strings representing the address of each row. These strings have the datatype ROWID. You can also create tables and clusters that contain actual columns having the ROWID datatype. Oracle does not guarantee that the values of such columns are valid ROWIDs. Datatype Comparison Rules This section describes how Oracle compares values of each datatype. 40
  • 41. ORACLE Number Values A larger value is considered greater than a smaller one. All negative numbers are less than zero and all positive numbers. Thus, -1 is less than 100; -100 is less than -1. Date Values A later date is considered greater than an earlier one. For example, the date equivalent of ’29-MAR- 1991' is less than that of ’05-JAN-1992' and ’05-JAN-1992 1:35pm’ is greater than ’05-JAN-1992 10:09am’. Character String Values Character values are compared using one of these comparison rules: • blank-padded comparison semantics • nonpadded comparison semantics The following sections explain these comparison semantics. The results of comparing two character values using different comparison semantics may be different. Table 2-5 shows the results of compar- ing five pairs of character values using each comparison semantic. Usually, the results of blank-padded and nonpadded comparisons are the same.The last comparison in the table illustrates the differences between the blank-padded and nonpadded comparison semantics. Blank-Padded Nonpadded 'ab' > 'aa' 'ab' > 'aa' 'ab' > 'a ' 'ab' > 'a ' 'ab' > 'a' 'ab' > 'a' 'ab' = 'ab' 'ab' = 'ab' 'a ' = 'a' 'a ' > 'a' Blank-Padded Comparison Semantics If the two values have different lengths, Oracle first adds blanks to the end of the shorter one so their lengths are equal. Oracle then compares the values character by character up to the first character that differs. The value with the greater character in the first differing position is considered greater. If two values have no differing characters, then they are considered equal. This rule means that two values are equal if they differ only in the number of trailing blanks. Oracle uses blank-padded comparison seman- tics only when both values in the comparison are either expressions of datatype CHAR, NCHAR, text literals, or values returned by the USER function. Nonpadded Comparison Semantics Oracle compares two values character by character up to the first character that differs. The value with the greater character in that position is considered greater. If two values of different length are identical up to the end of the shorter one, the longer value is considered greater. If two values of equal length have no differing characters, then the values are considered equal. Oracle uses nonpadded comparison semantics whenever one or both values in the comparison have the datatype VARCHAR2 or NVARCHAR2. 41
  • 42. ORACLE Single Characters Oracle compares single characters according to their numeric values in the database character set. One character is greater than another if it has a greater numeric value than the other in the character set. Oracle considers blanks to be less than any character, which is true in most character sets. These are some common character sets: • 7-bit ASCII (American Standard Code for Information Interchange) • EBCDIC Code (Extended Binary Coded Decimal Interchange Code) • ISO 8859/1 (International Standards Organization) • JEUC Japan Extended UNIX Portions of the ASCII and EBCDIC character sets appear in Table 2-6 and Table 2-7. Note that upper- case and lowercase letters are not equivalent. Also, note that the numeric values for the characters of a character set may not match the linguistic sequence for a particular language. Table 2-6: ASCII Character Set Symbol Decimal value Symbol Decimal value blank 32 ; 59 ! 33 < 60 " 34 = 61 # 35 > 62 $ 36 ? 63 % 37 @ 64 & 38 A-Z 65-90 ' 39 [ 91 ( 40 92 ) 41 ] 93 * 42 ^^ 94 + 43 _ 95 , 44 ` 96 - 45 a-z 97-122 . 46 { 123 / 47 | 124 0-9 48-57 } 125 : 58 ~ 126 42
  • 43. ORACLE Symbol Decimal value Symbol Decimal value blank 64 % 108 ¢ 74 _ 109 . 75 > 110 < 76 ? 111 ( 77 : 122 + 78 # 123 | 79 @ 124 & 80 ' 125 ! 90 = 126 $ 91 " 127 * 92 a-i 129-137 ) 93 j-r 145-153 ; 94 s-z 162-169 ÿ 95 A-I 193-201 - 96 J-R 209-217 / 97 S-Z 226-233 Data Conversion Generally an expression cannot contain values of different datatypes. For example, an expression can- not multiply 5 by 10 and then add ‘JAMES’. However, Oracle supports both implicit and explicit conversion of values from one datatype to another. Implicit Data Conversion Oracle automatically converts a value from one datatype to another when such a conversion makes sense. Oracle performs conversions in these cases: • When an INSERT or UPDATE statement assigns a value of one datatype to a column of an- other, Oracle converts the value to the datatype of the column. • When you use a SQL function or operator with an argument with a datatype other than the one it accepts, Oracle converts the argument to the accepted datatype. • When you use a comparison operator on values of different datatypes, Oracle converts one of the expressions to the datatype of the other. Example 1 The text literal ‘10’ has datatype CHAR. Oracle implicitly converts it to the NUMBER datatype if it appears in a numeric expression as in the following statement: SELECT sal + ‘10’ FROM emp; Example 2 When a condition compares a character value and a NUMBER value, Oracle implicitly converts the character value to a NUMBER value, rather than converting the NUMBER value to a character value. 43
  • 44. ORACLE In the following statement, Oracle implicitly converts ‘7936’ to 7936: SELECT ename FROM emp WHERE empno = ‘7936’; Example 3 In the following statement, Oracle implicitly converts ’12-MAR-1993' to a DATE value using the default date format ‘DD-MON-YYYY’: SELECT ename FROM emp WHERE hiredate = ’12-MAR-1993'; Example 4 In the following statement, Oracle implicitly converts the text literal ‘AAAAZ8AABAAABvlAAA’ to a ROWID value: SELECT ename FROM emp WHERE ROWID = ‘AAAAZ8AABAAABvlAAA’; Explicit Data Conversion You can also explicitly specify datatype conversions using SQL conversion functions. Table 2-8 shows SQL functions that explicitly convert a value from one datatype to another Table 2-8 SQL Functions for Datatype Conversion TO: FROM: CHAR NUMBER DATE RAW ROWID CHAR - TO_NUMBER TO_DATE HEXTORAW CHARTOROWID NUMBER TO_CHAR - TO_DATE (number, 'J') DATE TO_CHAR TO_CHAR - (date,'J') RAW RAWTOHEX - ROWID ROWIDTOCHAR - Implicit vs. Explicit Data Conversion Oracle recommends that you specify explicit conversions rather than rely on implicit or automatic conversions for these reasons: • SQL statements are easier to understand when you use explicit datatype conversions functions. • Automatic datatype conversion can have a negative impact on performance, especially if the datatype of a column value is converted to that of a constant rather than the other way around. 44
  • 45. ORACLE • Implicit conversion depends on the context in which it occurs and may not work the same way in every case. • Algorithms for implicit conversion are subject to change across software releases and among Oracle products. Behavior of explicit conversions is more predictable. Nulls If a column in a row has no value, then column is said to be null, or to contain a null. Nulls can appear in columns of any datatype that are not restricted by NOT NULL or PRIMARY KEY integrity constraints. Use a null when the actual value is not known or when a value would not be meaningful. Do not use null to represent a value of zero, because they are not equivalent. (Oracle currently treats a character value with a length of zero as null. However, this may not continue to be true in future releases, and Oracle recommends that you do not treat empty strings the same as NULLs.) Any arithmetic expression containing a null always evaluates to null. For example, null added to 10 is null. In fact, all operators (except concatenation) return null when given a null operand. Nulls in SQL Functions All scalar functions (except NVL and TRANSLATE) return null when given a null argument. The NVL function can be used to return a value when a null occurs. For example, the expression NVL(COMM,0) returns 0 if COMM is null or the value of COMM if it is not null. Most group functions ignore nulls. For example, consider a query that averages the five values 1000, null, null, null, and 2000. Such a query ignores the nulls and calculates the average to be (1000+2000)/ 2 = 1500. Nulls with Comparison Operators To test for nulls, use only the comparison operators IS NULL and IS NOT NULL. If you use any other operator with nulls and the result depends on the value of the null, the result is UNKNOWN. Because null represents a lack of data, a null cannot be equal or unequal to any value or to another null. However, note that Oracle considers two nulls to be equal when evaluating a DECODE expression. Oracle also considers two nulls to be equal if they appear in compound keys. That is, Oracle considers identical two compound keys containing nulls if all the non-null components of the keys are equal. Nulls in Conditions A condition that evaluates to UNKNOWN acts almost like FALSE. For example, a SELECT statement with a condition in the WHERE clause that evaluates to UNKNOWN returns no rows. However, a condition evaluating to UNKNOWN differs from FALSE in that further operations on an UNKNOWN condition evaluation will evaluate to UNKNOWN. Thus, NOT FALSE evaluates to TRUE, but NOT UNKNOWN evaluates to UNKNOWN. 45
  • 46. ORACLE Table 2-9 shows examples of various evaluations involving nulls in conditions. If the conditions evaluating to UNKNOWN were used in a WHERE clause of a SELECT statement, then no rows would be returned for that query. Table 2-9: Conditions containing Nulls If A is: Condition Evaluates to: 10 a IS NULL FALSE 10 a IS NOT NULL TRUE NULL a IS NULL TRUE NULL a IS NOT NULL FALSE 10 a = NULL UNKNOWN 10 a != NULL UNKNOWN NULL a = NULL UNKNOWN NULL a != NULL UNKNOWN NULL a = 10 UNKNOWN NULL a != 10 UNKNOWN PSEUDOCOLUMNS A pseudocolumn behaves like a table column, but is not actually stored in the table. You can select from pseudocolumns, but you cannot insert, update, or delete their values. This section describes these pseudocolumns: • CURRVAL and NEXTVAL • LEVEL • ROWID • ROWNUM CURRVAL and NEXTVAL A sequence is a schema object that can generate unique sequential values. These values are often used for primary and unique keys. You can refer to sequence values in SQL statements with these pseudocolumns: CURRVAL returns the current value of a sequence. NEXTVAL increments the sequence and returns the next value. You must qualify CURRVAL and NEXTVAL with the name of the sequence: sequence.CURRVAL sequence.NEXTVAL To refer to the current or next value of a sequence in the schema of another user, you must have been granted either SELECT object privilege on the sequence or SELECT ANY SEQUENCE system privi- lege, and you must qualify the sequence with the schema containing it: 46
  • 47. ORACLE schema.sequence.CURRVAL schema.sequence.NEXTVAL To refer to the value of a sequence on a remote database, you must qualify the sequence with a complete or partial name of a database link: schema.sequence.CURRVAL@dblink schema.sequence.NEXTVAL@dblink Where to Use Sequence Values You can use CURRVAL and NEXTVAL in these places: • the SELECT list of a SELECT statement that is not contained in a subquery, snapshot, or view • the SELECT list of a subquery in an INSERT statement • the VALUES clause of an INSERT statement • the SET clause of an UPDATE statement You cannot use CURRVAL and NEXTVAL in these places: • a subquery in a DELETE, SELECT, or UPDATE statement • a view’s query or snapshot’s query • a SELECT statement with the DISTINCT operator • a SELECT statement with a GROUP BY or ORDER BY clause • a SELECT statement that is combined with another SELECT statement with the UNION, IN- TERSECT, or MINUS set operator • the WHERE clause of a SELECT statement • DEFAULT value of a column in a CREATE TABLE or ALTER TABLE statement • the condition of a CHECK constraint Also, within a single SQL statement that uses CURVAL or NEXTVAL, all referenced LONG columns, updated tables, and locked tables must be located on the same database. How to Use Sequence Values When you create a sequence, you can define its initial value and the increment between its values. The first reference to NEXTVAL returns the sequence’s initial value. Subsequent references to NEXTVAL increment the sequence value by the defined increment and return the new value. Any reference to CURRVAL always returns the sequence’s current value, which is the value returned by the last refer- ence to NEXTVAL. Note that before you use CURRVAL for a sequence in your session, you must first initialize the sequence with NEXTVAL. Within a single SQL statement, Oracle will increment the sequence only once. If a statement contains more than one reference to NEXTVAL for a sequence, Oracle increments the sequence once and re- turns the same value for all occurrences of NEXTVAL. If a statement contains references to both CURRVAL and NEXTVAL, Oracle increments the sequence and returns the same value for both CURRVAL and NEXTVAL regardless of their order within the statement. A sequence can be accessed by many users concurrently with no waiting or locking. 47
  • 48. ORACLE Example 1 This example selects the current value of the employee sequence: SELECT empseq.currval FROM DUAL; Example 2 This example increments the employee sequence and uses its value for a new employee inserted into the employee table: INSERT INTO emp VALUES (empseq.nextval, ‘LEWIS’, ‘CLERK’, 7902, SYSDATE, 1200, NULL, 20); Example 3 This example adds a new order with the next order number to the master order table. It then adds suborders with this number to the detail order table: INSERT INTO master_order(orderno, customer, orderdate) VALUES (orderseq.nextval, ‘Al’’s Auto Shop’, SYSDATE); INSERT INTO detail_order (orderno, part, quantity) VALUES (orderseq.currval, ‘SPARKPLUG’, 4); INSERT INTO detail_order (orderno, part, quantity) VALUES (orderseq.currval, ‘FUEL PUMP’, 1); INSERT INTO detail_order (orderno, part, quantity) VALUES (orderseq.currval, ‘TAILPIPE’, 2); LEVEL For each row returned by a hierarchical query, the LEVEL pseudocolumn returns 1 for a root node, 2 for a child of a root, and so on. A root node is the highest node within an inverted tree. A child node is any nonroot node. A parent node is any node that has children. A leaf node is any node without children. Figure 2-1 shows the nodes of an inverted tree with their LEVEL values Fig. 2-1 : Hierarchical Tree To define a hierarchical relationship in a query, you must use the START WITH and CONNECT BY clauses. 48
  • 49. ORACLE ROWID For each row in the database, the ROWID pseudocolumn returns a row’s address. ROWID values contain information necessary to locate a row: • the data object number of the object • which data block in the datafile • which row in the data block (first row is 0) • which datafile (first file is 1). The file number is relative to the tablespace. Usually, a ROWID value uniquely identifies a row in the database. However, rows in different tables that are stored together in the same cluster can have the same ROWID. Values of the ROWID pseudocolumn have the datatype ROWID. ROWID values have several important uses: • They are the fastest way to access a single row. • They can show you how a table’s rows are stored. • They are unique identifiers for rows in a table. You should not use ROWID as a table’s primary key. If you delete and reinsert a row with the Import and Export utilities, for example, its ROWID may change. If you delete a row, Oracle may reassign its ROWID to a new row inserted later. Although you can use the ROWID pseudocolumn in the SELECT and WHERE clauses of a query, these pseudocolumn values are not actually stored in the database. You cannot insert, update, or delete a value of the ROWID pseudocolumn. Example This statement selects the address of all rows that contain data for employees in department 20: SELECT ROWID, ename FROM emp WHERE deptno = 20; ROWID ENAME ————————— ———-—- AAAAfSAABAAAClaAAA SMITH AAAAfSAABAAAClaAAD JONES AAAAfSAABAAAClaAAH SCOTT AAAAfSAABAAAClaAAK ADAMS AAAAfSAABAAAClaAAM FORD ROWNUM For each row returned by a query, the ROWNUM pseudocolumn returns a number indicating the order in which Oracle selects the row from a table or set of joined rows. The first row selected has a ROWNUM of 1, the second has 2, and so on. 49
  • 50. ORACLE You can use ROWNUM to limit the number of rows returned by a query, as in this example: SELECT * FROM emp WHERE ROWNUM < 10; Note that conditions testing for ROWNUM values greater than a positive integer are always false. For example, this query returns no rows: SELECT * FROM emp WHERE ROWNUM > 1; The first row fetched is assigned a ROWNUM of 1 and makes the condition false. The second row to be fetched is now the first row and is also assigned a ROWNUM of 1 and makes the condition false. All rows subsequently fail to satisfy the condition, so no rows are returned. You can also use ROWNUM to assign unique values to each row of a table, as in this example: UPDATE tabx SET col1 = ROWNUM; Oracle assigns a ROWNUM value to each row as it is retrieved, before rows are sorted for an ORDER BY clause, so an ORDER BY clause normally does not affect the ROWNUM of each row. However, if an ORDER BY clause causes Oracle to use an index to access the data, Oracle may retrieve the rows in a different order than without the index, so the ROWNUMs may be different than they would be without the ORDER BY clause. 50
  • 51. ORACLE SQL - AN INTRODUCTION COMPETENCY OBJECTIVES This chapter covers the following topics v SQL Operators v SQL Functions v SQL Queries 51