You are on page 1of 26

Oracle PL/SQL

By Pappu Neelavani npappu@csc.com

Confidentiality statement

04/28/12 08:26

Table of Contents

Introduction to ORACLE Database


What is Oracle? Oracle database server Oracle Instance What is personal oracle? Starting Database Starting SQL*Plus

SQL* PLUS Fundamentals


SQL Data Definition Language SQL Data Types SQL Data Manipulation Language Displaying Table Metadata Oracle Pseudo-Columns SQL Functions Recursive Queries and Table Aliases Formatting SQL*Plus Output

04/28/12 08:26

Table of Contents

SQL*PLUS Fundamentals
Saving SQL*Plus Output using the SPOOL Command Prompting and Accepting user Input Collecting Statistics On SQL Statements Stored Procedures and Triggers

PL SQL Fundamentals
Introduction Executing PL/SQL Data Types Control Structures Cursors Handling Errors and Exceptions

04/28/12 08:26

Introduction to Oracle Database


What is Oracle?
Oracle is the name of the database management system that comes from Oracle Corporation. Oracle11g is the latest product released by Oracle Corporation. Unlike Oracle8i, which is only a database management system, Oracle9i is a collection of following software:
Oracle9i Application Server Oracle9iAS

Oracle9i Database Server Oracle9iDB Oracle9i Developer Suite Oracle9iDS In simple words Oracle9i is a platform and not a simple database management system. Oracle9iDB is the database management system that is used to store and access data. Oracle is by far the most widely used relational database management system (RDBMS).

04/28/12 08:26

Oracle Database Server


Oracle database server is one of the databases that are widely used in client/server computing as back-end. Front-end programs that are written using application development tools such as Visual basic access Oracle and submit SQL commands for execution.

Oracle supports both OLTP (online transaction processing) applications as well as data warehouse applications, which contain a very large database (VLDB). Oracle has been its presence on around 100 different platforms. Oracle is quite scalable, which means it can scale up and down very easily as the requirements change. Oracle also provides Java Virtual Machine (JVM) as part of database. This enables oracle to run java programs.
04/28/12 08:26

Oracle Architecture
2 types of architecture exists: 1. Client server 2. Multitier Client-Server Architecture In this architecture, the database system is divided into two parts: a front-end or a client, and a back-end or a server. The client is a database application that initiates a request for an operation to be performed on the database server. Often, the client runs on a different computer than the database server. Many clients can simultaneously run against one server. The server runs Oracle software and receives and processes the SQL and PL/SQL statements that originate from client applications. Multitier Architecture: It has the following components A client or initiator process that starts an operation One or more application servers that perform parts of the operation. An application server provides access to the data for the client and performs some of the query processing, thus removing some of the load from the database server. It can serve as an interface between clients and multiple database servers including providing an additional level of security. A database server that stores most of the data used in the operation
04/28/12 08:26

Oracle Architecture

04/28/12 08:26

Oracle Architecture
The basic memory structures associated with Oracle are 1.The System Global Area (SGA) 2.and the Program Global Area (PGA) System Global Area (SGA) The SGA is a shared memory region that Oracle uses to store data and control information for one Oracle instance. The SGA is allocated when the Oracle instance starts and deallocated when the Oracle instance shuts down. Each Oracle instance that starts has its own SGA. The information in the SGA consists of :
1. The database buffer cache--This stores the most recently used data blocks. These blocks can contain modified data that has not yet been written to disk. 2. The redo log buffer--This stores redo entries, or a log of changes made to the database 3. The shared pool--This is the area of the SGA that stores shared memory structures such as shared SQL areas in the library cache and internal information in the data dictionary.

The Library Cache


The library cache is used to store shared SQL. Here the parse tree and the execution plan for every unique SQL statement are cached.

The Data-Dictionary Cache


The data dictionary contains a set of tables and views that Oracle uses as a reference to the database. Oracle stores information here about the logical and physical structure of the database.
04/28/12 08:26

