PL/SQL Tutorial

tags:


The PL/SQL programming language was developed by Oracle Corporation in the late 1980s as procedural extension language for SQL and the Oracle relational database. Following are certain notable facts about PL/SQL −

  • PL/SQL is a completely portable, high-performance transaction-processing language.

  • PL/SQL provides a built-in, interpreted and OS independent programming environment.

  • PL/SQL can also directly be called from the command-line SQL*Plus interface.

  • Direct call can also be made from external programming language calls to database.

  • PL/SQL’s general syntax is based on that of ADA and Pascal programming language.

  • Apart from Oracle, PL/SQL is available in TimesTen in-memory database and IBM DB2.

Features of PL/SQL

PL/SQL has the following features −

  • PL/SQL is tightly integrated with SQL.
  • It offers extensive error checking.
  • It offers numerous data types.
  • It offers a variety of programming structures.
  • It supports structured programming through functions and procedures.
  • It supports object-oriented programming.
  • It supports the development of web applications and server pages.

Advantages of PL/SQL

PL/SQL has the following advantages −

  • SQL is the standard database language and PL/SQL is strongly integrated with SQL. PL/SQL supports both static and dynamic SQL. Static SQL supports DML operations and transaction control from PL/SQL block. In Dynamic SQL, SQL allows embedding DDL statements in PL/SQL blocks.

  • PL/SQL allows sending an entire block of statements to the database at one time. This reduces network traffic and provides high performance for the applications.

  • PL/SQL gives high productivity to programmers as it can query, transform, and update data in a database.

  • PL/SQL saves time on design and debugging by strong features, such as exception handling, encapsulation, data hiding, and object-oriented data types.

  • Applications written in PL/SQL are fully portable.

  • PL/SQL provides high security level.

  • PL/SQL provides access to predefined SQL packages.

  • PL/SQL provides support for Object-Oriented Programming.

  • PL/SQL provides support for developing Web Applications and Server Pages.

PL/SQL – Environment Setup

In this chapter, we will discuss the Environment Setup of PL/SQL. PL/SQL is not a standalone programming language; it is a tool within the Oracle programming environment. SQL* Plus is an interactive tool that allows you to type SQL and PL/SQL statements at the command prompt. These commands are then sent to the database for processing. Once the statements are processed, the results are sent back and displayed on screen.

To run PL/SQL programs, you should have the Oracle RDBMS Server installed in your machine. This will take care of the execution of the SQL commands. The most recent version of Oracle RDBMS is 11g. You can download a trial version of Oracle 11g from the following link −

Download Oracle 11g Express Edition

You will have to download either the 32-bit or the 64-bit version of the installation as per your operating system. Usually there are two files. We have downloaded the 64-bit version. You will also use similar steps on your operating system, does not matter if it is Linux or Solaris.

  • win64_11gR2_database_1of2.zip

  • win64_11gR2_database_2of2.zip

After downloading the above two files, you will need to unzip them in a single directory database and under that you will find the following sub-directories −

Oracle Sub Directries

Step 1

Let us now launch the Oracle Database Installer using the setup file. Following is the first screen. You can provide your email ID and check the checkbox as shown in the following screenshot. Click the Next button.

Oracle Install 1

Step 2

You will be directed to the following screen; uncheck the checkbox and click the Continue button to proceed.

Oracle install error

Step 3

Just select the first option Create and Configure Database using the radio button and click the Next button to proceed.

Oracle Install 2

Step 4

We assume you are installing Oracle for the basic purpose of learning and that you are installing it on your PC or Laptop. Thus, select the Desktop Class option and click the Next button to proceed.

Oracle Install 3

Step 5

Provide a location, where you will install the Oracle Server. Just modify the Oracle Base and the other locations will set automatically. You will also have to provide a password; this will be used by the system DBA. Once you provide the required information, click the Next button to proceed.

Oracle Install 4

Step 6

Again, click the Next button to proceed.

Oracle Install 5

Step 7

Click the Finish button to proceed; this will start the actual server installation.

Oracle Install 6

Step 8

This will take a few moments, until Oracle starts performing the required configuration.

Oracle Install 7

Step 9

