PLSQL
PLSQL
[Chennai],
[30/01/2023] - [03-02-2023]
Agenda
3 Records, Cursors
7 Collections
4 Stored Procedures,
Functions, Packages 8 Autonomous Transactions,
Dynamic SQL
2
Introduction to PL/SQL
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 adds many procedural constructs to SQL language to overcome some limitations of SQL. Besides,
PL/SQL provides a more comprehensive programming language solution for building mission-critical
applications on Oracle Databases.
3
PL/SQL Architecture
PL/SQL Architecture
4
PL/SQL Anonymous Block
PL/SQL Anonymous Block
5
SELECT INTO
PL/SQL SELECT INTO examples
Let’s use the customers and contacts tables in the sample database for demonstration.
6
PL/SQL Cursor
A cursor is a pointer that points to a result of a query. PL/SQL has two types of cursors: implicit cursors and
explicit cursors.
7
PL/SQL Cursor
PL/SQL cursor example
We will use the orders and order_items tables from the sample database for the demonstration.
8
PL/SQL Procedure
A PL/SQL procedure is a reusable unit that encapsulates specific business logic of the application.
Technically speaking, a PL/SQL procedure is a named block stored as a schema object in the Oracle
Database.
[declaration statements]
BEGIN
[execution statements]
EXCEPTION
[exception handler]
END [procedure_name ];
9
PL/SQL Function
PL/SQL function is a reusable program unit stored as a schema object in the Oracle Database. The
following illustrates the syntax for creating a function:
[declarative section]
BEGIN
[executable section]
[EXCEPTION]
[exception-handling section]
END;
10
What is a PL/SQL package?
A package is a schema object that contains definitions for a group of related functionalities. A package
includes variables, constants, cursors, exceptions, procedures, functions, and subprograms. It is compiled
and stored in the Oracle Database.
11
Why PACKAGE?
12
PL/SQL - PACKAGE
A PL/SQL package has two parts: package specification and package body.
A package specification does not contain any implementations of the public items. For example, in case
of procedures or functions, the package specification contains only their headers, but not their bodies.
A package specification can exist independently if their items do not require implementations.
Procedures
Functions
Cursors
Types, variables, and constants
Records
CollectionsSQL is a tool for organizing, managing, and retrieving data stored by a computer database.
13
Triggers
A trigger is a set of SQL statements that reside in system memory with unique names. It is a specialized
category of stored procedure that is called automatically when a database server event occurs. Each trigger is
always associated with a table.
The following are the main characteristics that distinguish triggers from stored procedures:
Triggers will be helpful when we need to execute some events automatically on certain desirable scenarios.
14
Triggers
15
Triggers
DML Triggers - Two Triggers
After Triggers
Instead Of Triggers
16
Triggers
After Triggers
17
Triggers
Instead of Triggers
18
Triggers
Logon Triggers
Logon triggers are fires in response to a LOGON event. The LOGON event occurs when a user session is
generated with an SQL Server instance, which is made after the authentication process of logging is completed
but before establishing a user session.
19
PL/SQL Collections
PL/SQL Associative Array
PL/SQL Associative Array
PL/SQL Associative Array
Associative arrays are single-dimensional, unbounded, sparse collections of homogeneous elements.
First, an associative array is single-dimensional. It means that an associative array has a single column of data
in each row, which is similar to a one-dimension array.
Second, an associative array is unbounded, meaning that it has a predetermined limits number of elements.
Third, an associative array is sparse because its elements are not sequential. In other words, an associative
array may have gaps between elements.
20
PL/SQL Coding Guidelines
All PL/SQL functions and procedures will be implemented as part of a package. The package
names used will be specified in the component specification.
Source Files
Package headers and bodies will be declared in separate files. Package header file names will
use the ‘pkg’ extension. Package body file names will use the ‘.pkb’ extension.
Trigger code will be declared in a single file with the extension ‘.trg’.
21
PL/SQL Coding Guidelines
Header Comments
Package header source files will contain a package level comment which includes the following
information: FileName, Component Name, Description, Package Name, Designer Name,
Developer Name, Version, Date and Copyright statement. The format below will be followed
exactly.
/**********************************************************************
/*
/* Filename: TopCoder_Unit_Test.pkg
/* Component: Unit_Test_Framework
/* Package: Unit_Test_Frmwrk
/* Designer: TCSDesigner
/* Developer: TCSDeveloper
/* Version: 1.0
/* Copyright (c) 2006, TopCoder, Inc. All rights reserved.
/*
/* Description: Description of PL/SQL package...
/*
/**********************************************************************
22
PL/SQL Coding Guidelines
Function/Procedure Comments
The package header source file will document each function in the following format:
/*********************************************************************
/**
/** Function: get_employee_ssn
Confidential ©TopCoder Software, Inc. 2002 Page 2
/** In: p_employee_id – the id of the employee to search for
/** Returns: the Social Security Number for the employee
/**
/*********************************************************************
The package header source file will document each procedure in the following format:
/*********************************************************************
/**
/** Procedure: ins_employee
/** Out: p_employee_id – the id of the newly created employee.
/** In: p_ssn – the Social Security Number of the employee to
/** insert.
/** In: p_name – the name of the employee to insert.
/**
/********************************************************************* 23
PL/SQL Coding Guidelines
The possible parameter types are ‘In’, ‘Out’ and ‘InOut’. These comments will be used at a later
time by an automated comment generator (possibly RoboDoc) to generate HTML package
documentation.
24
PL/SQL Coding Guidelines
Maximum Line Length
No single line of code in a PL/SQL component will exceed 120 characters in length.
Indentation
Indentation will be 0 spaces for the outermost block and 3 spaces from the indentation level of
each enclosing block.
Alignment
Comma separated lists will be ‘stacked’ and aligned as shown below:
SELECT SUM(A)
,B
,C
FROM TABLE1
WHERE B = 5
GROUP BY B
,C
25
PL/SQL Coding Guidelines
Conditional Blocks
In a conditional, the ‘THEN’ keyword will be placed on the line below the ‘IF’ but aligned with it.
‘ELSEIF’ keywords will also be aligned with the ‘IF’.
Example:
IF l_total > lc_max
THEN
l_new_max := true;
ELSIF l_total = lc_max
THEN
l_new_max := false;
END IF;
26
PL/SQL Coding Guidelines
Reserved Words
SQL and PL/SQL reserved words (SELECT, INSERT, PACKAGE, FUNCTION, etc) will be
capitalized.
Confidential ©TopCoder Software, Inc. 2002 Page 3
Variable Names
Variable names will be all lower case, with individual words separated by an underscore. The
following standard prefixes will be used:
27
PL/SQL Coding Guidelines
Variable Types
Subtypes
When there’s no direct correlation between a variable and table column variable restrictions will
not be hard-coded. The developer will use ‘SUBTYPE’ to standardize data types.
Example:
CREATE OR REPLACE PACKAGE team_data
SUBTYPE total_win_count_t IS INTEGER(10);
…
DECLARE
l_win_count team_data.total_win_count_t;
28
PL/SQL Coding Guidelines
Variable Initialization
Variables will only be initialized in the ‘DECLARE’ section when that initialization doesn’t require a
function call or complex logic. When the variable must be initialized via a function call or complex
logic, it will be done in the executable section of the procedure or function.
29
PL/SQL Debugging
Before you Debug
30
PL/SQL Debugging
2. If you don't have the required DEBUG privileges, a SYSDBA role user has to assign them. Login as a SYSDBA
user.
3.Execute the grant commands and ACL(Access Control List) script shown as a SYSDBA user.
31
PL/SQL Debugging
4. Now login as hr user, who has a non-sysdba user role
5. Execute the SQL statement shown to check whether required privileges are granted to hr user.
32
PL/SQL Debugging
Debugging
4. To see how debug works, you create a break point. Click the line number 7.
33
PL/SQL Debugging
34
PL/SQL Debugging
5. When a break point is created at line 7, the execution will break at line 7 and allows developer to monitor
the data held in different variables. Click the Debug icon.
7. The debugger is running and has stopped at line 8. Click the Smart Data tab. The Smart Data tab holds the
values of variables in the PL/SQL block. These are currently set to NULL.
35
PL/SQL Debugging
8. You can see all the data manipulated in the procedure in the Data tab. You see that the current
values of l_salary and l_commission are NULL.
36
PL/SQL Debugging
9. Click the Step Over icon to move to the next statement in the procedure.
37
PL/SQL Debugging
10. Notice the values for l_salary and l_commission have changed to the existing values in the database, as the
execution of select statement is complete, you can see the values from the database are fetched into the
variables in the procedure.
38
PL/SQL Debugging
11. Click the Step Over icon again to move to the next statement.As the execution of the update statement
completes, you can see the new values of salary and commission in the Data tab.
39
PL/SQL Debugging
12. Notice that the debugger moved to the next statement in the procedure. You want to run the rest of the
procedure, click the Resume icon.
40
PL/SQL Debugging
13. Procedure execution and debugging is complete. In the next topic, you create a test repository so that you
can create and run a unit test.
41
SQL Profiling
42
SQL Profiling
What is a SQL profile?
A SQL profile is a set of auxiliary information specific to a SQL statement. Conceptually, a SQL
profile is to a SQL statement what statistics are to a table or index. The database can use the
auxiliary information to improve execution plans.
A SQL profile contains corrections for poor optimizer estimates discovered by the SQL Tuning
advisor. This information can improve optimizer cardinality and selectivity estimates, which in
turn leads the optimizer to select better plans.
The SQL profile does not contain information about individual execution plans. Rather, the
optimizer has the following sources of information when choosing plans:
• The environment, which contains the database configuration, bind variable values, optimizer
statistics, data set, etc.
43
SQL Profiling
What is the main use case for SQL profiles?
SQL Tuning Advisor can recommend a profile the following types of statements:
• DML statements (SELECT, INSERT with a SELECT clause, UPDATE, and DELETE)
• CREATE TABLE statements (only with the AS SELECT clause)
• MERGE statements (the update or insert operations)
If a profile is recommended it will be in a form of a finding that allows for the profile to be
implemented. Once implemented, the database creates the profile and stores it persistently in the
data dictionary. If a user issues a statement for which a profile has been built, then the query
optimizer uses both the environment and the SQL profile to build a well-tuned plan.
44
SQL Profiling
What is the difference between SQL profiles, stored outlines,
and SQL plan baselines?
To achieve SQL plan stability in earlier releases of Oracle Database stored outlines played a
major role. In Oracle Database 11g they are still supported, however will be deprecated in the
future releases in favor of SQL plan management. The goal of SQL plan baselines (that are
generated by the SQL plan management mechanism) is to preserve the performance of
corresponding SQL statements, regardless of changes in the database.
SQL Profiles, on the other hand, were introduced in Oracle Database 10g and were supposed to
guide the Optimizer to a better plan. They do not guarantee the same plan each time the
statement is parsed.Network Databases
It is the database that typically follows the network data model. Here, the representation of data is in the form
of nodes connected via links between them.
45
SQL Profiling
What are the benefits of SQL profiles?
• Unlike hints and stored outlines, profiles do not tie the optimizer to a specific plan or subplan.
Profiles fix incorrect estimates while giving the optimizer the flexibility to pick the best plan in
different situations.
• Unlike hints, no changes to application source code are necessary when using profiles.
• The use of SQL profiles by the database is transparent to the user.
46
SQL Profiling
Test execution
47
Queries?
48
Thank you