Oracle Architecture
Program Global Area (PGA) The PGA is a memory area that contains data and control information for the Oracle server processes. This area consists of the following components:
Stack space--This is the memory that holds the session's variables, arrays, and so on. Session information--If you are not running the multithreaded server, the session information is stored in the PGA. If you are running the multithreaded server, the session information is stored in the SGA. Private SQL area--This is an area in the PGA where information such as binding variables and runtime buffers is kept.

04/28/12 08:26

Oracle Architecture
Processes
process refers to the mechanism of execution and can refer to a traditional process or a thread. The Oracle RDBMS uses two types of processes: user processes and Oracle processes (also known as background processes).

User Processes
User, or client, processes are the user's connections to the RDBMS system. The user process manipulates the user's input and communicates with the Oracle server process through the Oracle program interface.

Oracle Processes
Oracle processes perform functions for users. Oracle processes can be split into two groups: 1. server processes (which perform functions for the invoking process) 2. and background processes (which perform functions on behalf of the entire RDBMS).

Server Processes
Server processes, also known as shadow processes, communicate with the user and interact with Oracle to carry out the user's requests. For example, if the user process requests a piece of data not already in the SGA, the shadow process is responsible for reading the data blocks from the datafiles into the SGA.

Background Processes
Background processes are used to perform various tasks within the RDBMS system. These tasks vary from communicating with other Oracle instances and performing system maintenance and cleanup to writing dirty blocks to disk. Following are brief descriptions of the nine Oracle background processes:

04/28/12 08:26

Background Processes
DBWR (Database Writer)--DBWR is responsible for writing dirty data blocks from the database block
buffers to disk. log.

LGWR (Log Writer)--The LGWR process is responsible for writing data from the log buffer to the redo CKPT (Checkpoint)--The CKPT process is responsible for signaling the DBWR process to perform a
checkpoint and to update all the datafiles and control files for the database to indicate the most recent checkpoint. A checkpoint is an event in which all modified database buffers are written to the datafiles by the DBWR. The CKPT process is optional. If the CKPT process is not present, the LGWR assumes these responsibilities. cleaning up if a process prematurely dies (PMON cleans up the cache and frees resources that might still be allocated). PMON is also responsible for restarting any dispatcher processes that might have failed. cleaning temporary segments and recovering transactions that have died because of a system crash. The SMON also defragments the database by coalescing free extents within the database.

PMON (Process Monitor)--PMON is responsible for keeping track of database processes and SMON (System Monitor)--SMON performs instance recovery at instance startup. This includes

RECO (Recovery)--RECO is used to clean transactions that were pending in a distributed database. RECO is responsible for committing or rolling back the local portion of the disputed transactions. ARCH (Archiver)--ARCH is responsible for copying the online redo log files to archival storage when they become full. ARCH is active only when the RDBMS is operated in ARCHIVELOG mode. When a system is not operated in ARCHIVELOG mode, it might not be possible to recover after a system failure. It is possible to run in NOARCHIVELOG mode under certain circumstances, but typically should operate in ARCHIVELOG mode. LCKn (Parallel Server Lock)--Up to 10 LCK processes are used for interi nstance locking when the Oracle Parallel Server option is used. Dnnn (Dispatcher)--When the Multithreaded Server option is used, at least one Dispatcher process is used for every communications protocol in use. The Dispatcher process is responsible for routing requests from the user processes to available shared server processes and back. 04/28/12 08:26

Oracle Instance
Every oracle installation contains at least one Oracle Instance and one oracle database.

Primary Memory RAM Oracle Instance

Oracle Database

Hard Disk

Every time a database is started, a system global area (SGA) is allocated and Oracle background processes are started. The combination of the background processes and memory buffers is called an Oracle instance. Each oracle database is to be accessed by one or more Oracle instances. If two or more instances are accessing the same database, it is called as parallel server architecture. In order to start using an oracle database, we must first start Oracle instance. Oracle instance will them open the database and make it available to users.
04/28/12 08:26

Personal Oracle
Personal Oracle is like a tool.

Client Oracle Instance

Oracle Database

It runs on desktop PCs. In personal oracle, oracle instance, oracle database and client application all run on the same machine. Whereas in Oracle database server, only oracle instance and database reside on the server and client applications run on clients..
04/28/12 08:26