Here, Oracle installation will copy the required configuration files. This should take a moment −

Oracle Configuration

Step 10

Once the database files are copied, you will have the following dialogue box. Just click the OK button and come out.

Oracle Configuration

Step 11

Upon installation, you will have the following final window.

Oracle Install 8

Final Step

It is now time to verify your installation. At the command prompt, use the following command if you are using Windows −

sqlplus "/ as sysdba"

You should have the SQL prompt where you will write your PL/SQL commands and scripts −

PL/SQL Command Prompt

Text Editor

Running large programs from the command prompt may land you in inadvertently losing some of the work. It is always recommended to use the command files. To use the command files −

  • Type your code in a text editor, like Notepad, Notepad+, or EditPlus, etc.

  • Save the file with the .sql extension in the home directory.

  • Launch the SQL*Plus command prompt from the directory where you created your PL/SQL file.

  • Type @file_name at the SQL*Plus command prompt to execute your program.

If you are not using a file to execute the PL/SQL scripts, then simply copy your PL/SQL code and right-click on the black window that displays the SQL prompt; use the paste option to paste the complete code at the command prompt. Finally, just press Enter to execute the code, if it is not already executed.

PL/SQL – Basic Syntax

In this chapter, we will discuss the Basic Syntax of PL/SQL which is a block-structured language; this means that the PL/SQL programs are divided and written in logical blocks of code. Each block consists of three sub-parts −

S.No Sections & Description
1

Declarations

This section starts with the keyword DECLARE. It is an optional section and defines all variables, cursors, subprograms, and other elements to be used in the program.

2

Executable Commands

This section is enclosed between the keywords BEGIN and END and it is a mandatory section. It consists of the executable PL/SQL statements of the program. It should have at least one executable line of code, which may be just a NULL command to indicate that nothing should be executed.

3

Exception Handling

This section starts with the keyword EXCEPTION. This optional section contains exception(s) that handle errors in the program.

Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested within other PL/SQL blocks using BEGIN and END. Following is the basic structure of a PL/SQL block −

DECLARE 
   <declarations section> 
BEGIN 
   <executable command(s)>
EXCEPTION 
   <exception handling> 
END;

The ‘Hello World’ Example

DECLARE 
   message  varchar2(20):= 'Hello, World!'; 
BEGIN 
   dbms_output.put_line(message); 
END; 
/ 

The end; line signals the end of the PL/SQL block. To run the code from the SQL command line, you may need to type / at the beginning of the first blank line after the last line of the code. When the above code is executed at the SQL prompt, it produces the following result −

Hello World  

PL/SQL procedure successfully completed.

The PL/SQL Identifiers

PL/SQL identifiers are constants, variables, exceptions, procedures, cursors, and reserved words. The identifiers consist of a letter optionally followed by more letters, numerals, dollar signs, underscores, and number signs and should not exceed 30 characters.

By default, identifiers are not case-sensitive. So you can use integer or INTEGER to represent a numeric value. You cannot use a reserved keyword as an identifier.

The PL/SQL Delimiters

A delimiter is a symbol with a special meaning. Following is the list of delimiters in PL/SQL −

Delimiter Description
+, -, *, / Addition, subtraction/negation, multiplication, division
% Attribute indicator
Character string delimiter
. Component selector
(,) Expression or list delimiter
: Host variable indicator
, Item separator
Quoted identifier delimiter
= Relational operator
@ Remote access indicator
; Statement terminator
:= Assignment operator
=> Association operator
|| Concatenation operator
** Exponentiation operator
<<, >> Label delimiter (begin and end)
/*, */ Multi-line comment delimiter (begin and end)
Single-line comment indicator
.. Range operator
<, >, <=, >= Relational operators
<>, ‘=, ~=, ^= Different versions of NOT EQUAL

The PL/SQL Comments

Program comments are explanatory statements that can be included in the PL/SQL code that you write and helps anyone reading its source code. All programming languages allow some form of comments.

The PL/SQL supports single-line and multi-line comments. All characters available inside any comment are ignored by the PL/SQL compiler. The PL/SQL single-line comments start with the delimiter — (double hyphen) and multi-line comments are enclosed by /* and */.

