Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
CONTENTS
• Large databases and Space management: Oracle supports the largest of the
databases, potentially hundreds of gigabytes in size. To make efficient use of
expensive hardware devices, it allows full control of space usage.
• Many concurrent database users: Oracle supports large number of concurrent users
executing a variety of database applications operating on the same data. It minimizes
data contention and guarantees data concurrency.
• High availability of Oracle database: At some sites, Oracle works 24 hours per day
with no downtime to limit database throughput. Normal system operations such as
database backup and partial computer system failures do not interrupt database use.
• Openness, industry standards: Oracle adheres to industry accepted standards for the
data access language, operating systems, user interfaces, and network communication
protocols.
• Database enforced integrity: Oracle enforces data integrity, “business rules” that
dictate the standards for acceptable data. As a result, the costs of coding and
managing checks in many database applications are eliminated.
• Portability: Oracle software is ported to work under different operating systems and
is the same on all systems. Applications developed for Oracle can be ported to any
operating system with little or no modification.
• Replicated Environments: Oracle Software lets you replicate groups of tables and
their supporting objects to multiple sites. Oracle supports replication of both data- and
schema-level changes to these sites.
Data Access
Applications
Tools
SQL
Oracle
Data
O/S
Server
SQL*PLUS
PL/SQL
SQL
• Structured Query Language
• Non-procedural language
- Processes sets of records rather than just one at a time
- Provides automatic navigation to the data
• Unified language: provides commands for--
- querying data (DML)
- inserting, updating and deleting rows in a table (DML)
- creating, replacing, altering and dropping objects (DDL)
- controlling access to the database and its objects (DCL)
- guaranteeing database consistency and integrity
• Common language for all relational databases
Embedded SQL
• Refers to the use of standard SQL commands embedded within a procedural language
• Embedded SQL is supported by the Oracle pre-compilers
• The Oracle pre-compilers interpret embedded SQL statements and translate them into
statements that can be understood by procedural language compilers
• Pre-compilers
- Pro*C/C++
- Pro*COBOL
- Pro*FORTRAN
- Pro*PASCAL
- Pro*PL/I
SQL*PLUS
• SQL*PLUS can be used in conjunction with the SQL database language and its
procedural language extensions, PL/SQL
• SQL*PLUS allows you to
- enter, edit, store, retrieve and run SQL commands and PL/SQL blocks
- format, perform calculations on, store, and print query results in the form of
reports
- list column definitions for any table
- access and copy data between SQL databases
- send messages to and accept responses from an end user
Oracle Tools
• Allow users to develop applications that automatically run on a variety of operating
environments and automatically take on the native look-and-feel of that operating
environment.
• Oracle Tools include :
- Oracle Forms
- Oracle Reports
- Oracle Graphics
PL/SQL
• PL/SQL is Oracle Corporation's procedural language extension to SQL, the standard
data access language for relational databases.
• With PL/SQL, you can use SQL statements to manipulate Oracle data and flow-of-
control statements to process the data..
• You can also declare constants and variables, define procedures and functions, and
trap runtime errors.
• Thus, PL/SQL combines the data manipulating power of SQL with the data
processing power of procedural languages.
The Oracle database consists of both logical database structure and the physical
database structure.
Tablespaces
A database is divided into logical storage units called tablespaces.
A tablespace can be online or offline.
Database
DATA1.O DATA3.O
DATA2.O
A tablespace is used to logically group data together. For example, you can have a
tablespace for accounting and a separate tablespace for purchasing. Segmenting groups
into different tablespaces simplifies the administration of these groups. Tablespaces are
made up of one or more datafiles. By using more than one datafile per tablespace, you
can spread the data over many different disks to distribute the I/O load and improve
performance.
As part of the process of creating the database, Oracle automatically creates the SYSTEM
tablespace. You can create additional separate tablespace for user data. The SYSTEM
tablespace is where the data dictionary is kept.
Schema Objects
- Tables: A table is the basic unit of data storage in an Oracle database. The tables hold
all of the user-accessible data.
Nested Tables: In the Oracle object-relational database, you can create a table with a
column whose datatype is another table. That is, tables can be nested within other
tables as values in a column. The Oracle Server stores nested table data "out of line"
from the rows of the parent table, using a store table which is associated with the
nested table column. The parent row contains a unique set identifier value associated
with a nested table instance.
- Views: A view is a custom-tailored presentation of the data in one or more tables (or
other views). A view can also be thought as a “stored query”.
- Sequences: A sequence generates a serial list of unique numbers for numeric columns
of a database’s tables.
- Indexes, Clusters, and Hash Clusters: Indexes, Clusters, and Hash Clusters are
optional structures associated with tables, which can be created to increase the
performance of data retrieval.
Data Blocks
• At the finest level of granularity, an Oracle database’s data is stored in data blocks.
• One data block corresponds to a specific number of bytes of physical database space
on disk.
• A data block size is specified for each Oracle database when the database is created.
Extents
• Extent is the next level of logical database space.
• Extent is a specific number of contiguous data blocks, obtained in a single allocation,
used to store a specific type of information.
Segments
• Segment is the level of logical database storage above an extent.
• Segment is a set of extents allocated for a certain logical structure.
• Types of segments :
Data Segment: Each non-clustered table has a data segment. All of the table’s data is
stored in the extents of its data segment. Each cluster has a data segment. The data of
every table in the cluster is stored in the cluster’s data segment.
Index Segment: Each index has an index segment that stores all of its data.
Rollback Segment: One or more rollback segments are created by the DBA for a
database to temporarily store “undo” information. This information is used :
• to generate read-consistent database information
• during database recovery
• to rollback uncommitted transactions for users
Temporary Segment: These are created by Oracle when a SQL statement needs a
temporary work area to complete execution. When the statement finishes execution,
the temporary segment’s extents are returned to the system.
Oracle allocates space for all types of segments in extents. Therefore, when the
existing extents of a segment are full, Oracle allocates another extent for that segment
as needed.
Segment
112 K
Extent Extent
28 K 84 K
2k 2k 2k 2k
2k 2k 2k 2k
2k 2k 2k 2k
2k 2k 2k 2k
2k 2k 2k 2k
2k 2k 2k 2k
2k 2k 2k 2k
Data Blocks
An Oracle Instance
User
Use Use Use Use .. Process
es
An Oracle instance has two types of processes: user processes and Oracle processes.
• A user process executes the code of an application program (such as an Oracle Forms
application) or an Oracle Tool (such as 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.
If the user and server processes are on different computers of a network or if the user
processes connect to shared server processes through dispatcher processes, the user
process and server process communicate using Net8. Dispatchers are optional
background processes, present only when a multi-threaded server configuration is used.
Net8 is Oracle's interface to standard communications protocols that allows for the proper
transmission of data between computers.
Oracle uses shared memory for several purposes, including caching of data and indexes
as well as storing shared program code. This shared memory is used for several functions
and is broken into various pieces, or memory structures. The basic memory structures
associated with Oracle are
- System Global Area ( SGA )
- Program Global Area ( PGA )
• It is a shared memory region containing data and control information for one Oracle
instance.
• Oracle allocates the SGA when an instance starts and deallocates it when the instance
shuts down.
• Each instance has its own SGA.
• SGA is divided into memory structures :
- Database Buffer Cache
- Redo Log Buffer
- Shared Pool
- Statement Handles or Cursors
• Shared Pool :
- Contains shared memory constructs such as shared SQL areas.
- Shared SQL area is used to process every unique SQL statement issued.
- Shared SQL area contains parse tree and execution plan for the SQL statement. If
multiple applications issue the same SQL statement, the shared SQL area can be
accessed by each of them to reduce the amount of memory needed and to reduce
the processing time used for parsing and execution planning.
Offlin
User Shared Dedicat e
Proces Server ed Storag
Process Server
CKPT ARCH
DBW
D000 LGW
User
Proces Contro
l Files
Redo
Log
Processes
• A process normally has its own private memory area in which it runs.
• Oracle Processes :
- These are called by other processes to perform function on behalf of the invoking
process. Oracle processes can be split into two groups : server processes (which
perform functions for the invoking process) and background processes (which
perform functions on behalf of the entire RDBMS).
• These are in charge of communicating with Oracle to carry out requests of the
associated user process.
Eg. If a user queries data not in SGA currently, server process fetches data into SGA
from datafiles.
• Oracle can be configured to vary the number of user processes per server process. In a
dedicated server configuration, a server process handles requests for a single user
process. A multi-threaded server configuration allows many user processes to share a
small number of server processes, minimizing the number of server processes and
maximizing the utilization of available system resources.
Dispatcher Process
Oracle Server
Code
Request Response Queues
Queues
SGA
- A Network Listener Process (of Net8), that waits for incoming connection request
from a user process and connects it to dispatcher, so that the shared process can be
used; if the user process requests a dedicated server, listener process creates a
dedicated server process and connects the user process to it.
- One or more Dispatcher Processes that routes the user request to the next available
shared server process.
- One or more Shared Server processes.
Background Processes
• Background processes are the Oracle processes used to perform various tasks within
the RDBMS system. Oracle creates a set of background processes for each instance.
• Background Processes :
- DBWR
- LGWR
- CKPT
- SMON
- PMON
- ARCH
- RECO
- Dnnn
- LCKn
• Checkpoint ( CKPT ) :
At specific times, all modified database buffers in the system global area are written
to the datafiles by DBWR; this event is called a checkpoint. The Checkpoint process
is responsible for signaling DBWR at checkpoints and updating all the datafiles and
control files of the database to indicate the most recent checkpoint.
back online. SMON also coalesces free extents within the database to make free space
contiguous and easier to allocate.
• Archiver ( ARCH ) :
The archiver copies the online redo log files to archival storage when they are full.
ARCH is active only when a database's redo log is used in ARCHIVELOG mode.
• Recoverer ( RECO ) :
The recoverer is used to resolve distributed transactions that are pending due to a
network or system failure in a distributed database. At timed intervals, the local
RECO attempts to connect to remote databases and automatically complete the
commit or rollback of the local portion of any pending distributed transactions.
• Dispatcher ( Dnnn ) :
Dispatchers are optional background processes, present only when a multi-threaded
server configuration is used. At least one dispatcher process is created for every
communication protocol in use (D000, . . ., Dnnn). Each dispatcher process is
responsible for routing requests from connected user processes to available shared
server processes and returning the responses back to the appropriate user processes.
• Lock ( LCKn ) :
The lock processes (LCK0, . . ., LCK9) are used for inter-instance locking in the
Oracle Parallel Server
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 DBWR 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.
Introduction to Rollback Segments
Each database contains one or more rollback segments. A rollback segment records the
old values of data that were changed by each transaction (whether or not committed).
Rollback segments are used to provide read consistency, to roll back transactions, and to
recover the database.
performs the actual rollbacks of transactions that had been neither committed nor rolled
back at the time of the system crash.
When Rollback Information Is Required
For each rollback segment, Oracle maintains a transaction table—a list of all
transactions that use the associated rollback segment and the rollback entries for each
change performed by these transactions. Oracle uses the rollback entries in a rollback
segment to perform a transaction rollback and to create read-consistent results for
queries.
Rollback segments record the data prior to change for each transaction. For every
transaction, Oracle links each new change to the previous change. If you must roll back
the transaction, Oracle applies the changes in a chain to the data blocks in an order that
restores the data to its previous state. Similarly, when Oracle needs to provide a read-
consistent set of results for a query, it can use information in rollback segments to create
a set of data consistent with respect to a single point in time.
Transactions and Rollback Segments
Each time a user’s transaction begins, the transaction is assigned to a rollback segment in
one of two ways:
1. Oracle can assign a transaction automatically to the next available rollback
segment. The transaction assignment occurs when you issue the first DML or
DDL statement in the transaction. Oracle never assigns read-only transactions
(transactions that contain only queries) to a rollback segment, regardless of
whether the transaction begins with a SET TRANSACTION READ ONLY
statement.
2. An application can assign a transaction explicitly to a specific rollback segment.
At the start of a transaction, an application developer or user can specify a
particular rollback segment that Oracle should use when executing the
transaction. This lets the application developer or user select a large or small
rollback segment, as appropriate for the transaction.
For the duration of a transaction, the associated user process writes rollback information
only to the assigned rollback segment.
When you commit a transaction, Oracle releases the rollback information but does not
immediately destroy it. The information remains in the rollback segment to create read-
consistent views of pertinent data for queries that started before the transaction
committed. To guarantee that rollback data is available for as long as possible for such
views, Oracle writes the extents of rollback segments sequentially. When the last extent
of the rollback segment becomes full, Oracle continues writing rollback data by wrapping
around to the first extent in the segment. A long-running transaction (idle or active) can
require a new extent to be allocated for the rollback segment.
Read Consistency
Read-Only Transactions
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 guarantee data integrity while allowing maximum concurrent access to the data by
unlimited users.
Automatic Locking
Manual Locking
• Under some circumstances, a user may want to override default locking. Oracle
allows manual override 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.
Transactions and Data Concurrency
Oracle provides data concurrency and integrity between transactions using its locking
mechanisms. Because the locking mechanisms of Oracle are tied closely to transaction
control, application designers need only define transactions properly, and Oracle
automatically manages locking.
• Keep in mind that Oracle locking is fully automatic and requires no user action.
• Implicit locking occurs for all SQL statements so that database users never need
to lock any resource explicitly.
Oracle releases all locks acquired by the statements within a transaction when you either
commit or roll back the transaction. Oracle also releases locks acquired after a savepoint
when rolling back to the savepoint. However, only transactions not waiting for the
previously locked resources can acquire locks on the now available resources. Waiting
transactions will continue to wait until after the original transaction commits or rolls back
completely.
Data Lock Conversion Versus Lock Escalation
A transaction holds exclusive row locks for all rows inserted, updated, or deleted within
the transaction. Because row locks are acquired at the highest degree of restrictiveness,
no lock conversion is required or performed.
• Oracle automatically converts a table lock of lower restrictiveness to one of
higher restrictiveness as appropriate.
• For example, assume that a transaction uses a SELECT statement with the FOR
UPDATE clause to lock rows of a table. As a result, it acquires the exclusive row
locks and a row share table lock for the table. If the transaction later updates one
or more of the locked rows, the row share table lock is automatically converted to
a row exclusive table lock.
Lock escalation occurs when numerous locks are held at one level of granularity (for
example, rows) and a database raises the locks to a higher level of granularity (for
example, table).
• For example, if a single user locks many rows in a table, some databases
automatically escalate the user’s row locks to a single table. The number of locks
is reduced, but the restrictiveness of what is being locked is increased.
Oracle never escalates locks. Lock escalation greatly increases the likelihood of
deadlocks. Imagine the situation where the system is trying to escalate locks on behalf of
transaction T1 but cannot because of the locks held by transaction T2. A deadlock is
created if transaction T2 also requires lock escalation of the same data
before it can proceed.
Database Security
• Database security can be classified into two distinct categories: system security and
data security.
• System security includes the mechanisms that control the access and use of the
database at the system level. For example, system security includes:
- valid username/password combinations
- the amount of disk space available to the objects of a user
- the resource limits for a user
• Data security includes the mechanisms that control the access and use of the database
at the object level. For example, data security includes
- which users have access to a specific schema object and the specific types of
actions allowed for each user on the object (for example, user SCOTT can
issue SELECT and INSERT statements but not DELETE statements using the
EMP table)
- the actions, if any, that are audited for each schema object
Security Mechanisms
The Oracle Server provides discretionary access control, which is a means of restricting
access to information based on privileges.
Oracle manages database security using several different facilities:
• database users and schemas
• privileges
• roles
• storage settings and quotas
• profiles and resource limits
• auditing: statement, privilege, object
• The online redo log files are used in a cyclical fashion; for example, if two files
constitute the online redo log, the first file is filled, the second file is filled, the first
file is reused and filled, the second file is reused and filled, and so on. Each time a file
is filled, it is assigned a log sequence number to identify the set of redo entries.
• To avoid losing the database due to a single point of failure, Oracle can maintain
multiple sets of online redo log files. A multiplexed online redo log consists of copies
of online redo log files physically located on separate disks; changes made to one
member of the group are made to all members.
• If a disk that contains an online redo log file fails, other copies are still intact and
available to Oracle. System operation is not interrupted and the lost online redo log
files can be easily recovered using an intact copy.
• If the database's redo log is operated in NOARCHIVELOG mode, the database can
be completely recovered from instance failure, but not from a disk failure.
Additionally, the database can be backed up only while it is completely closed.
Because no archived redo log is created, no extra work is required by the database
administrator.
Control Files
• The control files of a database keep, among other things, information about the file
structure of the database and the current log sequence number being written by
LGWR. During normal recovery procedures, the information in a control file is used
to guide the automated progression of the recovery operation.
• Multiplexed Control Files: This feature is similar to the multiplexed redo log feature:
a number of identical control files may be maintained by Oracle, which updates all of
them simultaneously.
Rollback Segments
• Rollback segments record rollback information used by several functions of Oracle.
During database recovery, after all changes recorded in the redo log have been
applied, Oracle uses rollback segment information to undo any uncommitted
transactions. Because rollback segments are stored in the database buffers, this
important recovery information is automatically protected by the redo log.
Database Backups
• Whole Database Backups: A whole database backup is an operating system backup
of all datafiles, online redo log files, and the control file that constitutes an Oracle
database. Full backups are performed when the database is closed and unavailable for
use.
• Partial Backups: A partial backup is an operating system backup of part of a
database. The backup of an individual tablespace's datafiles or the backup of a control
file are examples of partial backups. Partial backups are useful only when the
database's redo log is operated in ARCHIVELOG mode.
To solve this situation, two separate steps are always used by Oracle during recovery
from an instance or media failure: rolling forward and rolling back.
Rolling Forward
• The first step of recovery is to roll forward, that is, reapply to the datafiles all of the
changes recorded in the redo log. Rolling forward proceeds through as many redo log
files as necessary to bring the datafiles forward to the required time.
• If all needed redo information is online, Oracle performs this recovery step
automatically when the database starts. After roll forward, the datafiles contain all
committed changes as well as any uncommitted changes that were recorded in the
redo log.
Rolling Back
• The roll forward is only half of recovery. After the roll forward, any changes that
were not committed must be undone. After the redo log files have been applied,
then the rollback segments are used to identify and undo transactions that were
never committed, yet were recorded in the redo log. This process is called rolling
back. Oracle completes this step automatically.
Replication
Table Replication
Distributed database systems often locally replicate remote tables that are frequently
queried by local users. By having copies of heavily accessed data on several nodes, the
distributed database does not need to send information across a network repeatedly, thus
helping to maximize the performance of the database application. Data can be replicated
using materialized views.
Materialized Views
• 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.
object type has a constructor method that makes a new object according to the
datatype's specification.
Introduction to Partitioning
• Partitioning addresses key issues in supporting very large tables and indexes by
letting you decompose them into smaller and more manageable pieces called
partitions.
• SQL queries and DML statements do not need to be modified in order to access
partitioned tables.
• However, once partitions are defined, DDL statements can access and manipulate
individuals partitions rather than entire tables or indexes.
• This is how partitioning can simplify the manageability of large database objects.
• Also, partitioning is entirely transparent to applications. Each partition of a table
or index must have the same logical attributes, such as column names, datatypes,
and constraints, but each partition can have separate physical attributes such as
pctfree, pctused, and tablespaces.
• Partitioning is useful for many different types of applications, particularly
applications that manage large volumes of data. OLTP systems often benefit from
improvements in manageability and availability, while data warehousing systems
benefit from performance and manageability.
Partitioning offers these advantages:
• Partitioning enables data management operations such data loads, index creation
and rebuilding, and backup/recovery at the partition level, rather than on the entire
table. This results in significantly reduced times for these operations.
• Partitioning improves query performance. In many cases, the results of a query
can be achieved by accessing a subset of partitions, rather than the entire table.
For some queries, this technique (called partition pruning) can provide order-of-
magnitude gains in performance.
• Partitioning can significantly reduce the impact of scheduled downtime for
maintenance operations. Partition independence for partition maintenance
operations lets you perform concurrent maintenance operations on different
partitions of the same table or index. You can also run concurrent SELECT and
DML operations against partitions that are unaffected by maintenance operations.
• Partitioning increases the availability of mission-critical databases if critical tables
and indexes are divided into partitions to reduce the maintenance windows,
recovery times, and impact of failures.
• Partitioning can be implemented without requiring any modifications to your
applications.
For example, you could convert a nonpartitioned table to a partitioned table without
needing to modify any of the SELECT statements or DML statements which access that
table. You do not need to rewrite your application code to take advantage of partitioning.
Review Questions
6. The database structure which records all the transactions on tables is termed
________________________________________
8. The structures used to enhance the performance of Oracle by providing faster access
to data are ____________________________________________________________
9. The Oracle object which allows you to generate serial numbers is called a
_____________________________________
11. The database structure which stores the ‘meta-data’, which means
______________________________ is called _______________________________
12. The area in the SGA used to process SQL statements is called ___________________
14. The ARCH process is active only when the redo log operates in
_____________________________________________ mode.
17. When an update on the data occurs, the original data values changed by the update are
recorded in the database’s _____________________________ segments.
SQL
• Introductory Concepts
• Creating, Altering, and Dropping Tables
• Indexing, Clustering, and Sequences
• Changing Data: Inserting, Updating, and Deleting Data
• Querying Tables
• Views
• Controlling Transactions
Introductory Concepts
Topics
Database Objects
1. Schema Objects
A schema is a collection of logical structures of data, or schema objects. A schema is
owned by a database user and has the same name as that user. Each user owns a
single schema. Schema objects can be created and manipulated with SQL and include
the following types of objects:
• Clusters
• Database Links
• Database Triggers
• External Procedure Libraries
• Index-only Tables
• Indexes
• Object Tables
• Object Types
• Object Views
• Packages
• Sequences
• Snapshots
• Snapshot Logs
• Stored Functions
• Stored Procedures
• Synonyms
• Tables
• Views
2. Non-Schema Objects
Other types of objects are also stored in the database and can be created and
manipulated with SQL, but are not contained in a schema:
• directories
• profiles
• roles
• rollback segments
• tablespaces
• users
Tables and indexes can be partitioned. When partitioned, these schema objects consist of
a number of parts, called partitions, all of which have the same logical attributes. For
example, all partitions in a table share the same column and constraint definitions, and all
partitions in an index share the same index columns.
Partitions can be used as tables, providing users with a shortcut method of performing
some partition-level operations that would otherwise require using a WHERE clause
predicate.
Partition-level bulk operations, such as deleting all of the rows from a partition, restrict
the operation to one partition. These types of operations are easily expressed with the
partition-extended table name syntax. Trying to phrase the same operation with a
WHERE clause predicate can be cumbersome, especially when the range partitioning key
uses more than one column.
Table specification syntax has been extended for the following DML statements to allow
an optional partition specification for non-remote partitioned tables:
• DELETE
• INSERT
• LOCK TABLE
• SELECT
• UPDATE
Namespaces
A name must be unique across its namespace. Objects in the same namespace must have
different names. Each schema in the database has its own namespaces for the objects it
contains.
TABLES INDEXES
VIEWS
SEQUENCES CONSTRAINTS
PRIVATE SYNONYMS
CLUSTERS
STAND-ALONE PROCEDURES
STAND-ALONE STORED DATABASE TRIGGERS
FUNCTIONS
PRIVATE DATABASE
Datatypes
Character Datatypes:
Character datatypes are used to manipulate words and free-form text. These datatypes are
used to store character (alphanumeric) data in the database. 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. 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.
Number Datatype:
The NUMBER datatype is used to store zero, positive and negative fixed and floating
point numbers with magnitudes between 1.0 x 10-130 and 9.9...9 x 10125 (38 9s
followed by 88 0s) with 38 digits of precision.
You can specify a fixed point number using the form:
NUMBER(p,s)
You specify an integer using the form:
NUMBER (p)
You specify a floating point number using the form:
NUMBER
LONG Datatype:
You can use LONG columns to store long text strings.
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.
DATE Datatype:
The DATE datatype is used to store the date and time information. For each DATE value
the following information is stored:
• century
• year
• month
• day
• hour
• minute
• second
To specify a date value, you must convert a character or numeric value to a data value
with the TO_DATE function. The date function SYSDATE returns the current date and
time.
LOB value. DBMS_LOB package operations on LOBs are performed through these
locators.
LOBs are similar to LONG and LONG RAW types, but differ in the following ways:
• Multiple LOBs are allowed in a single row.
• LOBs can be attributes of a user-defined datatype (object).
• The LOB locator is stored in the table column, either with or without the actual LOB
value; BLOB and CLOB values can be stored in separate tablespaces and BFILE data
is stored in an external file on the server.
• When you access a LOB column, it is the locator which is returned.
• A LOB can be up to four gigabytes in size. BFILE maximum size is operating system
dependent, but cannot exceed four gigabytes.
• LOBs permit efficient, random, piece-wise access to and manipulation of data.
• You can define one or more LOB datatype columns in a table.
• You can define one or more LOB attributes in an object.
• You can declare LOB bind variables.
• You can select LOB columns and LOB attributes.
• You can insert a new row or update an existing row that contains one or more LOB
columns and/or an object with one or more LOB attributes. (You can set the internal
LOB value to NULL, empty, or replace the entire LOB with data. You can set the
BFILE to NULL or so that it points to a different file.)
• You can update a LOB row/column intersection or a LOB attribute with another LOB
row/column intersection or LOB attribute.
• You can delete a row containing a LOB column or LOB attribute and thereby also
delete the LOB value. Note that for BFILEs, the actual operating system file is not
deleted.
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.
Restricted ROWIDs: The Oracle8i Server incorporates an extended format for ROWIDs
to efficiently support partitioned tables and indexes and tablespace-relative data block
addresses (DBAs) without ambiguity.
Character values representing ROWIDs in Oracle and earlier releases are as follows:
block.row.file
Extended ROWIDs: The Oracle8i extended ROWID datatype stored in a user column
includes the data in the Oracle ROWID, plus a data object number. The data object
number is an identification number assigned to every database segment. You can retrieve
the data object number from data dictionary views USER_OBJECTS, DBA_OBJECTS,
and ALL_OBJECTS.
User-Defined Types
User-defined datatypes use Oracle built-in datatypes and other user-defined datatypes as
the building blocks of types that model the structure and behavior of data in applications.
Object Types:
Object types are abstractions of the real-world entities-for example, purchase orders-that
application programs deal with. An object type is a schema object with three kinds of
components:
• A name, which serves to identify the object type uniquely within that schema.
• Attributes, which are built-in types or other user-defined types. Attributes model the
structure 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
operations the application can perform on the real world entity.
Varrays
An array is an ordered set of data elements. All elements of a given array are of the same
datatype. Each element has an index, which is a number corresponding to the element's
position in the array.
Nested Tables:
A nested table is like an object table without the object identifiers. It has a single column,
and the type of that column is a built-in type or an object type. If an object type, the table
can also be viewed as a multi-column table, with a column for each attribute of the object
type.
When a nested table appears as the type of a column in a relational table or as an attribute
of the underlying object type of an object table, Oracle stores all of the nested table data
in a single table, which it associates with the enclosing relational or object table.
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.
• Oracle currently treats a character value with a length of zero as null. However, this
may not continue to be true in future versions of Oracle.
• Do not use null to represent a value of zero, because they are not equivalent. 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, only use 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.
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. The
Pseudocolumns supported are:
• CURRVAL and NEXTVAL
• LEVEL
• ROWID
• ROWNUM
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 data file
• which row in the data block (first row is 0)
• which data file (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.
Example :
SELECT ROWID, ename
FROM emp
WHERE deptno = 20
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.
• You can use ROWNUM to limit the number of rows returned by a query, as in this
example:
SELECT *
FROM emp
WHERE ROWNUM < 10
• 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 differ than without the ORDER BY
clause.
• 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 :
CREATE SEQUENCE cust_seq;
SELECT cust_seq.NEXTVAL FROM dual;
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 non-root node. A parent node is any node
that has children. A leaf node is any node without children.
Example :
Family Parent Child
A A B
A C
B D
B C B E
C F
D E F G C G
G H
H I J G I
G J
Output:
Parent Child Level
A B 1
B D 2
B E 2
A C 1
C F 2
C G 2
G H 3
G I 3
G J 3
Example :
In the emp table, to find the staff members at successively lower tiers in the organization :
SELECT PRIOR ename || ‘ manages ‘ || ename || ‘ on tier’
|| TO_CHAR(LEVEL – 1)
FROM emp
START WITH empno = 7839
CONNECT BY PRIOR empno = mgr;
• Creating a Table
• Constraints in CREATE TABLE
• Dropping a Table
• Altering a Table
• Sample Tables
• Syntax
CREATE TABLE table
({column datatype [DEFAULT expr]
[column_constraint | table_constraint]}
[,{column datatype [DEFAULT expr]
[column_constraint | table_constraint]}]...)
[CLUSTER cluster (column [, column] ...)]
[AS query]
• Constraints limit the values entered into the columns of the table
• There are two ways to specify constraints
- As part of the column definition: a column constraint
- At the end of the CREATE TABLE statement: a table constraint
Types Of Constraints:
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
• The NOT NULL constraint specifies that a column cannot contain nulls. To satisfy
this constraint, every row in the table must contain a value for the column.
• A unique key column cannot be of datatype LONG or LONG RAW. You cannot
designate the same column or combination of columns as both a unique key and a
primary key or as both a unique key and a cluster key. However, you can designate
the same column or combination of columns as both a unique key and a foreign key.
• No primary key value can appear in more than one row in the table.
• A primary key column cannot be of datatype LONG or LONG RAW. You cannot
designate the same column or combination of columns as both a primary key and a
unique key or as both a primary key and a cluster key. However, you can designate
the same column or combination of columns as both a primary key and a foreign key.
CHECK Constraints
• The CHECK constraint explicitly defines a condition. To satisfy the constraint, each
row in the table must make the condition either TRUE or unknown (due to a null).
For information on conditions, see the syntax description of condition. The condition
of a CHECK constraint can refer to any column in the table, but it cannot refer to
columns of other tables.
); /* table constraint */
• The foreign key and the referenced key can be in the same table. In this case, the
parent and child tables are the same.
• Before you define a referential integrity constraint in the child table, the referenced
UNIQUE or PRIMARY KEY constraint on the parent table must already be defined.
• DROP TABLE is used to remove a table and all its data from the database
• Syntax:
DROP TABLE table_name CASCADE CONSTRAINTS;
Examples:
DROP TABLE emp;
DROP TABLE dept CASCADE CONSTRAINTS;
Altering a table
• You can alter the definition of a table in one of the following ways:
- adding a column
- adding an integrity constraint
- redefining a column (datatype, size, default value)
- dropping an integrity constraint or trigger
Examples
ALTER TABLE emp
ADD (grade CHAR(1) NOT NULL);
• ADD allows you to add a new column to the end of an existing table, or add a
constraint to the table’s definition
• MODIFY changes an existing column, with some restrictions:
• You may change the type of column or decrease its size only if every row for the
column is NULL
• A NOT NULL column may be added to a table with no rows
• An existing column can be modified to NOT NULL only if it has a non-NULL
value in every row
• Increasing the length of a NOT NULL column without specifying NULL will
leave it NOT NULL
• Views that reference a table with SELECT * FROM … will not work after a
column has been added to the table unless they are dropped and recreated
You can define a NOT NULL constraint on an existing column only if the column
contains no nulls.
DROP clause
• To remove an integrity constraint or trigger from the database.
• The DROP clause can appear in an ALTER TABLE statement.
• You can drop an integrity constraint by naming it in a DROP clause of an ALTER
TABLE statement. When you drop an integrity constraint, Oracle stops enforcing the
integrity constraint and removes it from the data dictionary.
• You cannot drop a unique or primary key that is part of a referential integrity
constraint without also dropping the foreign key. You can drop the referenced key
and the foreign key together by specifying the referenced key with the CASCADE
option in the DROP clause.
Examples
ALTER TABLE emp
ADD (thriftplan NUMBER(7,2),
loancode CHAR(1) NOT NULL);
Sample Tables
EMP Table
DEPT Table
Review Questions
3. If you are defining a referential integrity constraint in a child table, the corresponding
column in the parent table should have ____________________________________
constraint already.
4. You can drop a table which is referenced by a foreign key in some other table, by
using _____________________________ clause in the DROP TABLE command.
5. When you drop a table, the table’s indexes will not be dropped automatically. (T / F)
7. You can delete a column from a table using the ALTER TABLE command. (T / F)
Exercises
Customers Table
Orders Table
Salespeople Table
• SNUM is the primary key
• SNAME should not be null
• COMM should always be less than 1
Customers Table
• CNUM is the primary key
• CNAME should not be null
• SNUM is the foreign key
Orders Table
• ONUM is the primary key
• CNUM is the foreign key
• SNUM is the foreign key
• AMT should not be greater than or equal to 10000
• Indexes
• Reverse Key Indexes
• Bitmap Indexes
• Index Organized Tables
• Clusters
• Sequences
Indexing and clustering are two methods of enhancing performance used by Oracle by
providing faster access to the data.
Indexes
A UNIQUE index guarantees that each indexed row is unique on the values of the
index columns
• When you create an index, Oracle fetches and sorts the columns to be indexed, and
stores the ROWID along with the index value for each row. Then Oracle loads the
index from the bottom up.
Oracle sorts the EMP table on the ENAME column. It then loads the index with
the ENAME and corresponding ROWID values in this sorted order. When it uses
the index, Oracle does a quick search through the sorted ENAME values and then
uses the associated ROWID values to locate the rows having the sought ENAME
value.
• Some columns are strong candidates for indexing. Columns with one or more of the
following characteristics are candidates for indexing:
- Values are relatively unique in the column.
- There is a wide range of values.
- The column contains many nulls, but queries often select all rows having a value.
• Columns with the following characteristics are less suitable for indexing:
- The column has few distinct values (for example, a column for the sex of
employees).
- There are many nulls in the column and you do not search on the non-null values.
• ORACLE itself creates indexes at the time of table creation if a table definition
contains a PRIMARY key or UNIQUE constraint
• Internally, Oracle uses B*Tree indexes that are balanced to equalize access times to
any row.
ADAMS
ALLEN
JAMES
JONES
<KING
KING
KING
MARTIN
KING MILLER
MILLER SCOTT
TURNER SMITH
TURNER
WARD
Creating a reverse key index, compared to a standard index, reverses the bytes of each
column indexed (except the rowid) while keeping the column order. Such an arrangement
can help avoid performance degradation in indexes in an Oracle Parallel Server
environment where modifications to the index are concentrated on a small set of leaf
blocks. By reversing the keys of the index, the insertions become distributed across all
leaf keys in the index.
Example:
• Creating a reverse key index:
CREATE INDEX i ON t (a,b,c) REVERSE;
• You can specify the keyword NOREVERSE to REBUILD a reverse-key index into
one that is not reverse keyed:
ALTER INDEX i REBUILD NOREVERSE;
Bitmap Indexes
• Oracle provides five indexing schemes: B*-tree indexes (currently the most
common), B*-tree cluster indexes, hash cluster indexes, reverse key indexes, and
bitmap indexes. These indexing schemes provide complementary performance
functionality.
• The purpose of an index is to provide pointers to the rows in a table that contain a
given key value.
• In a regular index, this is achieved by storing a list of rowids for each key
corresponding to the rows with that key value. (The Oracle Server stores each key
value repeatedly with each stored rowid.)
• In a bitmap index, a bitmap for each key value is used instead of a list of rowids.
Each bit in the bitmap corresponds to a possible rowid, and if the bit is set, it
means that the row with the corresponding rowid contains the key value.
A mapping function converts the bit position to an actual rowid, so the bitmap
index provides the same functionality as a regular index even though it uses a
different representation internally. If the number of different key values is small,
bitmap indexes are very space efficient.
• Bitmap indexes are not suitable for OLTP applications with large numbers of
concurrent transactions modifying the data. These indexes are primarily intended for
decision support (DSS) in data warehousing applications where users typically query
the data rather than update it.
• Cardinality: The advantages of using bitmap indexes are greatest for low cardinality
columns: that is, columns in which the number of distinct values is small compared to
the number of rows in the table. If the values in a column are repeated more than a
hundred times, the column is a candidate for a bitmap index.
Note: B*-tree indexes are most effective for high-cardinality data: that is, data with
many possible values, such as CUSTOMER_NAME or PHONE_NUMBER.
Table: Bitmap index for the REGION column. It consists of three separate bitmaps, one
for each region.
Like other indexes, you can create bitmap indexes on partitioned tables. The only
restriction is that bitmap indexes must be local to the partitioned table -- they cannot be
global indexes.
Index-Organized Tables
• An index-organized table differs from a regular table in that the data for the table is
held in its associated index. Changes to the table data, such as adding new rows,
updating rows, or deleting rows, result only in updating the index.
• The index-organized table is like a regular table with an index on one or more of its
columns, but instead of maintaining two separate storages for the table and the B*-
tree index, the database system only maintains a single B*-tree index which contains
both the encoded key value and the associated column values for the corresponding
row. Rather than having row ROWID as the second element of the index entry, the
actual data row is stored in the B*-tree index.
• Applications manipulate the index-organized table just like a regular table, using SQL
statements. However, the database system performs all operations by manipulating
the corresponding B*-tree index.
Example:
CREATE TABLE docindex
( token char(20),
doc_oid integer,
token_frequency smallint,
token_occurrence_data varchar(512),
CONSTRAINT pk_docindex PRIMARY KEY (token, doc_oid))
ORGANIZATION INDEX TABLESPACE text_collection
PCTTHRESHOLD 20
OVERFLOW TABLESPACE text_collection_overflow;
have a row identity (ROWID). Thus, index-organized table does not support implicit
ROWID column and hence you cannot perform ROWID based-retrieval on index-
organized tables.
Examples:
INSERT INTO docindex VALUES (`Gypsy',234,1,'17');
SELECT * FROM docindex;
UPDATE docindex SET doc_oid=237 WHERE token = `Gypsy';
DELETE FROM docindex WHERE token = `Gypsy';
Clusters
• Clusters are an optional method of storing table data. A cluster is a group of tables
that share the same data blocks because they share common columns and are often
used together.
• Because clusters store related rows of different tables together in the same data
blocks, two primary benefits are achieved when clusters are properly used:
- Disk I/O is reduced and access time improves for joins of clustered tables.
- In a cluster, a cluster key value (that is, the related value) is only stored once, no
matter how many rows of different tables contain the value. Therefore, less
storage may be required to store related table data in a cluster than is necessary in
non-clustered table format.
• Clustered tables must have a common column (or group of columns) called the
cluster key.
• Once you create a cluster, tables can be created in the cluster. However, before you
can insert any rows into the clustered tables, you must create a cluster index. The use
of clusters does not affect the creation of additional indexes on the clustered tables;
you can create and drop them as usual.
• After a cluster is created, this cluster definition is specified in the CLUSTER clause
of the CREATE TABLE command
• Syntax:
CREATE CLUSTER cluster (column datatype
[, column datatype]...)
[INDEX|[HASH IS column] HASHKEYS integer];
You must create a cluster index before you can execute any DML statements against the
clustered tables.
Example: Clustering
Note: A cluster index cannot be unique. Furthermore, Oracle is not guaranteed to enforce
uniqueness of columns in the cluster key if they have UNIQUE or PRIMARY KEY
constraints.
20 DNAME LOC
ADMIN NEW YORK
EMPNO ENAME …
932 KEHR … DEPT Table
1139 WILSON …
1277 NORMAN … DEPTNO DNAME LOC .
10 SALES BOSTON
20` ADMIN NEW YORK
• When you drop a cluster, the tables within the cluster and the corresponding cluster
index are dropped; all extents belonging to both the cluster's data segment and the
index segment of the cluster index are returned to the containing tablespace and
become available for other segments within the tablespace.
• You can individually drop clustered tables without affecting the table's cluster, other
clustered tables, or the cluster index.
• You can drop a cluster index without affecting the cluster or its clustered tables.
However, you cannot use a clustered table if it does not have a cluster index.
• To drop a cluster that contains no tables, as well as its cluster index, if present:
• If the cluster contains one or more clustered tables and you intend to drop the tables
as well, add the INCLUDING TABLES option of the DROP CLUSTER command,
as in
DROP CLUSTER emp_dept INCLUDING TABLES;
If you do not include the INCLUDING TABLES option, and the cluster contains
tables, an error is returned.
• If one or more tables in a cluster contain primary or unique keys that are referenced
by FOREIGN KEY constraints of tables outside the cluster, you cannot drop the
cluster unless you also drop the dependent FOREIGN KEY constraints. Use the
CASCADE CONSTRAINTS option of the DROP CLUSTER command, as in
Hash Clusters:
• A hash cluster is used to store individual tables or a group of clustered tables that are
static and often queried by equality queries. Once you create a hash cluster, you can
create tables.
• Hashing is an optional way of storing table data to improve the performance of data
retrieval. To use hashing, create a hash cluster and load tables into the cluster. Oracle
physically stores the rows of a table in a hash cluster and retrieves them according to
the results of a hash function. A hash cluster stores related rows together in the same
data blocks. Rows in a hash cluster are stored together based on their hash value.
( In contrast, an index cluster stores related rows of clustered tables based on each
row’s cluster key value.)
• Example:
CREATE CLUSTER trial_cluster (trialno NUMBER(5,0))
HASH IS trialno HASHKEYS 100000;
You can also specify any SQL expression as the hash function for a hash cluster. If your
cluster key values are not evenly distributed among the cluster, you should consider
creating your own hash function that more efficiently distributes cluster rows among the
hash values.
For example, if you have a hash cluster containing employee information and the cluster
key is the employee's home area code, it is likely that many employees will hash to the
same hash value. To alleviate this problem, you can place the following expression in the
HASH IS clause of the CREATE CLUSTER command:
MOD((emp.home_area_code + emp.home_prefix +
emp.home_suffix), 101)
The expression takes the area code column and adds the phone prefix and suffix columns,
divides by the number of hash values (in this case 101), and then uses the remainder as
the hash value. The result is cluster rows more evenly distributed among the various hash
values.
Sequences
• A sequence is a database object used to generate unique integers for use as primary
keys
• Syntax:
CREATE SEQUENCE seqname
[INCREMENT BY n]
[START WITH m]
[MAXVALUE integer | NOMAXVALUE ]
[MINVALUE integer | NOMINVALUE ]
[CYCLE | NOCYCLE ]
[CACHE integer | NOCACHE ]
• seqname.NEXTVAL returns the next value of the sequence. Also increments the
value
• Example:
CREATE SEQUENCE order_seq
START WITH 1
INCREMENT BY 1
NOMAXVALUE
NOCYCLE
CACHE 20;
Example: Referencing a Sequence
INSERT INTO orders (orderno, custno)
VALUES (order_seq.NEXTVAL, 1032);
UPDATE orders
SET orderno = order_seq.NEXTVAL
WHERE orderno = 10112;
Only a single sequence number can be generated per row; that is, if NEXTVAL is
referenced more than once in a single statement, the first reference generates the next
number and all subsequent references in the statement return the same number.
• Once a sequence number is generated, the sequence number is available only to the
session that generated the number. Independent of transactions committing or rolling
back, other users referencing ORDER_SEQ.NEXTVAL obtain unique values. If two
users are accessing the same sequence concurrently, the sequence numbers each user
receives might have gaps because sequence numbers are also being generated by the
other user.
Review Questions
3. You can query the index, but cannot modify its contents. (T / F)
4. A cluster is _________________________________________________________
___________________________________________________________________
5. Clusters, like indexes, can be created on any existing tables which have a common
column. (T / F)
8. Sequences can be used to generate both the ascending and descending lists of
numbers. (T / F)
Exercises
• Create a sequence itno_seq, which starts the counting from 1000, and will be used to
insert the ITNO value into the table ITEMMAST.
• Syntax :
INSERT INTO table [ ( column [, column ]… ) ]
{ VALUES ( expression [, expression ]… ) | query }
• An INSERT statement with a VALUES clause adds a single row to the table.
Examples
INSERT INTO dept
VALUES (50, 'PRODUCTION', 'SAN FRANCISCO');
INSERT INTO emp VALUES ( &1, ‘&2’, ‘&3’, &4, ‘&5’, &6,
NULL, &7);
This INSERT statement can be used to accept values interactively, and any number of
rows can be inserted one after the other by using the “ / “, which executes the last
executed SQL statement.
• Syntax :
• The SET clause determines which columns are updated and what new values are
stored in them.
• The WHERE clause determines the rows in which values are updated. If the WHERE
clause is not specified, all rows are updated.
Examples
• Cancel the commission for all trainees
UPDATE emp
SET comm = NULL
WHERE job = 'TRAINEE';
• All employees having more than 2 people reporting to them, are to directly report to
the PRESIDENT
UPDATE emp SET mgr = 7839
WHERE mgr <> 7839 AND empno IN
( SELECT mgr FROM emp
GROUP BY mgr HAVING COUNT(*) > 2 );
• The DELETE Command is used to remove rows from a table or from a view's base
table.
• Syntax :
DELETE FROM table [WHERE condition ];
Examples
DELETE FROM temp_assign;
Exercises
1. Insert the values into the Salespeople, Customers, and Orders tables.
2. Insert the values into the ITEMMAST and ITTRAN tables. Make use of the itno_seq
for inserting values for the ITNO column.
Querying Tables
Topics
• Syntax:
SELECT * | [DISTINCT] column [, column]...
FROM table [, table]...
[WHERE condition]
[GROUP BY column [, column]...]
[HAVING condition]
[ORDEY BY expr];
Examples
• To display the information of all employees
SELECT * FROM emp;
WHERE Clause
• To list the name and salary of the employees whose salary is more than 2000
SELECT ename, sal FROM emp WHERE sal > 2000;
• To list details of employees who have joined before the end of August 81
SELECT * FROM emp WHERE hiredate <= TO_DATE(‘31-AUG-81’, ‘DD-MON-
YY’);
Example :
• To list name, salary and PF amount which is calculated as 10%, of all employees
SELECT ename, sal, sal * .1 “PF” FROM emp;
SQL Functions
A SQL function is similar to an operator in that it manipulates data items and returns a
result. SQL functions differ from operators in the format in which they appear with their
arguments. This format allows them to operate on zero, one, two, or more arguments :
Function(argument, argument, …)
SQL functions are of these general types :
Single row (or scalar) functions
Group (or aggregate) functions
The two types of SQL functions differ in the number of rows upon which they act. A
single row function returns a single result row for every row of a queried table or view,
while a group function returns a single result row for a group of queried rows.
• The Group functions produce a single value for an entire GROUP or table
• In all group functions NULLs are ignored
• Different Group functions :
- COUNT
- SUM
- MAX
- MIN
- STDDEV
- VARIANCE
- AVG
Examples: Group functions to summarize data
• To list the number of employees working for the company
SELECT COUNT(*) FROM emp;
• To list the number of jobs available in the emp table
SELECT COUNT(DISTINCT job) FROM emp;
Number Functions
ABS(value) POWER(value, exponent)
CEIL(value) ROUND(value, precision)
COS(value) SIGN(value)
COSH(value) SIN(value)
EXP(value) SINH(value)
FLOOR(value) SQRT(value)
LN(value) TAN(value)
LOG(value) TANH(value)
MOD(value) TRUNC(value, precision)
NVL(value, substitute)
Raised
----------
9
String Functions
String || String LPAD(string, length[,’set’])
ASCII(string) LTRIM(string[,’set’])
CHR(integer) RPAD(string, length[,’set’])
CONCAT(string1, string2) RTRIM(string[,’set’])
INITCAP(string) SOUNDEX(string)
INSTR(string, set[,start[,occurrence]]) SUBSTR(string, start[, count])
LENGTH(string) UPPER(string)
LOWER(string)
Date Functions
ADD_MONTHS(date,count)
GREATEST(date1, date2, date3, …)
LEAST(date1, date2, date3, …)
LAST_DAY(date)
MONTHS_BETWEEN(date2, date1)
NEXT_DAY(date, ‘day’)
NEW_TIME(date, ‘this’, ‘other’)
ROUND(date, ‘format’)
TRUNC(date, ‘format’)
TO_CHAR(date, ‘format’)
TO_DATE(string, ‘format’)
Time Zones
Time Zone Description
AST/ADT Atlantic Standard / Daylight Time
BST/BDT Bering Standard / Daylight Time
CST/CDT Central Standard / Daylight Time
EST/EDT Eastern Standard / Daylight Time
GMT Greenwich Mean Time
HST/HDT Alaska-Hawaii Standard / Daylight Time
MST/MDT Mountain Standard / Daylight Time
NST Newfoundland Standard Time
PST/PDT Pacific Standard / Daylight Time
YST/YDT Yukon Standard / Daylight Time
Other Functions
Function Description
GREATEST (expr [,expr]…) Returns the greatest of the list of
expressions
LEAST (expr [,expr]…) Returns the least of the list of expressions
NVL (expr1, expr2) If expr1 is null, returns expr2; if expr1 is
not null, returns expr1
VSIZE (expr) Returns the number of bytes in the internal
representation of expr
DECODE (value, if1, then1 [, if2, If the value is if1 then the result of the
then2]… else) DECODE is then1; if it is if2 then the result
is then2, and so on; if the value equals none
of the ifs, then the result is else
ORDER BY Clause
• You can specify the column, and/or expression position also in the ORDER BY
clause.
Examples :
• To list the employee name, salary, PF, HRA, DA and gross, ordering the result in
ascending order of gross. HRA is 50% of salary and DA is 30% of salary.
SELECT ename, sal, sal * .1 “PF”, sal * .5 “HRA”, sal *.3 “DA”, sal + (sal * .5) +
(sal * .3) + (sal * .1) “GROSS” FROM emp
ORDER BY 6;
GROUP BY Clause
• Conditional retrieval of rows from a grouped result is possible with the HAVING
clause.
Examples :
• To list the number of employees working in each department
SELECT deptno, COUNT(*) FROM emp;
• To list the jobs and the total salaries payable to each job title
SELECT job, SUM(sal) FROM emp GROUP by job
ORDER BY 2 DESC;
• To list the the jobs and the total salaries payable to each job title only if the total
salary is > 5000
SELECT job, SUM(sal) FROM emp GROUP by job
HAVING SUM ( sal ) > 5000;
• Types of joins :
- Equi Join
- Cartesian Join
- Outer Join
- Self Join
Examples :
• Equi Join : To list the employee numbers, names, department numbers and the
department names
SELECT empno, ename, emp.deptno, dname FROM emp, dept
WHERE emp.deptno = dept.deptno;
• Outer Join : Display the list of employees working in each department. Display the
department information even if no employee belongs to that department.
SELECT empno,ename,emp.deptno, dname, loc FROM emp, dept
WHERE emp.deptno ( + ) = dept.deptno;
• Self Join : To display the employee names and the manager names in the emp table
SELECT WORKER.ename, MANAGER.ename
FROM emp WORKER, emp MANAGER
WHERE WORKER.mgr = MANAGER.empno;
SET Operators
• SET operators :
- UNION : Rows of first query plus rows of second query, less
duplicate rows
- INTERSECT : Common rows from all queries
- MINUS : Rows unique to the first query
Examples :
Nested Queries
• SQL first evaluates the sub query within the WHERE clause. The return value is then
substituted in the condition of the outer query.
• When using relational operators, ensure that the sub query returns a single row
output.
Examples:
• In a correlated sub query, the used in the outer query refers to the table used in the
inner sub query. The sub query is executed repeatedly, once for each row of the outer
query table.
Example : To list the employee names who have got more than one increment
SELECT empno, ename FROM emp
WHERE 1 < ( SELECT COUNT( * ) FROM incr
WHERE empno = emp.empno );
• Special operators :
- EXISTS : TRUE if a subquery returns at least one row.
- ANY/SOME : Compares a value to each value in a list or returned by a query.
Must be preceded by =, !=, >, <, <=, >=. Evaluates to FALSE if the query returns
no rows.
- ALL : Compares a value to every value in a list or returned by a query. Must be
preceded by =, !=, >, <, <=, >=. Evaluates to TRUE if the query returns no rows.
Examples :
• To list the employee details only if more than 10 employees are present in
dept 10
SELECT * FROM emp
WHERE deptno = 10 AND EXISTS
( SELECT deptno, COUNT( * )
FROM emp WHERE deptno = 10
GROUP BY deptno
HAVING COUNT ( * ) > 10 );
• To list the employee names whose salary is greater than the lowest salary of an
employee in dept 20
SELECT ename FROM emp
WHERE sal > ANY
( SELECT sal FROM emp WHERE deptno = 20 );
• To list the employee names whose salary is greater than the highest salary of an
employee in dept 20
SELECT ename FROM emp
WHERE sal > ALL
( SELECT sal FROM emp WHERE deptno = 20 );
More Examples:
Exercises
Refer to the Salespeople, Customers, and Orders Tables. Write queries for the following :
20. Write a query that selects the first customer, in alphabetical order whose name begins
with the letter H.
21. Count the number of salespeople currently listing orders in the Orders table.
22. Find the largest order taken by each salesperson.
23. List the largest order taken by each salesperson on each date.
24. Show the names of all customers matched with the salespeople serving them.
25. Find all pairs of customers having the same rating.
26. Display all orders of the salesperson Robert.
27. Find all orders credited to the same salesperson that services Periera.
28. Display all orders that are greater than the average for October 4th.
29. Find all orders attributed to salespeople in London.
30. Display the commissions of all salespeople servicing customers in London.
31. Find salespeople with customers located in their cities.
32. Output only those customers whose ratings are higher than every customer in Rome.
33. Write a query that selects each customer’s smallest order.
34. Write a query that counts the number of salespeople registering orders for each day (if
a salesperson has more than one order on a given day, he should be counted only
once).
35. Write a query on the orders table that will produce the order number, the salesperson
number and the amount of commission, for that order.
36. Write a query on the Customers table that will find the highest rating in each city. The
output should be of the form :
For the city city, the highest rating is rating
37. Write a query that lists customers in descending order of rating. Output the rating
field first, followed by the customer’s name and number.
38. Write a query that totals the orders for each day and places the results in descending
order.
39. Write a query that lists each order number followed by the name of the customer who
made the order.
40. Write a query that gives the names of both the salesperson and the customer for each
order after the order number.
41. Write a query that produces all customers serviced by salespeople with a commission
above 12%. Output the customer’s name, the salesperson name, and the salesperson’s
rate of commission.
42. Write a query that calculates the amount of the salespersons’ commission on each
order by a customer with a rating above 100.
43. Write a query that uses a sub-query to obtain all orders for the customer named
Harold.
44. Write a query that produces the names and ratings of all customers who have above
average orders.
45. Write a query that selects the total amount in orders for each salesperson for who this
total is greater than the amount of the largest order in the table.
46. Write a query that uses the EXISTS operator to extract all salespeople who have
customers with a rating of 300.
Solve this problem using a JOIN also.
47. Write a query that will find all salespeople who have no customers located in their
city.
Views
Topics
• What is a View?
• How Views are Used
• Creating Views
• Creating Views with Errors
• Replacing Views
• Using Views
• Modifying a Join View
• Partition Views
• The ALTER VIEW Command
• Dropping a View
What is a View?
• A view is a logical table that allows you to access data from other tables and views. A
view contains no data itself. The tables upon which a view is based are called base
tables.
• A view gives a tailored presentation of the data contained in one or more tables (or
other views).
• A view takes the output of a query and treats it as a table; therefore a view can be
thought of as a “stored query” or a “virtual table”. You can use views in most places
where a table can be used.
• You can query views, and with some restrictions, users can update, insert into, and
delete from the views. All operations performed on a view actually affect data in the
base tables of the view and are subject to the integrity constraints and triggers of the
base tables.
• to present the data in a different perspective from that of the base table
For example, the columns of a view can be renamed without affecting the tables on
which the view is based.
Table EMP
EMPN ENAM JOB MGR HIREDAT SAL COM DEPTN
O E E M O
7329 SMITH CLERK 7902 17-DEC-87 300.00 800.00 20
7499 ALLE SALESMA 7698 20-FEB-88 300.00 1600.0 30
N N 0
7521 WARD SALESMA 7698 22-FEB-88 5.00 1250.0 30
N 0
7566 JONES MANAGE 7839 02-APR-88 2975.0 20
R 0
Creating Views
• Use the SQL command CREATE VIEW to create a view. You can define views with
any query that references tables, snapshots, or other views; however, the query that
defines a view cannot contain the ORDER BY or FOR UPDATE clauses.
• Syntax :
CREATE [ OR REPLACE ] [ FORCE | NOFORCE ] VIEW
view [ ( alias [, alias ]… ) ]
AS query
[ WITH CHECK OPTION [ CONSTRAINT constraint ] ]
[ WITH READ ONLY ]
• The FORCE option creates the view regardless of whether the tables to which the
view refers exist or whether the user has privileges on them. The user still can’t
execute the view, but he/she can create it.
• The NOFORCE option creates the view only if the base tables exist and the user has
the privileges on them.
• alias specifies names for the expressions selected by the view's query. The number of
aliases must match the number of expressions selected by the view. If you omit the
aliases, Oracle derives them from the columns or column aliases in the view's query.
Hence, you must use aliases if the view's query contains expressions rather than only
column names.
• AS subquery identifies columns and rows of the table(s) that the view is based on. A
view's query can be any SELECT statement without the ORDER BY or FOR
UPDATE clauses.
• WITH READ ONLY specifies that no deletes, inserts, or updates can be performed
through the view.
• WITH CHECK OPTION specifies that inserts and updates performed through the
view must result in rows that the view query can select. The CHECK OPTION cannot
make this guarantee if there is a subquery in the query of this view or any view on
which this view is based.
• CONSTRAINT is the name assigned to the CHECK OPTION constraint. If you omit
this identifier, Oracle automatically assigns the constraint a name of this form:
SYS_Cn, where n is an integer that makes the constraint name unique within the
database.
• You can define a view with a query that uses an asterisk (*) to select all the columns
of a table: CREATE VIEW emp_vu AS SELECT * FROM emp ;
Examples : Views
• Assuming no syntax errors, a view can be created (with errors) even if the defining
query of the view cannot be executed. For example, if a view is created that refers to
a non-existent table or an invalid column of an existing table, or if the owner of the
view does not have the required privileges, the view can still be created and entered
into the data dictionary.
• You can only create a view with errors by using the FORCE option of the CREATE
VIEW command:
CREATE FORCE VIEW AS ...;
• When a view is created with errors, Oracle returns a message that indicates the view
was created with errors. The status of such a view is left as INVALID. If conditions
later change so that the query of an invalid view can be executed, the view can be
recompiled and become valid. Oracle dynamically compiles the invalid view if you
attempt to use it.
Replacing Views
To alter the definition of a view, you must replace the view using one of the following
methods:
• Example:
CREATE OR REPLACE VIEW sales_staff AS
SELECT empno, ename, deptno
FROM emp
WHERE deptno = 30
WITH CHECK OPTION CONSTRAINT sales_staff_cnst;
Using Views
• Views can be queried in the same manner as tables. For example, to query the
SALES_STAFF view, enter a valid SELECT statement that references the view:
SELECT * FROM sales_staff;
• With some restrictions, rows can be inserted into, updated in, or deleted from a base
table using a view. The following statement inserts a new row into the EMP table
using the SALES_STAFF view:
• Restrictions on DML operations for views use the following criteria in the order
listed:
1. If a view is defined by a query that contains SET or DISTINCT operators, a GROUP
BY clause, or a group function, rows cannot be inserted into, updated in, or deleted
from the base tables using the view.
2. If a view is defined with the WITH CHECK OPTION, a row cannot be inserted into,
or updated in, the base table (using the view) if the view cannot select the row from
the base table.
3. If a NOT NULL column that does not have a DEFAULT clause is omitted from the
view, a row cannot be inserted into the base table using the view.
4. If the view was created by using an expression, such as DECODE(deptno, 10,
'SALES', ...), rows cannot be inserted into or updated in the base table using the view.
• The Oracle Server allows you, with some restrictions, to modify views that involve
joins.
• If you create a view that involves a join operation, such as:
CREATE VIEW emp_dept AS
SELECT e.empno, e.ename, e.deptno, d.dname, d.loc
FROM emp e, dept d /* JOIN operation */
WHERE e.deptno = d.deptno
AND d.loc IN ('DALLAS', 'NEW YORK', 'BOSTON');
then there are restrictions on modifying either the EMP or the DEPT base table
through this view, for example, using a statement such as:
UPDATE emp_dept SET ename = 'JOHNSON'
WHERE ename = 'SMITH';
• A modifiable join view is a view that contains more than one table in the top-level
FROM clause of the SELECT statement, and that does not contain any of the
following:
- DISTINCT operator
- aggregate functions: AVG, COUNT, MAX, MIN, STDDEV, SUM, or
VARIANCE
- set operations: UNION, UNION ALL, INTERSECT, MINUS
- GROUP BY or HAVING clauses
- START WITH or CONNECT BY clauses
- ROWNUM pseudocolumn
Key-Preserved Tables:
Note: It is not necessary that the key or keys of a table be selected for it to be key
preserved. It is sufficient that if the key or keys were selected, then they would also be
key(s) of the result of the join.
In the EMP_DEPT view, EMP is a key-preserved table, because EMPNO is a key of the
EMP table, and also a key of the result of the join. DEPT is not a key-preserved table,
because although DEPTNO is a key of the DEPT table, it is not a key of the join.
Any UPDATE, INSERT, or DELETE statement on a join view can modify only one
underlying base table.
UPDATE Statements
• The following example shows an UPDATE statement that successfully modifies the
EMP_DEPT view:
UPDATE emp_dept
SET ename = 'JOHNSON'
WHERE ename = 'SMITH';
• If the view is defined using the WITH CHECK OPTION clause, then all join columns
and all columns of repeated tables are not modifiable. So, for example, if the
EMP_DEPT view were defined using WITH CHECK OPTION, the following
UPDATE statement would fail:
UPDATE emp_dept
SET deptno = 10
WHERE ename = 'SMITH';
DELETE Statements
• You can delete from a join view provided there is one and only one key-preserved
table in the join.
The following DELETE statement works on the EMP_DEPT view:
DELETE FROM emp_dept
WHERE ename = 'SMITH';
• In the following view, a DELETE operation cannot be performed on the view because
both E1 and E2 are key-preserved tables:
CREATE VIEW emp_emp AS
SELECT e1.ename, e2.empno, deptno
FROM emp e1, emp e2
WHERE e1.empno = e2.empno;
• If a view is defined using the WITH CHECK OPTION clause and the key-preserved
table is repeated, then rows cannot be deleted from such a view. For example:
CREATE VIEW emp_mgr AS
SELECT e1.ename, e2.ename mname
FROM emp e1, emp e2
WHERE e1.mgr = e2.empno WITH CHECK OPTION;
No deletion can be performed on this view because the view involves a self-join
of the table that is key preserved.
INSERT Statements
Three views are available to assist you in using the capability of modifying join views.
These views are defined in the following table:
Partition Views
• The database administrator can use partition views to divide a very large table into
multiple smaller pieces (or partitions) to achieve significant improvements in
availability, administration, and performance.
• The basic idea behind partition views is simple: divide the large table into multiple
physical tables using a partitioning criteria; glue the partitions together into a whole
for query purposes. A partition view can assign key ranges to partitions. Queries that
use a key range to select from a partitions view will access only the partitions that lie
within the key range.
Example:
Sales data for a calendar year may be broken up into four separate tables, one per quarter:
Q1_SALES, Q2_SALES, Q3_SALES and Q4_SALES. A partition view may then be
defined by using check constraints or by using WHERE clauses.
However, using WHERE clauses to define partition views has one advantage over using
check constraints: the partition can be on a remote database with WHERE clauses. For
example:
Because queries against eastern sales data do not need to fetch any western data, users
will get increased performance. This cannot be done with constraints because the
distributed query facility does not retrieve check constrains from remote databases.
• Syntax :
ALTER VIEW view COMPILE
• ALTER VIEW recompiles a view. You can use ALTER VIEW to explicitly
recompile a view that is invalid. Explicit recompilation allows you to locate
recompilation errors before runtime.
• You may want to explicitly recompile a view after altering one of its base tables to
ensure that the alteration does not affect the view or other objects that depend on it.
• When you issue the ALTER VIEW command Oracle recompiles the view regardless
of whether it is valid or invalid. Oracle also invalidates all dependent objects
(procedures, functions, package bodies, and views that reference this view). If you
subsequently reference one of these objects without first explicitly recompiling it,
Oracle recompiles it implicitly at runtime.
Dropping a View
Review Questions
1. If modifications are made on a base table on which a view is based, after the view is
created, the view does not show the changes. (T / F)
3. If you want that any inserts or updates performed through the view result in rows that
the view query can select, you use the ______________________________________
clause in the CREATE VIEW command.
Exercises
1. Create a view that contains the name and department number of all employees
belonging to department 30 and 40, who are either clerk or salesman.
2. Create a view that stores the info regarding the total employees working in each
department under each job title.
3. Create a view that stores the employee numbers and total salaries (sum of sal and
comm) for all the employees.
4. Create a view that holds info of each department number, department name, the name
of the last employee hired in that department, and his hire date.
Controlling Transactions
Topics
• A transaction (or a logical unit of work) is a sequence of SQL statements that Oracle
treats as a single unit. A transaction begins with the first executable SQL statement
after a COMMIT, ROLLBACK or connection to the database. A transaction ends
with a COMMIT, ROLLBACK or disconnection (intentional or unintentional) from
the database.
• COMMIT is used to end your current transaction and make permanent all changes
performed in the transaction.
• This command also erases all savepoints in the transaction and releases the
transaction's locks.
Example :
INSERT INTO dept VALUES (50, 'MARKETING', 'TAMPA');
COMMIT;
• Using the ROLLBACK command without the TO SAVEPOINT clause performs the
following operations:
- ends the transaction
- undoes all changes in the current transaction
- erases all savepoints in the transaction
- releases the transaction's locks
Example :
UPDATE emp SET sal = sal + sal * .10;
ROLLBACK;
• Using the ROLLBACK command with the TO SAVEPOINT clause performs the
following operations:
- rolls back just the portion of the transaction after the savepoint.
- loses all savepoints created after that savepoint.
- releases all table and row locks acquired since the savepoint.
Example :
• Syntax :
SET TRANSACTION { READ ONLY | READ WRITE |
USE ROLLBACK SEGMENT segment }
Example :
COMMIT;
SET TRANSACTION READ ONLY;
SELECT COUNT(*)
FROM emp;
SELECT COUNT(*)
FROM dept;
COMMIT ;
The last COMMIT statement does not actually make permanent any
changes to the database. It ends the read-only transaction.
• SQL *PLUS has the facility to automatically commit your work without your
explicitly telling to do so.
• SET AUTOCOMMIT ON : Sets the auto commit feature ON; OFF is the default.
Review Questions
3. The command used to make all the changes made in the current transaction
permanent is __________________________________________
6. If you want the commit to happen automatically after each DML statement execution,
the SQL*PLUS command used is _________________________________________
SQL Tuning
• Because SQL is a flexible language, more than one SQL statement may meet the
needs of your application.
• Although two SQL statements may produce the same result, Oracle may process one
faster than the other.
• You can use the results of the EXPLAIN PLAN statement to compare the execution
plans and costs of the two statements and determine which is more efficient.
Example: Consider the following two statements to return all the departments in the
DEPT table that have no employees in the EMP table. Each statement searches the EMP
table with a subquery. Assume there is an index, DEPTNO_INDEX, on the DEPTNO
column of the EMP table.
Statement1:
SELECT dname, deptno
FROM dept
WHERE deptno NOT IN
(SELECT deptno FROM emp);
Oracle executes this statement by performing a full table scan of the EMP table despite
the index on the DEPTNO column. This full table scan can be a time-consuming
operation. Oracle does not use the index because the subquery that searches the EMP
table does not have a WHERE clause that makes the index available.
Statement2:
SELECT dname, deptno
FROM dept WHERE NOT EXISTS
(SELECT deptno
FROM emp
WHERE dept.deptno = emp.deptno);
The WHERE clause of the subquery refers to the DEPTNO column of the EMP table, so
the index DEPTNO_INDEX is used. The index range scan of DEPTNO_INDEX takes
less time than the full scan of the EMP table in the first statement. Furthermore, the first
query performs one full scan of the EMP table for every DEPTNO in the DEPT table. For
these reasons, the second SQL statement is faster than the first.
If you have statements in your applications that use the NOT IN operator, as the first
query in this example does, you should consider rewriting them so that they use the NOT
EXISTS operator. This would allow such statements to use an index, if one exists.
rather than
WHERE TO_NUMBER(substr(a.order_no,instr(b.order_no,'.')-1)
= TO_NUMBER(substr(a.order_no, instr(b.order_no, '.') - 1)
Use optimizer hints, such as /*+ORDERED */ to control access paths. This is a better
approach than using traditional techniques or "tricks of the trade" such as CUST_NO + 0.
For example, use
rather than
SELECT E.ENAME
FROM EMP E
WHERE E.JOB || '' = 'CLERK';
Avoid mixed-mode expressions, and beware of implicit type conversions. When you
want to use an index on the VARCHAR2 column charcol, but the WHERE clause looks
like this:
You can avoid this problem by replacing the top expression with the explicit conversion
DISTINCT always creates a SORT; all the data must be instantiated before your results
can be returned.
The shared SQL area in Oracle reduces the cost of parsing queries that reference views.
In addition, optimizer improvements make the processing of predicates against views
very efficient. Together these factors make possible the use of views for ad hoc queries.
Despite this, joins to views are not recommended, particularly joins from one complex
view to another.
Beware of writing a view for one purpose and then using it for other purposes, to which it
may be ill-suited. Consider this example:
You can obtain dname and deptno directly from the DEPT table. It would be inefficient
to obtain this information by querying the DX view (which was declared earlier in the
present example). To answer the query, the view would perform a join of the DEPT and
EMP tables, even though you do not need any data from the EMP table.
Using Indexes
• Indexes improve the performance of queries that select a small percentage of rows
from a table.
• As a general guideline, create indexes on tables that are queried for less than 2% or
4% of the table's rows.
• Building indexes "just in case" is not a good practice; indexes should not be built
until required.
• To maintain optimal performance with indexes, drop indexes that your application is
not using. You can find indexes that are not referenced in execution plans by
processing all of your application SQL through EXPLAIN PLAN and capturing the
resulting plans.
Composite Indexes
A composite index contains more than one key column. Composite indexes can provide
additional advantages over single-column indexes:
Improved Sometimes two or more columns or expressions, each with poor selectivity, can be
selectivity combined to form a composite index with more accurate selectivity.
Reduced If all columns selected by a query are in a composite index, then Oracle can return
I/O these values from the index without accessing the table.
A SQL statement can use an access path involving a composite index if the statement
contains constructs that use a leading portion of the index. A leading portion of an index
is a set of one or more columns that were specified first and consecutively in the list of
columns in the CREATE INDEX statement that created the index. Consider this
CREATE INDEX statement:
These combinations of columns are leading portions of the index: x, xy, and xyz. These
combinations of columns are not leading portions of the index: yz, y, and z.
SELECT ename
FROM emp
WHERE deptno = 10;
SELECT ename
FROM emp
WHERE deptno = 10;
The situation will be even worse! Instead, consider composite (concatenated) index on
the columns contained in both the SELECT and the WHERE clauses:
SELECT ename
FROM emp
WHERE deptno = 10;
The query now will be tremendously faster. The table itself did not have to be accessed.
Indexing both the column contained in the SELECT clause and the column in the
WHERE clause allows the query to only access the index.
The fast full index scan is an alternative to a full table scan when there is an index that
contains all the keys that are needed for the query. A fast full scan is faster than a normal
full index scan in that it can use multiblock I/O and can be parallelized just like a table
scan.
SELECT COUNT(*)
FROM t1, t2
WHERE t1.c1 > 50
AND t1.c2 = t2.c1;
SELECT STATEMENT
SORT AGGREGATE
HASH JOIN
TABLE ACCESS t1 FULL
INDEX t2_c1_idx FAST FULL SCAN
Because index t2_c1_idx contains all columns needed from table t2, the optimizer uses a
fast full index scan on that index.
Fast full scan has a special index hint, INDEX_FFS, which has the same format and
arguments as the regular INDEX hint.
In some cases, you may want to prevent a SQL statement from using an access path that
uses an existing index. You may want to do this if you know that the index is not very
selective and that a full table scan would be more efficient. If the statement contains a
construct that makes such an index access path available, then you can force the
optimizer to use a full table scan through one of these methods:
• You can use the NO_INDEX hint to give the CBO maximum flexibility while
disallowing the use of a certain index.
• You can use the FULL hint to force the optimizer to choose a full table scan
instead of an index scan.
• You can use the INDEX, INDEX_COMBINE, or AND_EQUAL hints to force
the optimizer to use one index or a set of listed indexes instead of another.
Function-based Indexes
Examples
• Oracle compares SQL statements and PL/SQL blocks issued directly by users and
applications, as well as recursive SQL statements issued internally by a DDL
statement. If two exact statements are issued, then the SQL or PL/SQL area used to
process the first instance of the statement is shared.
• Shared SQL and PL/SQL areas are shared memory areas.
• Shared SQL and PL/SQL areas age out of the shared pool according to a "least
recently used" (LRU) algorithm, similar to database buffers. To improve performance
and prevent reparsing, you may want to prevent large SQL or PL/SQL areas from
aging out of the shared pool.
• A problem can occur if users fill the shared pool, and then a large package ages out. If
someone calls the large package back in, then a significant amount of maintenance is
required to create space for it in the shared pool.
• You can avoid this problem by reserving space for large allocations with the
SHARED_POOL_RESERVED_SIZE initialization parameter. This parameter sets
aside room in the shared pool for allocations larger than the value specified by the
SHARED_POOL_RESERVED_SIZE_MIN_ALLOC parameter.
inexplicable slowdowns in user response time that occur when SQL and PL/SQL
areas are accessed after aging out.
To use the DBMS_SHARED_POOL package to pin a SQL or PL/SQL area, complete the
following steps.
1. Decide which packages or cursors to pin in memory.
2. Start up the database.
3. Make the call to DBMS_SHARED_POOL.KEEP to pin your objects.
This procedure ensures that your system does not run out of shared memory before the
objects are loaded. By pinning the objects early in the life of the instance, you prevent
memory fragmentation that could result from pinning a large portion of memory in the
middle of the shared pool.
Example:
DBMS_SHARED_POOL.KEEP('scott.hispackage');
• The EXPLAIN PLAN statement displays execution plans chosen by the Oracle
optimizer for SELECT, UPDATE, INSERT, and DELETE statements.
• A statement's execution plan is the sequence of operations Oracle performs to
execute the statement.
• The components of execution plans include:
− An ordering of the tables referenced by the statement.
− An access method for each table mentioned in the statement.
− A join method for tables affected by join operations in the statement.
• EXPLAIN PLAN output shows how Oracle executes SQL statements. EXPLAIN
PLAN results alone, however, cannot differentiate between well-tuned statements and
those that perform poorly.
• For example, if EXPLAIN PLAN output shows that a statement uses an index, then
this does not mean the statement runs efficiently. Sometimes using indexes can be
extremely inefficient.
• It is best to use EXPLAIN PLAN to determine an access plan, and later prove that it
is the optimal plan through testing.
• When evaluating a plan, always examine the statement's actual resource consumption.
For best results, use the Oracle Trace or SQL trace facility and TKPROF to examine
individual SQL statement performance.
Before you can issue an EXPLAIN PLAN statement, you must create a table to hold its
output. Use one of the following approaches:
• Run the SQL script UTLXPLAN.SQL to create a sample output table called
PLAN_TABLE in your schema. PLAN_TABLE is the default table into which the
EXPLAIN PLAN statement inserts rows describing execution plans.
• Issue a CREATE TABLE statement to create an output table with any name you
choose. When you issue an EXPLAIN PLAN statement you can direct its output to
this table.
Any table used to store the output of the EXPLAIN PLAN command must have the same
column names and datatypes as the PLAN_TABLE:
object_owner VARCHAR2(30),
object_name VARCHAR2(30),
object_instance NUMERIC,
object_type VARCHAR2(30),
optimizer VARCHAR2(255),
search_columns NUMERIC,
id NUMERIC,
parent_id NUMERIC,
position NUMERIC,
cost NUMERIC,
cardinality NUMERIC,
bytes NUMERIC,
other_tag VARCHAR2(255),
other LONG);
The following example shows a SQL statement and its corresponding execution plan
generated by EXPLAIN PLAN. The sample query retrieves names and related
information for employees whose salary is not within any range of the SALGRADE
table:
This EXPLAIN PLAN statement generates an execution plan and places the output in
PLAN_TABLE:
EXPLAIN PLAN
SET STATEMENT_ID = 'Emp_Sal'
FOR SELECT ename, job, sal, dname
FROM emp, dept
WHERE emp.deptno = dept.deptno
AND NOT EXISTS
(SELECT *
FROM salgrade
WHERE emp.sal BETWEEN losal AND hisal);
This type of SELECT statement generates a nested representation of the output that more
closely depicts the processing order used for the SQL statement.
Query Plan
------------------------------
SELECT STATEMENT Cost = 5
FILTER
NESTED LOOPS
TABLE ACCESS FULL EMP
TABLE ACCESS FULL DEPT
Bibliography
Oracle documentation
Oracle Database Concepts
Oracle SQL Reference
Oracle Database Performance Guide and Reference
***End of Document***