Starting Up Database
Before we access oracle database, we must start oracle database. Starting up oracle database means starting oracle instance and associating oracle instance with an oracle database so that oracle instance can access the database. The three steps to starting an Oracle database and making it available for system wide use are: 1.Start an instance. 2.Mount the database. 3.Open the database.
Start Oracle server in UNIX: Type the following command: $ su - oracle Now use lsnrctl command to start service (e.g usually located at /home/oracle/oracle/product/10.2.0/db_1/bin directory): $ lsnrctl start Next start database: $ dbstart Stop Oracle service in UNIX: To stop Oracle service, type following two commands: $ lsnrctl stop $ dbshut
04/28/12 08:26

Database Structures
Oracle Database has 2 types of structures: 1. Physical 2. Logical Physical database structures Physical database structures of an Oracle database includes
datafiles, redo log files, and control files.

Datafiles
Every Oracle database has one or more physical datafiles. The datafiles contain all the database data. The data of logical database structures, such as tables and indexes, is physically stored in the datafiles allocated for a database. A datafile can be associated with only one database.

Control Files
Every Oracle database has a control file. A control file contains entries that specify the physical structure of the database. For example, it contains the following information: Database name Names and locations of datafiles and redo log files Time stamp of database creation

04/28/12 08:26

Database Structures
Redo Log Files
Every Oracle database has a set of two or more redo log files. The primary function of the redo log is to record all changes made to data. If a failure prevents modified data from being permanently written to the datafiles, then the changes can be obtained from the redo log, so work is never lost. Archive Log Files You can enable automatic archiving of the redo log. Oracle automatically archives log files when the database is in ARCHIVELOG mode. Parameter Files Parameter files contain a list of configuration parameters for that instance and database. Oracle recommends that you create a server parameter file (SPFILE) as a dynamic means of maintaining initialization parameters. A server parameter file lets you store and manage your initialization parameters persistently in a server-side disk file. Alert and Trace Log Files Each server and background process can write to an associated trace file. When an internal error is detected by a process, it dumps information about the error to its trace file. Some of the information written to a trace file is intended for the database administrator, while other information is for Oracle Support Services. Trace file information is also used to tune applications and instances. The alert file, or alert log, is a special trace file. The alert log of a database is a chronological log of messages and errors.

04/28/12 08:26

Database Structures
Backup Files To restore a file is to replace it with a backup file. Typically, you restore a file when a media failure or user error has damaged or deleted the original file. User-managed backup and recovery requires you to actually restore backup files before you can perform a trial recovery of the backups. Server-managed backup and recovery manages the backup process, such as scheduling of backups, as well as the recovery process, such as applying the correct backup file when recovery is needed.

Logical Database Structures


The logical storage structures, includes data blocks, extents, and segments, enable Oracle to have fine-grained control of disk space use. Tablespaces A database is divided into logical storage units called tablespaces, which groups related logical structures together. Each database is logically divided into one or more tablespaces. One or more datafiles are explicitly created for each tablespace to physically store the data of all logical structures in a tablespace. The combined size of the datafiles in a tablespace is the total storage capacity of the tablespace. Oracle Data Blocks At the finest level of granularity, Oracle database data is stored in data blocks. One data block corresponds to a specific number of bytes of physical database space on disk. The standard block size is specified by the DB_BLOCK_SIZE initialization parameter.
04/28/12 08:26

Database Structures
Extents The next level of logical database space is an extent. An extent is a specific number of contiguous data blocks, obtained in a single allocation, used to store a specific type of information. Segments Above extents, the level of logical database storage is a segment. A segment is a set of extents allocated for a certain logical structure. The following are different types of segments: Data segment, Index segment, Temporary segment, Rollback segment. Schema Schema is a collection of database objects. A schema is owned by a database user and has the same name as that user. Schema objects are the logical structures that directly refer to the database's data. Schema objects include structures like tables, views, and indexes. Some of the most common schema objects are: Tables Tables are the basic unit of data storage in an Oracle database. Database tables hold all user-accessible data. Each table has columns and rows. Indexes Indexes are optional structures associated with tables. Indexes can be created to increase the performance of data retrieval.