DECLARE 
   -- variable declaration 
   message  varchar2(20):= 'Hello, World!'; 
BEGIN 
   /* 
   *  PL/SQL executable statement(s) 
   */ 
   dbms_output.put_line(message); 
END; 
/

When the above code is executed at the SQL prompt, it produces the following result −

Hello World

PL/SQL procedure successfully completed.

PL/SQL Program Units

A PL/SQL unit is any one of the following −

  • PL/SQL block
  • Function
  • Package
  • Package body
  • Procedure
  • Trigger
  • Type
  • Type body

Each of these units will be discussed in the following chapters.

PL/SQL – Data Types

In this chapter, we will discuss the Data Types in PL/SQL. The PL/SQL variables, constants and parameters must have a valid data type, which specifies a storage format, constraints, and a valid range of values. We will focus on the SCALAR and the LOB data types in this chapter. The other two data types will be covered in other chapters.

S.No Category & Description
1

Scalar

Single values with no internal components, such as a NUMBER, DATE, or BOOLEAN.

2

Large Object (LOB)

Pointers to large objects that are stored separately from other data items, such as text, graphic images, video clips, and sound waveforms.

3

Composite

Data items that have internal components that can be accessed individually. For example, collections and records.

4

Reference

Pointers to other data items.

PL/SQL Scalar Data Types and Subtypes

PL/SQL Scalar Data Types and Subtypes come under the following categories −

S.No Date Type & Description
1

Numeric

Numeric values on which arithmetic operations are performed.

2

Character

Alphanumeric values that represent single characters or strings of characters.

3

Boolean

Logical values on which logical operations are performed.

4

Datetime

Dates and times.

PL/SQL provides subtypes of data types. For example, the data type NUMBER has a subtype called INTEGER. You can use the subtypes in your PL/SQL program to make the data types compatible with data types in other programs while embedding the PL/SQL code in another program, such as a Java program.

PL/SQL Numeric Data Types and Subtypes

Following table lists out the PL/SQL pre-defined numeric data types and their sub-types −

S.No Data Type & Description
1

PLS_INTEGER

Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32 bits

2

BINARY_INTEGER

Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32 bits

3

BINARY_FLOAT

Single-precision IEEE 754-format floating-point number

4

BINARY_DOUBLE

Double-precision IEEE 754-format floating-point number

5

NUMBER(prec, scale)

Fixed-point or floating-point number with absolute value in range 1E-130 to (but not including) 1.0E126. A NUMBER variable can also represent 0

6

DEC(prec, scale)

ANSI specific fixed-point type with maximum precision of 38 decimal digits

7

DECIMAL(prec, scale)

IBM specific fixed-point type with maximum precision of 38 decimal digits

8

NUMERIC(pre, secale)

Floating type with maximum precision of 38 decimal digits

9

DOUBLE PRECISION

ANSI specific floating-point type with maximum precision of 126 binary digits (approximately 38 decimal digits)

10

FLOAT

ANSI and IBM specific floating-point type with maximum precision of 126 binary digits (approximately 38 decimal digits)

11

INT

ANSI specific integer type with maximum precision of 38 decimal digits

12

INTEGER

ANSI and IBM specific integer type with maximum precision of 38 decimal digits

13

SMALLINT

ANSI and IBM specific integer type with maximum precision of 38 decimal digits

14

REAL

Floating-point type with maximum precision of 63 binary digits (approximately 18 decimal digits)

Following is a valid declaration −

DECLARE 
   num1 INTEGER; 
   num2 REAL; 
   num3 DOUBLE PRECISION; 
BEGIN 
   null; 
END; 
/ 

When the above code is compiled and executed, it produces the following result −

PL/SQL procedure successfully completed 

PL/SQL Character Data Types and Subtypes

Following is the detail of PL/SQL pre-defined character data types and their sub-types −

S.No Data Type & Description
1

CHAR

Fixed-length character string with maximum size of 32,767 bytes

2

VARCHAR2

Variable-length character string with maximum size of 32,767 bytes

3

RAW

Variable-length binary or byte string with maximum size of 32,767 bytes, not interpreted by PL/SQL

4

NCHAR

Fixed-length national character string with maximum size of 32,767 bytes

