PLSQL Syntax
PLSQL Syntax
PL/SQL SYNTAX
PL/SQL stands for “Procedural Language extensions to the Structured Query
Language”. SQL is a popular language for both querying and updating data in
the relational database management systems (RDBMS).
PL/SQL architecture
1
PL/SQL engine is in charge of compiling PL/SQL code into byte-code and
executes the executable code. The PL/SQL engine can only be installed in an
Oracle Database server or an application development tool such as Oracle
Forms.
Once you submit a PL/SQL block to the Oracle Database server, the PL/SQL
engine collaborates with the SQL engine to compile and execute the code.
PL/SQL engine runs the procedural elements while the SQL engine processes
the SQL statements.
You will learn about the PL/SQL anonymous block and how to execute it using
SQL*Plus and SQL Developer tools.
2
A PL/SQL block has a name. Functions or Procedures is an example of a
named block. A named block is stored into the Oracle Database server and
can be reused later.
1) Declaration section
A PL/SQL block has a declaration section where you declare variables, allocate
memory for cursors, and define data types.
2) Executable section
3
A PL/SQL block has an exception-handling section that starts with the
keyword EXCEPTION. The exception-handling section is where you catch and
handle exceptions raised by the code in the execution section.
Note a block itself is an executable statement, therefore you can nest a block
within other blocks.
The following example shows a simple PL/SQL anonymous block with one
executable section.
BEGIN
DBMS_OUTPUT.put_line ('Hello World!');
END;
Once you have the code of an anonymous block, you can execute it using
SQL*Plus, which is a command-line interface for executing SQL statement and
PL/SQL blocks provided by Oracle Database.
First, connect to the Oracle Database server using a username and password.
Second, turn on the server output using the SET SERVEROUTPUT ON command so
that the DBMS_OUTPUT.PUT_LINE procedure will display text on the screen.
Third, type the code of the block and enter a forward slash ( /) to instruct
SQL*Plus to execute the block. Once you type the forward-slash (/), SQL*Plus
4
will execute the block and display the Hello World message on the screen as
shown in the illustrations.
Note that you must execute SET SERVEROUTPUT ON command in every session
that you connect to the Oracle Database in order to show the message using
the DBMS_OUTPUT.PUT_LINE procedure.
To execute the block that you have entered again, you use / command instead
of typing everything from the scratch:
First, connect to the Oracle Database server using Oracle SQL Developer.
5
Third, enter the PL/SQL code and execute it by clicking the Execute button or
pressing the Ctrl-Enter keyboard shortcut.
6
More PL/SQL anonymous block examples
In this example, we first declare a variable l_message that holds the greeting
message. And then, in the execution section, we use
the DBMS_OUTPUT.PUTLINE procedure to show the content of this variable
instead of using a literal string.
DECLARE
l_message VARCHAR2( 255 ) := 'Hello World!';
BEGIN
DBMS_OUTPUT.PUT_LINE( l_message );
END;
Here is the output:
1 Hello World!
The next anonymous block example adds an exception-handling section which
catches ZERO_DIVIDE exception raised in the executable section and displays
an error message.
1 DECLARE
2 v_result NUMBER;
3 BEGIN
4 v_result := 1 / 0;
5 EXCEPTION
7
6 WHEN ZERO_DIVIDE THEN
7 DBMS_OUTPUT.PUT_LINE( SQLERRM );
8 END;
The error mesage is:
The SQLERRM function returns the error message associated with the most
recently raised error exception. This function should only be used within the
Exception Handling section of your code.
Oracle Data Types
In this section, you will get a brief overview of the PL/SQL data types including
numbers, Boolean, character, and datetime.
Each value in PL/SQL such as a constant, variable and parameter has a data
type that determines the storage format, valid values and allowed operations.
PL/SQL has two kinds of data types: scalar and composite. The scalar types
are types that store single values such as number, Boolean, character, and
datetime whereas the composite types are types that store multiple values, for
example, record and collection.
This section explains the scalar data types that store values with no internal
components.
Number
Boolean
Character
Datetime
A scalar data type may have subtypes. A subtype is a data type that is a subset
of another data type, which is its base type. A subtype further defines a base
type by restricting the value or size of the base data type.
8
Note that PL/SQL scalar data types include SQL data types and its own data
type such as Boolean.
The numeric data types represent real numbers, integers, and floating-point
numbers. They are stored as NUMBER, IEEE floating-point storage types
(BINARY_FLOAT and BINARY_DOUBLE), and PLS_INTEGER.
The data types NUMBER, BINARY_FLOAT, and BINARY_DOUBLE are SQL data types.
The PLS_INTEGER datatype is specific to PL/SQL. It represents signed 32 bits
integers that range from -2,147,483,648 to 2,147,483,647.
Because PLS_INTEGER datatype uses hardware arithmetic, they are faster
than NUMBER operations, which uses software arithmetic.
In addition, PLS_INTEGER values require less storage than NUMBER. Hence, you
should always use PLS_INTEGER values for all calculation in its range to increase
the efficiency of programs.
The PLS_INTEGER datatype has the following predefined subtypes:
PLS_INTEGER Description
subtypes
NATURAL Represents nonnegative PLS_INTEGER values
NATURALN Represents nonnegative PLS_INTEGER values with NOT
NULL constraint
The BOOLEAN datatype has three data values: TRUE, FALSE, and NULL.
Boolean values are typically used in control flow structure such as IF-
THEN, CASE, and loop statements like LOOP, FOR LOOP, and WHILE LOOP.
SQL does not have the BOOLEAN data type, therefore, you cannot:
9
Use a BOOLEAN value in
the DBMS_OUTPUT.PUTLINE and DBMS_OUTPUT.PUT subprograms.
Character data types
The character data types represent alphanumeric text. PL/SQL uses the SQL
character data types such as CHAR, VARCHAR2, LONG, RAW, LONG RAW, ROWID,
and UROWID.
The datetime data types represent dates, timestamp with or without time zone
and intervals. PL/SQL datetime data types
are DATE, TIMESTAMP, TIMESTAMP WITH TIME ZONE, TIMESTAMP WITH LOCAL
TIME ZONE, INTERVAL YEAR TO MONTH, and INTERVAL DAY TO SECOND.
Data type synonyms
Data types have synonyms for compatibility with non-Oracle data sources such
as IBM Db2, SQL Server. And it is not a good practice to use data type
synonym unless you are accessing a non-Oracle Database.
PL/SQL Comments
In this section, you will learn how to use PL/SQL comments including single-
line and multi-line comments that allow you to improve the readability of your
code.
10
PL/SQL comments allow you to describe the purpose of a line or a block of
PL/SQL code.
When compiling the PL/SQL code, the Oracle pre-compiler ignores comments.
However, you should always use comments to make your code more readable
and to help you and other developers understand it better in the future.
Single-line comments
A single-line comment starts with a double hyphen ( --) that can appear
anywhere on a line and extends to the end of the line.
For example, the following single-line comment explains the meaning of
the co_vat_rate constant:
1 -- valued added tax 10%
2 DECLARE co_vat_rate CONSTANT NUMBER := 0.1;
If you want to comment just potion of a line, you can also use the single-line
comment. The following example shows how to comment out
the WHERE clause of the UPDATE statement. All the code which follows the
double-hyphen -- to the rest of the line will be treated as a comment:
1 UPDATE products SET list_price = 0; -- WHERE product_id = l_id;
Note that we add the semicolon (;) before the (--) to make the statement valid.
Multi-line comments
11
1 /* A multi-line comment can be used as a single-line comment */
1 /*
2 This code allow users to enter the customer id and
3 return the corresponding customer name and credit limit
4 */
5 DECLARE
6 l_customer_name [Link]%TYPE;
7 l_credit_limit customers.credit_limit%TYPE;
8 BEGIN
9 ...
10 END;
11 /
1 BEGIN
2 -- single-line comment /* another comment */
3 NULL;
4 /*
5 multi-line comment
6 -- that has another single-line comment
7 */
8 END;
9/
1 BEGIN
2 -- single-line comment, another comment
12
3 NULL;
4 /*
5 multi-line comment
6 that has another single-line comment
7 */
8 END;
9/
PL/SQL does not allow you to nest a multi-line comment within another multi-
line comment. The following code block is not valid:
1 BEGIN
2 /*
3 a multi-line comment
4 /*
5 a nested multi-line comment
6 */
7 */ -- -> error
8 END;
9/
For a PL/SQL block that will be processed dynamically, you cannot use single-
line comments. Because Oracle precompiler will ignore the end-of-line
characters that cause the single-line comments extend to the end of the block.
In this case, you can use multi-line comments instead.
In this tutorial, you have learned about PL/SQL comments including single-
line and multi-line comments that allow you to document the purpose of your
code
13
and also we can use this language to create a database. SQL uses certain
commands like Create, Drop, and Insert etc. to carry out the required tasks.
These SQL commands are mainly categorized into four categories as:
1. DDL – Data Definition Language
2. DQl – Data Query Language
3. DML – Data Manipulation Language
4. DCL – Data Control Language
5. TCL-Transaction Control Language
3. DML (Data Manipulation Language): The SQL commands that deals with
the manipulation of data present in the database belong to DML or Data
Manipulation Language and this includes most of the SQL statements.
Examples of DML:
INSERT – is used to insert data into a table.
UPDATE – is used to update existing data within a table.
DELETE – is used to delete records from a database table.
4. DCL (Data Control Language): DCL includes commands such as GRANT
and REVOKE which mainly deals with the rights, permissions and other
controls of the database system.
Examples of DCL commands:
GRANT-gives user’s access privileges to database.
14
REVOKE-withdraw user’s access privileges given by using the GRANT
command.
ORACLE DDL
Create Table
The person_id is the identity column that identifies unique rows in the table. The
data type of the person_id column is NUMBER. The clause GENERATED BY DEFAULT
AS IDENTITY instructs Oracle to generate a new integer for the column whenever
a new row is inserted into the table.
15
1 ALTER TABLE table_name action;
The ALTER TABLE statement allows you to:
We will use the persons table that we created in the previous tutorial for the
demonstration
For example, the following statement adds a new column named birthdate to
the persons table:
If you view the persons table, you will see that the birthdate column is
appended at the end of the column list:
DESC persons;
16
To add multiple columns to a table at the same time, you place the new
columns inside the parenthesis as follows:
ALTER TABLE table_name
ADD (
column_name type constraint,
column_name type constraint,
...
);
DESC persons
17
column_1 type constraint,
...);
For example, the following statement changes the phone and email column
to NOT NULL columns and extends the length of the email column to 255
characters:
ALTER TABLE persons MODIFY(
phone VARCHAR2(20) NOT NULL,
email VARCHAR2(255) NOT NULL
);
To remove an existing column from a table, you use the following syntax:
This statement deletes the column from the table structure and also the data
stored in that column.
The following example removes the birthdate column from the persons table:
To drop multiple columns at the same time, you use the syntax below:
For example, the following statement removes the phone and email columns
from the persons table:
ALTER TABLE persons
DROP
( email, phone );
Since version 9i, Oracle added a clause for rename a column as follows:
18
For example, the following statement renames the first_name column
to forename column:
ALTER TABLE persons
RENAME COLUMN first_name TO forename;
For example, the statement below renames the persons table to people table:
Oracle SELECT statement is used to fetch the data from a database table
which returns data in the form of result table. These result tables are called
result-sets.
Syntax
SQL DISTINCT Clause: produces a list of only those values that are different
from one another SELECT DISTINCT column1, column2....columnN FROM
table_name;
SQL WHERE Clause: You can select partial table contents by placing
restrictions on the rows to be included in the output.
19
This is done by using the WHERE clause to add conditional restrictions to the
SELECT statement. SELECT column1, column2....columnN FROM table_name
WHERE CONDITION;
SQL IN Clause: Used to check whether an attribute value matches any value
within a value list SELECT column1, column2....columnN FROM table_name
WHERE column_name IN (val-1, val-2,...val-N);
SQL LIKE Clause: Used to check whether an attribute value matches a given
string pattern.
Standard SQL allows you to use the percent sign (%) and underscore (_)
wildcard characters to make matches when the entire string is not known:
Oracle ORDER BY clause In Oracle, a table stores its rows in unspecified order
regardless of the order which rows were inserted into the database.
SELECT country_id, city, state FROM locations ORDER BY state ASC NULLS
LAST;
20
You don’t need to specify the column names for sorting the data. If you prefer,
you can use the positions of the column in the ORDER BY clause. See the
following statement:
Oracle DELETE
1
INSERT INTO table_name (column_list) VALUES( value_list);
2
INSERT INTO target_table (col1, col2, col3) SELECT col1, col2, col3 FROM
source_table WHERE condition;
The Oracle INSERT INTO SELECT statement requires the data type of the source
and target tables match.
21
8 PRIMARY KEY(customer_id,
9 product_id,
order_date)
);
To insert multiple rows into a table, you use the following Oracle INSERT
ALL statement:
1 INSERT ALL
2 INTO table_name(col1,col2,col3) VALUES(val1,val2, val3)
3 INTO table_name(col1,col2,col3) VALUES(val4,val5, val6)
4 INTO table_name(col1,col2,col3) VALUES(val7,val8, val9)
5 Subquery;
INSERT ALL
INTO fruits(fruit_name, color)
VALUES ('Apple','Red')
The following shows the syntax of the conditional multi table insert statement:
22
4 WHEN condition2 THEN
5 INTO table_2(column_list ) VALUES (value_list)
6 ELSE
7 INTO table_3(column_list ) VALUES (value_list)
8 Subquery
It can be used to insert data into tables only, not views or materialized
view.
It cannot be used to insert data into remote tables.
The number of columns in all the INSERT INTO clauses must not exceed
999.
A table collection expression cannot be used in a multi table insert
statement.
The subquery of the multitable insert statement cannot use a sequence.
UPDATE table_name
SET column1 = value1, column2 =value2, column3 =value3, WHERE condition;
UPDATE parts
SET lead_time = 30, cost = 120, status = 1 WHERE part_id = 5;
23