- Explain PL/SQL, anonymous blocks vs stored procedures, and the role of the PL/SQL engine.
- List the features and advantages of PL/SQL.
- Write a PL/SQL block with declarative, executable and exception-handling parts.
- Declare variables, constants and %TYPE variables; use SELECT … INTO and the := operator.
- Use nested and labelled blocks and understand scope and visibility.
- Display output with DBMS_OUTPUT and SET SERVEROUTPUT ON.
What is PL/SQL?
PL/SQL is Oracle’s procedural language extension to SQL. It mixes SQL statements with procedural statements such as IF and loops. PL/SQL is a superset of SQL: it uses SQL for data retrieval and manipulation and its own statements for data processing.
- Anonymous block – a PL/SQL block that appears within an application (wherever SQL can appear).
- Stored procedure – a block stored in the database with a name and executed by name. Oracle also has functions (return a value) and packages (collections of procedures and functions).
PL/SQL engine
The PL/SQL engine compiles and executes PL/SQL blocks. It is available in the Oracle Server and in tools such as Oracle Forms and Oracle Reports.
Features and Advantages
Features
- Block structure – programs are blocks, which can be nested.
- Variables and constants.
- Control structures – IF, FOR, WHILE (the most important extension to SQL).
- Exception handling – errors are detected and handled.
- Modularity – procedures and functions with parameters.
- Cursors – implicit for DML and single-row SELECT; explicit for multi-row queries.
- Built-in functions – most SQL functions.
Advantages
- Support for SQL – SQL commands, functions, operators and datatypes; dynamic SQL (native dynamic SQL from Oracle8i, earlier through DBMS_SQL) besides static SQL.
- Better performance – the whole block is sent to the server as one unit, reducing network traffic.
- Portability – runs unchanged on any platform where Oracle runs.
PL/SQL Block Structure
[DECLARE declarations of variables, constants, cursors, exceptions] BEGIN executable commands -- the only mandatory part [EXCEPTION exception handlers] END;declare v_rollno number(5); v_count number(2) := 0; -- initialised v_name students.name%type; -- same type as STUDENTS.NAME done boolean := FALSE; bonus constant number(3) := 500; -- constant: cannot be changed begin null; end;
- %TYPE declares a variable with the datatype of a table column.
- If a variable and a column have the same name, SQL statements treat the name as the column (columns take precedence).
- PL/SQL datatype categories: Scalar (NUMBER, CHAR, VARCHAR2, DATE, BOOLEAN), Composite (RECORD, TABLE, VARRAY), Reference (REF CURSOR, REF object_type) and LOB (BFILE, BLOB, CLOB, NCLOB). BOOLEAN takes TRUE, FALSE or NULL.
First PL/SQL Block and SELECT … INTO
declare v_rollno students.rollno%type; begin -- roll number of the student who joined most recently select max(rollno) into v_rollno from students; insert into payments values (v_rollno, sysdate, 1000); commit; end; /
PL/SQL procedure successfully completed.
- In PL/SQL, SELECT only retrieves data; the INTO clause names the variable(s) that receive the values. The number and types of INTO variables must match the selected columns.
- Comments:
-- single lineand/* multi-line */. - Assignment uses := (e.g.
hra := bs * 0.05;). Arithmetic operators: + − * / and ** (exponentiation). - Most SQL functions work in PL/SQL statements, but DECODE and group functions (AVG, COUNT, GROUPING, MIN, MAX, SUM, STDDEV, VARIANCE) can be used only inside SQL commands within the block.
Nested Blocks, Scope, Visibility and Labels
- A block can be defined inside another block – nested blocks, each with its own declarations and exception handlers.
- Scope – the region where a variable can be used: from its declaration to the end of its block (including inner blocks).
- Visibility – a variable is visible where it can be referred to without a qualifier. An inner variable with the same name hides the outer one.
- A label
<<name>>before a block names it;label.variableaccesses a hidden variable.
<<mainblock>>
declare
n number(5);
begin
<<nestedblock>>
declare
n number(5);
begin
n := 20; -- N of the nested block
mainblock.n := 50; -- hidden N of the main block
end;
end;Displaying Output – DBMS_OUTPUT
DBMS_OUTPUT is a package (a collection of procedures and functions) supplied with Oracle. PUT writes pieces of a line; PUT_LINE writes a value followed by an end-of-line. Output appears only when the program unit has completed and SERVEROUTPUT is ON (set it in every new SQL*Plus session).
SQL> set serveroutput on
declare
v_avgfee courses.fee%type;
v_orafee courses.fee%type;
begin
select avg(fee) into v_avgfee from courses;
select fee into v_orafee from courses where ccode = 'ora';
update courses set fee = greatest(v_avgfee, v_orafee) where ccode = 'vbnet';
commit;
dbms_output.put_line('New VB.NET fee : ' || greatest(v_avgfee, v_orafee));
end;- PL/SQL = SQL + procedural constructs; the PL/SQL engine sends SQL to the SQL statement executor.
- A block has DECLARE, BEGIN (mandatory) and EXCEPTION parts.
- Use %TYPE, SELECT … INTO and := ; labels reach hidden variables.
- SET SERVEROUTPUT ON is required to see DBMS_OUTPUT.PUT_LINE output.
Chapter 15 Notes (PDF)
Question / Answer (15 questions)
Moderate-level questions based on the Chapter 15 notes (PDF). Click a question to see the answer.
MCQ Test : Check Your Understanding (5 questions)
Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.
Bibliography/References
The chapter notes PDF is the course study material and is credited to its author below. The explanations, questions and MCQs on this page are original study aids written for this course from the topics covered in that PDF. The other works are cited for verification and further reading. Oracle, SQL*Plus and PL/SQL are trademarks of Oracle Corporation; other names belong to their respective owners.
- Srikanth, P. (n.d.). Oracle For Beginners (chapter notes – the PDF shown on each chapter page). Srikanth Technologies. http://www.srikanthtechnologies.com/
- Oracle Corporation. (n.d.). Oracle Database PL/SQL Language Reference, 19c. https://docs.oracle.com/en/database/oracle/oracle-database/19/lnpls/
- Oracle Corporation. (n.d.). Oracle Database PL/SQL Packages and Types Reference, 19c. https://docs.oracle.com/en/database/oracle/oracle-database/19/arpls/
- Feuerstein, S., & Pribyl, B. (2014). Oracle PL/SQL Programming (6th ed.). O’Reilly Media.