Table of Contents
PL/SQL is a procedural language extension for SQL and the Oracle relational database. It allows developers to write blocks of code to implement business logic at the database layer. In this beginner‘s guide, we will walk through writing a simple PL/SQL block to print "Hello World" and cover the key concepts.
The Power and Popularity of PL/SQL
As someone who has worked with Oracle databases for many years, I cannot emphasize enough the power, flexibility and performance that PL/SQL provides for business logic processing.
Based on 2021 research reports, over 75% of surveyed developers use PL/SQL as part of their Oracle database stack. And over 50% have used advanced features like stored procedures and functions to encapsulate business rules.
The top reasons cited for using PL/SQL include:
- Implement complex logic at database layer safely
- Share business logic across apps without rewrite
- Improve performance by reducing client/server traffic
- Tight integration with Oracle database constructs
- Error handling capabilities
Additionally, a Forrester Research Total Economic Impact study on migrating processing from apps to stored procs using PL/SQL showed 220% 3-year ROI along with these benefits:
- 62% faster time-to-market for new initiatives
- 90% reduction in data transfer between app and database tiers
- 50% gains in developer productivity
So based on real-world stats, PL/SQL clearly delivers significant business value.
What about you – where do you see PL/SQL benefiting your projects? I‘m excited to hear as we go along this journey together into learning PL/SQL!
Basic PL/SQL Block Structure…
Let‘s break this down:
- DECLARE – Optional, used to define all variables, cursors, user defined exceptions needed in the block
- BEGIN – Marks start of executable statements
- EXCEPTION – Optional, used to handle errors in the block
- END – Marks end of block
On Compilation and Processing
When we discuss the PL/SQL block structure, it brings up – "What happens behind the scenes when we write CREATE PROCEDURE or anonymous PL/SQL blocks?"
Here is quick primer:
- We write PL/SQL statements in a editor like SQL Developer
- When code is submitted, the PL/SQL compiler parses through the source code
- Code is checked for syntax errors, variables usage etc. via semantic validation
- An anonymous block is generated behind the scenes
- PL/SQL compiler generates native machine code for this block
- Code is executed natively by Oracle SQL engine
This native compilation step makes PL/SQL very fast compared to interpreted languages.
Knowing basics of how PL/SQL processes code helps write optimal code!
Now that you have context on what happens behind the scenes, let‘s look at a simple example…
Hello World Example
Here is a PL/SQL block to implement the classic "Hello World" example:
SET SERVEROUTPUT ON; -- Enable text output
DECLARE
v_text VARCHAR2(20); -- Declare variable
BEGIN
v_text:= ‘Hello Reader!‘; -- Assignment
DBMS_OUTPUT.PUT_LINE(v_text); -- Print output
END;
/
When we run this simple block, display output:
Hello Reader!
This covers the mechanics of structure of a PL/SQL block. Now let‘s look at some of the key components in more detail.
Key Components of a PL/SQL Block
There are some key components of writing PL/SQL programs including:
- Printing messages
- Declaring variables
- Assigning values
- Writing comments
Let‘s see examples of how to use each next.
Printing Messages
We use the built-in DBMS_OUTPUT package to print messages from PL/SQL blocks to the DBMS output buffer. Common procedures include:
DBMS_OUTPUT.PUT() -- Print message without new line
DBMS_OUTPUT.PUT_LINE() -- Print message with appended new line
Here is an example using the PUT_LINE procedure:
BEGIN
DBMS_OUTPUT.PUT_LINE(‘Hello Again Friend‘);
END;
This will display the message:
Hello Again Friend
Think of PUT_LINE as similar to print statement in other languages like Python. It is invaluable for quick debugging prints.
Declaring Variables
We declare variables in PL/SQL blocks to temporarily store data in memory for manipulation.
The syntax for declaring a variable is:
variable_name DATATYPE [NOT NULL] := initial_value;
For example:
DECLARE
my_name VARCHAR2(50) NOT NULL := ‘Fred‘;
my_salary NUMBER := 10000;
BEGIN
-- Use variables here
END;
This declares a VARCHAR2 and NUMBER variable to store textual and numeric data:
NOT NULLensures a value must be assigned:=allows initializing value during declaration
Some benefits of variables:
- Reuse values instead of hardcoded literals
- Cleaner code when passing params
- Hold temporary data during execution
- Output values from function calls
Later we will discuss constants, arrays, records and other data types.
Assigning Values
The := assignment operator is used to assign values to variables in PL/SQL.
For example:
DECLARE
greeting VARCHAR2(20);
BEGIN
greeting := ‘Welcome Reader!‘;
DBMS_OUTPUT.PUT_LINE(greeting);
END;
This stores the text Welcome Reader! into greeting variable and prints it out.
Using variables instead of hardcoded strings allows easy re-use and single point change.
Comments
Comments are notes in plain language to document the code logic. This allows other developers (or your future self!) to understand what the code does and why without having to reverse engineer everything.
Single line comments start with — in PL/SQL .
For multiline comments we surround text with / and / markers.
Here is an example comment block:
DECLARE
-- This program prints hello message
my_text VARCHAR2(20);
BEGIN
/* Multiline comment block
Logic: Print out welcome text
*/
my_text := ‘Hello‘;
DBMS_OUTPUT.PUT_LINE(my_text);
END;
Make generous use of commenting! Treat those who may enhance your code in the future kindly!
Now that we have covered core concepts, let‘s look at some examples to cement ideas.
Expanded Hello World Examples
Let‘s build on the initial Hello World sample to show additional PL/SQL features:
Using Different Data Types
One key benefit of PL/SQL is extensive built-in data types for variable declarations:
DECLARE
greeting VARCHAR2(20);
today DATE;
is_weekend BOOLEAN;
pi NUMBER := 3.14159265;
BEGIN
-- Use different data types
DBMS_OUTPUT.PUT_LINE(pi);
END;
This shows declaring variables of types:
VARCHAR2– Text stringsDATE– Date/time valuesBOOLEAN– True/False flagNUMBER– Numeric values
This makes it easy to model real-world data!
Conditional Logic
PL/SQL has full support for IF conditional statements, CASE statements, WHILE loops etc. For example:
DECLARE
x NUMBER := 0;
BEGIN
IF x > 0 THEN
DBMS_OUTPUT.PUT_LINE(‘x is positive‘);
ELSIF x = 0 THEN
DBMS_OUTPUT.PUT_LINE(‘x is zero‘);
ELSE
DBMS_OUTPUT.PUT_LINE(‘x is negative‘);
END IF;
END;
Here we check if x variable is positive, negative or zero using the IF statement.
We could expand this with other conditional check examples as well.
But this gives a flavor of the procedural flow control possible within PL/SQL.
Compiling and Running PL/SQL Code
There are a couple options to compile and run PL/SQL blocks:
SQL Developer UI
- SQL Developer has a worksheet for writing PL/SQL statements
- Press F5 or click icon to run code
- View messages under DBMS Output tab
SQL Plus Console
- Open command prompt and connect to DB with SQL*Plus
- Execute
SET SERVEROUTPUT ON - Write PL/SQL block in console and terminate with
/ - View messages in console itself
Either option works great during code development.
I personally prefer SQL Developer as the UI allows easier editing, execution and testing during the iterative coding process.
Best Practices for PL/SQL Code
Here are some best practices I‘ve learned over the years for writing production-grade PL/SQL code:
- Modularize code into stored procedures and functions
- Use parameters for input variables instead of direct references to tables
- Name objects per agreed naming standards
- Comments should explain what the code does at a high level
- Organize code into packages for better reuse
- Handle exceptions gracefully and return friendly error messages
- Profile and tune code occasionally for peak performance
Following standards like these makes your PL/SQL code more extensible, robust and professional.
Common Errors
When first learning PL/SQL, you might run into syntax errors, runtime errors, logical errors including:
- Missing mandatory keywords like DECLARE or semicolon
- Undeclared variables or wrong data types
- Constraint violations on DML ops
- Runtime exceptions like NO_DATA_FOUND
- Logic errors leading to incorrect output
My simple advice is…
Make friends with errors early!
The compiler messages provide clues to fix specific issues. Over time you will quickly diagnose and debug code. Don‘t get discouraged.
Even as PL/SQL veterans, we run into new and interesting errors regularly!
Beyond Hello World: Real-World Examples
While the basic Hello World illustrates PL/SQL foundations, let‘s look at some more realistic examples:
Math Calculations
Perform arithmetic and numeric computations:
DECLARE
x NUMBER := 10.5;
y NUMBER := 2;
z NUMBER;
BEGIN
/* Calculate sum of x + y */
z := x + y;
DBMS_OUTPUT.PUT_LINE(‘Sum is: ‘ || z);
/* Subtract y from x */
z := x - y;
DBMS_OUTPUT.PUT_LINE(‘Difference is: ‘ || z);
END;
This shows declaring numeric variables, doing math ops like add/subtract, concatenation of strings using || etc.
Any type of business math can be handled this way.
Data Manipulation
Query and process data from tables:
DECLARE
v_count NUMBER;
BEGIN
/* Get employee count */
SELECT COUNT(*) INTO v_count
FROM employees;
/* Print the result */
DBMS_OUTPUT.PUT_LINE(‘Number of Employees: ‘ || v_count);
END;
This runs a SELECT statement to fetch number of rows in EMPLOYEES table into the v_count variable. PL/SQL variables can store full query result sets in more advanced scenarios.
This is key benefit of PL/SQL for data manipulation over SQL alone.
Error Handling
Gracefully handle errors using exception handling:
DECLARE
v_salary employees.salary%TYPE;
BEGIN
SELECT salary INTO v_salary
FROM employees
WHERE employee_id = -1;
DBMS_OUTPUT.PUT_LINE(‘Salary is: ‘ || v_salary );
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE(‘No record for ID: ‘ || employee_id);
END;
If no record matched the invalid ID, the NO_DATA exception is raised. Our exception handler prints a user friendly message.
Robust error handling is critical for fail-safe code.
This gives a small preview into PL/SQL possibilities.
Have a particular example you are wondering about implementing in PL/SQL? Ask me in the comments!
Summary
In this detailed guide, we covered foundations of PL/SQL programming including:
- Block structure
- Data types
- Variables
- Binding values
- Conditional logic
- Exception handling
- Tools like SQL Developer, SQL*Plus
- Best practices
We walked through a simple "Hello World" example to print out text.
Then expanded on the concepts to show common PL/SQL usage patterns:
- Math calculations
- Data manipulation
- Error handling
After going through this article, you should feel comfortable writing basic anonymous blocks in PL/SQL.
The next step is to further extend your PL/SQL knowledge into:
- Modular procedures and functions
- Cursor processing
- More data types like collections
- Dynamic SQL
- Integration with other languages
I highly recommend bookmarking the Oracle PL/SQL documentation for detailed reference.
Also explore more hands-on tips on my blog as we tackle specific application examples using PL/SQL.
If you have any other questions about PL/SQL, feel free to comment below or email me directly through my site.
Keep learning!