5

NVARCHAR2

Variable-length national character string with maximum size of 32,767 bytes

6

LONG

Variable-length character string with maximum size of 32,760 bytes

7

LONG RAW

Variable-length binary or byte string with maximum size of 32,760 bytes, not interpreted by PL/SQL

8

ROWID

Physical row identifier, the address of a row in an ordinary table

9

UROWID

Universal row identifier (physical, logical, or foreign row identifier)

PL/SQL Boolean Data Types

The BOOLEAN data type stores logical values that are used in logical operations. The logical values are the Boolean values TRUE and FALSE and the value NULL.

However, SQL has no data type equivalent to BOOLEAN. Therefore, Boolean values cannot be used in −

  • SQL statements
  • Built-in SQL functions (such as TO_CHAR)
  • PL/SQL functions invoked from SQL statements

PL/SQL Datetime and Interval Types

The DATE datatype is used to store fixed-length datetimes, which include the time of day in seconds since midnight. Valid dates range from January 1, 4712 BC to December 31, 9999 AD.

The default date format is set by the Oracle initialization parameter NLS_DATE_FORMAT. For example, the default might be ‘DD-MON-YY’, which includes a two-digit number for the day of the month, an abbreviation of the month name, and the last two digits of the year. For example, 01-OCT-12.

Each DATE includes the century, year, month, day, hour, minute, and second. The following table shows the valid values for each field −

Field Name Valid Datetime Values Valid Interval Values
YEAR -4712 to 9999 (excluding year 0) Any nonzero integer
MONTH 01 to 12 0 to 11
DAY 01 to 31 (limited by the values of MONTH and YEAR, according to the rules of the calendar for the locale) Any nonzero integer
HOUR 00 to 23 0 to 23
MINUTE 00 to 59 0 to 59
SECOND 00 to 59.9(n), where 9(n) is the precision of time fractional seconds 0 to 59.9(n), where 9(n) is the precision of interval fractional seconds
TIMEZONE_HOUR -12 to 14 (range accommodates daylight savings time changes) Not applicable
TIMEZONE_MINUTE 00 to 59 Not applicable
TIMEZONE_REGION Found in the dynamic performance view V$TIMEZONE_NAMES Not applicable
TIMEZONE_ABBR Found in the dynamic performance view V$TIMEZONE_NAMES Not applicable

PL/SQL Large Object (LOB) Data Types

Large Object (LOB) data types refer to large data items such as text, graphic images, video clips, and sound waveforms. LOB data types allow efficient, random, piecewise access to this data. Following are the predefined PL/SQL LOB data types −

Data Type Description Size
BFILE Used to store large binary objects in operating system files outside the database. System-dependent. Cannot exceed 4 gigabytes (GB).
BLOB Used to store large binary objects in the database. 8 to 128 terabytes (TB)
CLOB Used to store large blocks of character data in the database. 8 to 128 TB
NCLOB Used to store large blocks of NCHAR data in the database. 8 to 128 TB

PL/SQL User-Defined Subtypes

A subtype is a subset of another data type, which is called its base type. A subtype has the same valid operations as its base type, but only a subset of its valid values.

PL/SQL predefines several subtypes in package STANDARD. For example, PL/SQL predefines the subtypes CHARACTER and INTEGER as follows −

SUBTYPE CHARACTER IS CHAR; 
SUBTYPE INTEGER IS NUMBER(38,0);

You can define and use your own subtypes. The following program illustrates defining and using a user-defined subtype −

DECLARE 
   SUBTYPE name IS char(20); 
   SUBTYPE message IS varchar2(100); 
   salutation name; 
   greetings message; 
BEGIN 
   salutation := 'Reader '; 
   greetings := 'Welcome to the World of PL/SQL'; 
   dbms_output.put_line('Hello ' || salutation || greetings); 
END; 
/ 

When the above code is executed at the SQL prompt, it produces the following result −

Hello Reader Welcome to the World of PL/SQL 
 
PL/SQL procedure successfully completed. 

NULLs in PL/SQL

PL/SQL NULL values represent missing or unknown data and they are not an integer, a character, or any other specific data type. Note that NULL is not the same as an empty data string or the null character value