04/28/12 08:26

Database Structures
Views Views are customized presentations of data in one or more tables or other views. A view can also be considered a stored query. Views do not actually contain data. Rather, they derive their data from the tables. Clusters Clusters are groups of one or more tables physically stored together because they share common columns and are often used together. Because related rows are physically stored together, disk access time improves. Like indexes, clusters do not affect application design. Whether a table is part of a cluster is transparent to users and to applications. Synonyms A synonym is an alias for any table, view, materialized view, sequence, procedure, function, package, type, Java class schema object, user-defined object type, or another synonym. Because a synonym is simply an alias, it requires no storage other than its definition in the data dictionary. Oracle Data Dictionary An Oracle data dictionary is a set of tables and views that are used as a read-only reference about the database. For example, a data dictionary stores information about both the logical and physical structure of the database. A data dictionary is created when a database is created. To accurately reflect the status of the database at all times, the data dictionary is automatically updated by Oracle in response to specific actions, such as when the structure 04/28/12 08:26 of the database is altered.

Starting SQL* PLUS


SQL*plus is a tool that comes along with Oracle. It is used to issue SQL and SQL*PLUS commands. It provides command line interface through which we can enter SQL and SQL*PLUS command. On windows : 1. Select start->programs->Oracle Oracle9i. (Oracle9i is the name of the instance. ) 2. Then select Application Development -> SQL Plus. 3. When Log On dialog box is displayed, enter username, password and Host string. Use tab key to move from one field to another. 4. Click on OK. 5. If the information supplied is valid then you enter into Oracle and SQL*PLUS will display SQL> prompt.

Every user who wants to access oracle database must have an account in the database. These accounts are created by DBA. Each account is associated with username and password.
04/28/12 08:26

Starting SQL* PLUS


Oracle comes with a set of predefined accounts. The following are the usernames and passwords of these accounts: Username system sys Scott Demo Note: when you enter into oracle using either system or sys then you become DBA. That means you get special privileges to perform major operations such as creating users etc. Password manager change_on_install tiger demo

04/28/12 08:26

Host String
Host string is required when you are trying to connect to Oracle Server running on remote machine. Host string is actually called as net service name. Net service name is a name that is stored in TNSNAMES.ORA file on the client to provide the following information. Host Name of the machine or IP address of the machine on which oracle server is running. Instance name Name of the Oracle Instance running on the remote machine. Port Number Port number of the listener, a program that takes requests from clients. Port number is an integer that uniquely identifies the program on the server.
Example1.world = ) (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (COMMUNITY = tcp.world) (PROTOCOL = TCP) (Host = Production1) (Port = 1521) ) ) (CONNECT_DATA = (SID = SID1))

04/28/12 08:26

How to enter SQL statements?


The following are the rules to be followed while entering SQL commands. 1. An SQL statement may be entered in multiple lines. 2. It is not possible to break a word across lines. 3. SQL statement must be terminated by semicolon (;) The following is an example of SQL command. SQL> select ccode,name 2 from courses 3 where fee > 5000; In the above command, we entered the command in three lines. When you enter semicolon and press enter key then SQL*PLUS will take it as the end of the command. Also note that you have to press enter key at the end of each line. The following example show how to use CLEAR SCREEN command: SQL>clear screen Or SQL>cl scr

04/28/12 08:26

Common Errors
The following are the common errors that you get while you are trying to log on to Oracle. Ora-01017: invalid username/password; login denied The reason for this error is that you have entered a username or password that is not valid. Check whether username you are entering is really existing and password is correctly typed. ORA-01034: ORACLE not available The reason for this message is that Oracle Instance is not up and running.

04/28/12 08:26

What affects Oracle Performance


1. Overview of Computer Architecture 2. CPU and Cache 3. CPU Design 4. CISC Processors 5. RISC Processors 6. Multiprocessor Systems

04/28/12 08:26

Thank You

04/28/12 08:26

You might also like