0% found this document useful (0 votes)
11 views41 pages

Lecture 03 1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views41 pages

Lecture 03 1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Database Development with PL/SQL INSY

8311

Instructor:
▪ Eric Maniraguha | ericmaniraguha2024@gmail.com | LinkedIn Profile

6h00 pm – 9h50 pm
▪ Monday A -G207
▪ Tuesday B-G204
▪ Wednesday E-G207
▪ Thursday F-G307
January 2025 1
Database Development with PL/SQL

Reference reading
▪ What is PL/SQL?
▪ Oracle PL/SQL Articles
▪ Difference Between SQL and PLSQL
▪ Real Application Clusters (RAC) Articles
▪ Oracle SQL Queries: Basic Exercises with Solution
▪ Autonomicity in Oracle Database Management System
▪ The Toughest Challenges and Problems with Oracle Database

Lecture 03 - Introduction to PL/SQL 2


What is PL/SQL?

PL/SQL is a procedural relational database language developed by Oracle


What? Corporation in earlier 90’s.

PL/SQL – Procedural Language Structured Query Language.

Procedural language? “PL/SQL allows the execution of a block of code at a time which
increases it performance.”

3
Course Overview

Starting
out This course introduces Oracle's database environment, covering
SQL, PL/SQL, and SQL*Plus. You'll learn their fundamentals,
with interactions, and applications for managing and manipulating
relational databases.

Oracle Feature
Type
SQL
Query language
PL/SQL
Procedural extension
SQL*Plus
Command-line interface

Covering Databases, Purpose Data manipulation Logic and automation Executing SQL/PL/SQL commands

SQL, PL/SQL, Execution Directly on database Runs as blocks/procs Executes SQL/PLSQL commands
Developer Tools Portability Cross-platform Oracle-specific Oracle-specific
and DBA Use Case Query data Implement logic Manage and execute database tasks

4
Brief History of Oracle Database
Oracle Database is a relational database management
system (RDBMS) developed by Oracle Corporation, one
of the world's leading providers of database solutions.
Founded in 1977 by Larry Ellison, Bob Miner, and
Ed Oates, Oracle Corporation began as Software
Development Laboratories (SDL). The company
revolutionized the database industry by introducing the
first commercially available SQL-based RDBMS with
Oracle V2 in 1979.

Over the years, Oracle Database has become


synonymous with innovation, scalability, and reliability,
evolving to meet the needs of businesses and modern
computing environments.

Source Image: https://ittutorial.org/oracle-version-history-oracle-database-release-versions/ 5


Oracle Database Latest Versions and Features

Oracle Database 19c (2019) Oracle Database 21c (2021) Oracle Database 23c AI (2023) Oracle Database 24c AI (2024)
▪Significance: Advanced hybrid ▪Significance: Emerging technologies and Significance: Integration of Artificial Significance: Advanced real-time AI
partitioning and real-time statistics. modern data management. Intelligence and developer-friendly tools. capabilities and enhanced productivity.
Features: Features:
▪Features: ▪Features:
oImproved Autonomous Database oIntroduced Blockchain Tables for ▪Transpiler for converting Python and ▪Improved real-time AI-driven insights and
capabilities. immutable records. JavaScript into PL/SQL. decision-making.
oEnhanced PL/SQL functionality. oAdded Native JSON Datatypes for ▪AI-driven automation for query tuning and ▪Expanded Transpiler support for more
better NoSQL integration. anomaly detection. programming languages.
▪In-database AI/ML model training and ▪Enhanced AI algorithms for predictive
execution. modeling and analytics.

6
Meaning of "I," "G," and "C" in Oracle Versions
& Oracle Version Numbers
Oracle version numbers follow the format: X.Y.Z.P.Q

1. X – Major Release:
Indicates significant new features and architectural changes.
2. Y – Maintenance Release:
Includes enhancements and optimizations.
G (Grid Computing)
3. Z – Application Server Release Number:
Minor updates or bug fixes for the application server.
▪Introduced with ▪Introduced with version 4. P – Patch Release Number:
versions 6i, 8i, 9i 12c (2013).
(1999–2001). Fixes specific bugs and security vulnerabilities.
▪“C” signifies cloud-
▪Reflects integration with ▪Introduced with focused architecture. 5. Q – Platform-Specific Patch Level:
the Internet and built-in versions 10g and 11g ▪Features multitenant Updates for specific hardware or OS platforms.
Java Virtual Machine (2003+). architecture with
(JVM). ▪Focus on grid pluggable databases
▪Added support for XML computing to treat (PDBs).
in 9i (2001). clusters of servers as a ▪12c includes 500+ new
single unit. features, such as in-
▪Emphasis on Enterprise memory capabilities for
Manager and Grid real-time analytics.
Control.

I (Internet) C (Cloud)

Source Image: Description of "Figure 1-2 Example of an Oracle Database Release


Number"

7
Oracle Architecture (1/2)

1. SQL Plus (User Process)


▪ Users interact with the database through SQL Plus or other
tools, sending DML (Data Manipulation Language), DDL
(Data Definition Language), and DATA commands.

2. Listeners
▪ Listeners handle connections between user processes and the
Oracle database.
▪ They are configured using a listeners.ora file.

3. Password and Parameter Files


▪ Password File: Used for authenticating privileged users.
▪ Parameter File: Contains initialization parameters for the
database instance.

4. Oracle Server Processes


▪ These processes perform actions requested by user queries.
They interact with the memory structures in the SGA and data
stored on disk.

Source Image: https://learnomate.org/oracle-dba-architecture/


8
Oracle Architecture (2/2)
5. SGA (System Global Area)
▪ The SGA is a shared memory region that contains:
o Log Buffer: Stores redo entries before they are written to redo log files.
o Database Buffer Cache: Temporarily holds data blocks read from data files.
o Shared Pool: Contains:
❖ Library Cache: Stores parsed SQL statements and execution plans.
❖ Data Dictionary Cache (or Row Cache): Contains metadata about
database objects.
❖ Result Cache: Stores query results for faster retrieval.
o Large Pool, Java Pool, and Stream Pool: Used for specific operations like
backups, Java-based applications, or streaming.

6. PGA (Program Global Area)


▪ Contains memory specific to a server process, including sort areas and session
information. 8. Storage Components
▪ Data Files: Store actual user and application data.
7. Background Processes ▪ Control Files: Maintain the structure of the database and log locations.
▪ MMON, SMON, PMON, RECO, MMNL: Perform tasks such as monitoring, recovering, ▪ Online Redo Log Files: Record changes made to the database.
managing sessions, and maintaining log files. ▪ Archived Redo Log Files: Used for recovery and backup.
▪ DBWn (Database Writer): Writes modified data blocks from the buffer cache to data ▪ Flashback Logs: Contain data for undoing changes and recovering the
files. database to a prior state.
▪ LGWR (Log Writer): Writes redo entries from the log buffer to redo log files.
▪ CKPT (Checkpoint): Updates control files and data files with checkpoint information. This architecture showcases the interaction between memory, processes, and
▪ ARCn (Archive): Copies redo log files to archive destinations. storage in an Oracle database, ensuring efficient data management,
▪ RVWR (Recovery Writer): Writes flashback data for recovery purposes. transaction processing, and recovery.

9
Oracle DB Environments: Tablespaces,
Datafiles, and Control Files
Tablespaces are logical storage units in Oracle Database used to store and Type of Tablespace
organize data. They enable efficient data retrieval by providing logical structures for
managing and locating specific information. SYSTEM Tablespace
▪ Automatically created during database creation.
A database, as defined by Oracle, is an organized collection of data, typically stored ▪ Stores the data dictionary tables for the entire database.
electronically. However, managing this data efficiently requires structured storage, Undo Tablespaces
which is where tablespaces come into play. ▪ Dedicated to storing undo information exclusively.

Source Image: https://www.geeksforgeeks.org/working-on-oracle-tablespaces-for-developers/


10
Oracle Database 21c Server Block Diagram.

This Is The Highest-level Diagram. Note That The Listener Process Often Runs Outside The Server, Especially In Clustered Environments.

Diagram 1: Database Server

1.Client Application (Client Process):


▪ Represents the application used by end-users to send SQL queries to the
database.
▪ The client connects to the database using a connection packet.
2.Connect Packet:
▪ A communication protocol packet sent by the client application to establish
a connection with the database server.
3.Listener:
▪ A process on the database server that listens for incoming connection
requests from clients.
▪ It establishes the connection between the client application and the server
process.
4.Database Server:
▪ Houses the Database Instance and the Database.
▪ The Server Process processes the SQL queries from the client.
5.Database Instance:
▪ Consists of memory and processes that handle interactions with the
database.
▪ Processes the SQL queries received from the client through the server
process.
6.Database:
▪ Stores the actual data, including:
Source Image: https://www.infoworld.com/article/2264510/oracle-database-21c-review-the-old-rdbms-is-new-again.html o Data Files: Contain user data and metadata.
o System Files: Contain database system information and
configuration.
11
Oracle Database 21c Instance Diagram.
The Instance Handles Memory And Processes.

Diagram 2: Database Instance


1.Client Applications:
▪ Send SQL queries to the database instance.
2.Database Server:
▪ Includes the Database Instance and the physical Database.
3.Database Instance:
▪ Comprises memory structures and processes used to interact with the
database.
▪ Key Components:
1. System Global Area (SGA):
▪ Shared memory area that contains information shared
across multiple server processes.
▪ Stores data such as SQL query results, cached data, and
execution plans.
2. Program Global Areas (PGAs):
▪ Memory areas allocated for individual server processes.
▪ Contains data specific to a single user or process.
3. Server Processes:
▪ Handle client requests by executing SQL queries and
interacting with the database.
4. Background Processes:
▪ Perform maintenance tasks like managing data files, logs,
and memory cleanup.
4.Database:
▪ The storage component that holds the physical data files and system
Source Image: https://www.infoworld.com/article/2264510/oracle-database-21c-review-the-old-rdbms-is-new-again.html files.
12
Multi-tenant Container Database (CDB) &
Pluggable Databases (PDB)
An Oracle Database Is A Multi-tenant Container Database (CDB) With Multiple User-created Pluggable Databases (PDB).

1.Container Database (CDB):


1. The CDB is the main database that houses multiple
pluggable databases (PDBs).
2. It has a Root Container (CDB$ROOT), which
contains metadata and shared data used across all
PDBs.
3. The root container includes the following data files:
▪ SYSTEM: Contains core database metadata,
objects, and code required by Oracle Database.
▪ SYSAUX: Holds auxiliary metadata, such as
performance and administrative data.
▪ TEMP: Temporary data storage used for sorting
and other transient tasks.
▪ USERS: A tablespace where user data can be
stored.
▪ UNDO: Handles rollback operations (shown here
as a shared resource).
2.Seed PDB (PDB$SEED):
1. The Seed PDB is a template for creating new PDBs. It
has a set of predefined data files:
▪ SYSTEM and SYSAUX (as in the root container).
▪ TEMP for temporary data.
▪ UNDO may not always be unique to the Seed
PDB, depending on configuration.
Source Image: https://www.infoworld.com/article/2264510/oracle-database-21c-review-the-old- 13
rdbms-is-new-again.html
Multi-tenant Container Database (CDB) &
Pluggable Databases (PDB)
3. Regular Pluggable Databases (Regular PDBs):
1. Each Regular PDB is a self-contained database created from the Seed PDB.
2. Regular PDBs include their own data files for:
▪ SYSTEM and SYSAUX for metadata specific to the PDB.
▪ TEMP and USERS for temporary and user data storage.
▪ UNDO, if not shared, for rollback operations.
4. Application Container:
▪ This is an optional container for managing shared data or metadata across multiple application PDBs.
▪ It can host application-specific metadata and configuration while maintaining separate PDBs for different applications.

Key Insights:
▪ The CDB$ROOT shares its resources with the PDBs to optimize management and performance.
▪ The Seed PDB serves as a standardized starting point for creating PDBs.
▪ Regular PDBs are isolated from each other in terms of their data but share the root container's infrastructure.
▪ This architecture supports scalability, allowing multiple PDBs to run within a single CDB, minimizing resource overhead.

14
What is SQL*Plus?
SQL*Plus is an Oracle command-line tool used to interact with Oracle databases. It acts as a query interface for running SQL commands, PL/SQL blocks, and managing
database objects. SQL*Plus is widely used by database administrators (DBAs) and developers for various database operations.

Key Features of SQL*Plus Key SQL*Plus Commands

Interactive Query Execution: CONNECT: Connect to an Oracle database.


Run SQL queries and view results directly in the Example: CONNECT
command-line interface. username/password@database
Support for PL/SQL Blocks:
SELECT: Retrieve data from tables.
Execute PL/SQL scripts for procedural
Example: SELECT * FROM employees;
programming.
Database Administration: DESC: Describe the structure of a table or
Perform tasks like creating users, managing view.
roles, and monitoring database health. Example: DESC employees;
Scripting and Automation: SET: Customize session settings (e.g., format,
Use SQL*Plus scripts (.sql files) to automate linesize).
routine tasks. Example: SET LINESIZE 100
Customization:
Customize the environment with SQL*Plus SPOOL: Save query results to a file.
commands like SET and DEFINE to format Example: SPOOL output.txt
outputs.
SQLPlus is an essential tool for database interaction, particularly for running SQL queries and managing Oracle databases. While it provides an interface to execute PL/SQL,
the two serve distinct roles: SQLPlus is a client tool, whereas PL/SQL is a language for database programming. 15
SQL and SQL*Plus Interaction

Process Flow:
SQL Statements SQL Statements 1. The user inputs SQL statements in SQL*Plus.
Buffer 2. These statements are stored in the buffer temporarily.
3. The statements are sent from the buffer to the server,
where they are processed.
4. The query results are returned to SQL*Plus.
5. SQL*Plus formats these results into a report.
6. The formatted report is then displayed to the user.

SQL*Plus Server

Query Results
SQL*Plus
Commands
Formatted Report
16
Difference Between SQL Statements and
SQL*Plus Commands
Aspect SQL Statements SQL*Plus Commands

SQL statements are instructions written in SQL to interact SQLPlus commands are specific to SQLPlus for managing the
Definition
with the database. SQL*Plus environment and enhancing user interaction.

Perform operations like querying, updating, and managing


Purpose Control the behavior and formatting of the SQL*Plus session.
data in the database.

Executed within any SQL environment (SQL*Plus, SQL


Execution Only recognized and executed within SQL*Plus.
Developer, etc.).

Examples SELECT, INSERT, UPDATE, DELETE, CREATE, DROP. SET, SPOOL, DESCRIBE, PROMPT, SHOW.

Provides results based on database operations (e.g., data


Output Adjusts the session output (e.g., formatting or saving results).
from a query).

Affects the database (data manipulation, definition, and Affects the SQL*Plus interface and session environment, not the
Scope
control). database itself. 17
Examples SQL Statements vs. SQL*Plus
Commands
Category Command/Statement Description
Retrieves all columns from the employees table where department_id is
SQL Statement SELECT * FROM employees WHERE department_id = 10;
10.

SQL Statement UPDATE employees SET salary = salary * 1.1 WHERE employee_id = 101; Increases the salary by 10% for the employee with employee_id 101.

CREATE TABLE departments (department_id NUMBER PRIMARY KEY,


SQL Statement Creates a new table departments with department_id as the primary key.
department_name VARCHAR2(50));

SQL*Plus Command SET LINESIZE 100; Adjusts the line width of the SQL*Plus output to 100 characters per line.

SQL*Plus Command SET PAGESIZE 50; Limits the output to 50 rows per page in SQL*Plus.
SQL*Plus Command SPOOL results.txt; Starts saving the query results to the results.txt file.
SQL*Plus Command SELECT * FROM employees; Executes a query to fetch all data from the employees table.
SQL*Plus Command SPOOL OFF; Stops saving query results to the file results.txt.
Displays the structure of the employees table, including column names
SQL*Plus Command DESCRIBE employees;
and data types.
SQL*Plus Command SHOW USER; Displays the current logged-in user in the SQL*Plus session.

Key Points
▪ SQL Statements directly interact with the database (e.g., querying, inserting, updating data).
▪ SQL*Plus Commands help manage the SQL*Plus environment (e.g., controlling output format, saving results to files, and showing session details). 18
SQL*Plus - Usage

19
Oracle SQL (Structured Query Language)
Features 1/2
1. Data Querying and Manipulation
▪SELECT Statements: Retrieve data from one or more tables.
▪Joins: Combine data from multiple tables using INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL JOIN.
▪Subqueries: Use nested queries within the main query.
▪Aggregating Data: Functions like COUNT(), SUM(), AVG(), MAX(), and MIN() for summarizing data.
▪Filtering and Sorting: Use WHERE, ORDER BY, HAVING, and GROUP BY to filter and sort data.
2. Data Definition
▪CREATE: Define new tables, views, indexes, etc.
▪ALTER: Modify the structure of an existing table, column, or index.
▪DROP: Remove objects like tables, views, or indexes from the database.
▪RENAME: Change the name of a database object.
3. Data Integrity and Constraints
▪Primary Key: Ensure that each record in a table is unique and identifiable.
▪Foreign Key: Enforce referential integrity between tables.
▪Unique: Ensure all values in a column are unique.
▪Check Constraints: Ensure values in a column satisfy a specified condition.
▪Not Null: Ensure that a column does not contain null values.
4. Transactional Control
▪COMMIT: Save changes made to the database.
▪ROLLBACK: Undo changes made in the current transaction.
▪SAVEPOINT: Create a point in a transaction to roll back to.
▪SET TRANSACTION: Control the properties of a transaction, such as isolation level.
5. Views and Indexes
▪Views: Virtual tables based on the result of a query, simplifying complex queries and providing security by limiting access to certain columns.
▪Indexes: Improve the performance of queries by providing quick access to rows in a table.
6. Stored Procedures and Functions
▪PL/SQL: Oracle’s extension of SQL for procedural programming, allowing you to define reusable stored procedures, functions, and triggers.
▪Triggers: Automatic actions that occur in response to certain events, such as before or after an insert, update, or delete operation. 20
Oracle SQL (Structured Query Language)
Features 2/2
7. Advanced Querying Capabilities
▪Hierarchical Queries: Use CONNECT BY for querying hierarchical data (e.g., organization charts, bill-of-materials).
▪Analytic Functions: Functions like RANK(), ROW_NUMBER(), LEAD(), and LAG() for advanced reporting and windowed analytics.
▪Full-Text Search: Oracle’s Full-Text Search allows efficient querying of text-based data.

8. Security Features
▪User Management: Create and manage user roles and privileges.
▪Granting and Revoking Permissions: Control access to database objects using the GRANT and REVOKE commands.
▪Audit: Track and log database activity for security auditing purposes.

9. Performance Tuning
▪EXPLAIN PLAN: Analyze query execution plans to optimize performance.
▪Indexes and Optimizers: Help speed up query processing by reducing the amount of data the database engine needs to scan.
▪Partitioning: Improve query performance by dividing large tables into smaller, more manageable parts.

10. Concurrency Control


▪Locking: Mechanisms to ensure data consistency and prevent conflicts in multi-user environments.
▪Isolation Levels: Control the visibility of data changes made by other transactions.

11. Integration with Other Languages


▪Java: Oracle supports embedding Java within SQL queries and using Java Stored Procedures.
▪XML Support: Oracle SQL has robust features for working with XML data, such as XMLTYPE and XQuery.

12. Error Handling


▪Exception Handling in PL/SQL: Catch and handle exceptions (errors) in PL/SQL blocks to prevent program crashes and improve robustness.

13. Oracle Extensions to SQL


▪Dual Table: A special table (DUAL) that returns a single row with a single column, typically used to select a value or perform a calculation.
▪Sequences: Automatically generate unique numbers for primary keys and other purposes.
▪Synonyms: Create alternative names for database objects for easier referencing.
21
Oracle PL/SQL (Procedural Language/SQL)
Feature Description
Block Structure PL/SQL programs are organized into blocks (anonymous or named).
Procedures and Functions Create reusable subprograms for modular programming and improved maintainability.
Control Structures Use loops (FOR, WHILE), conditional statements (IF-THEN-ELSE), and case expressions.
Exception Handling Manage runtime errors using EXCEPTION blocks.
Cursors Work with explicit and implicit cursors to process query results row-by-row.
Triggers Automatically execute code in response to specific events (e.g., BEFORE or AFTER DML operations).
Packages Group related procedures, functions, variables, and cursors into modules.
Data Types Support scalar, composite, reference, and LOB data types for flexible programming.
Collections Use associative arrays, nested tables, and VARRAYs for advanced data handling.
Dynamic SQL Execute SQL dynamically at runtime using EXECUTE IMMEDIATE and DBMS_SQL.
PL/SQL Libraries Use built-in packages like DBMS_OUTPUT, UTL_FILE, and DBMS_SCHEDULER.
Integration with SQL Seamlessly embed SQL statements within PL/SQL code for database interaction.
Performance Features Leverage bulk processing (FORALL, BULK COLLECT) for efficient data operations.
Portability Write code that runs across multiple Oracle database platforms.
Object-Oriented Programming Support for user-defined types, methods, and object-oriented programming features.

Usage: PL/SQL is used for:


▪ Batch Processing: Running multiple SQL statements in sequence, using variables, cursors, and control statements.
▪ Improved Performance: Avoids multiple round-trips between the application and the database by bundling SQL statements into a single block of code.
22
PL/SQL vs. Its Counterparts in Different
Database Platforms
PL/SQL (Procedural Language/Structured Query Language) is specifically designed for Oracle databases. It is
Oracle Corporation's procedural extension to SQL and is tightly integrated with Oracle's SQL engine.

Database System Procedural Language Description


Oracle PL/SQL Oracle's proprietary procedural extension to SQL.

PostgreSQL (pgAdmin) PL/pgSQL Procedural language designed for PostgreSQL.

Microsoft SQL Server T-SQL (Transact-SQL) Procedural extension used in Microsoft SQL Server.

MySQL MySQL SQL/PSM MySQL's procedural extension for SQL.

In summary, PL/SQL is exclusive to Oracle databases, and each database management system (DBMS) typically has its own procedural
language.

23
The Architecture of PL/SQL (1/2)
PL/SQL (Procedural Language/Structured Query Language) is Oracle Corporation's procedural extension to SQL, designed specifically for managing and
manipulating data in Oracle databases. It combines the data manipulation capabilities of SQL with the procedural programming features of languages like C or Java,
allowing developers to write complex scripts that can execute multiple SQL statements, control logic, handle exceptions, and more within a single program unit.

DECLARE

BEGIN Following are the different type of PL/SQL units.


▪ Anonymous Block
PL/SQL Block ▪

Function
Library
Procedure
EXCEPTION ▪
▪ Package Body
▪ Package Specification
PL/SQL PL/SQL Engine ▪ Trigger
▪ Type
END ▪ Type Body

Database Server

24
PL/SQL Architecture

PL/SQL Block 1. PL/SQL Block:


▪ At the top, you have a PL/SQL block, which contains both SQL and PL/SQL code.
SQL PL/SQL ▪ SQL statements refer to standard SQL commands like SELECT, INSERT, UPDATE, etc.
▪ PL/SQL refers to procedural extensions for SQL, such as loops, conditions, and variable
declarations.

2. PL/SQL Engine:
▪ The PL/SQL engine is responsible for processing the PL/SQL code.
PL/SQL Engine
▪ When a PL/SQL block is passed to the PL/SQL engine, it splits the SQL commands and
PL/SQL logic into separate units.
PL/SQL ▪ The PL/SQL Units are passed to the PL/SQL Unit Executor for processing.
SQL PL/SQL Unit Executor
Unit
3. SQL Execution:
▪ The SQL statements (from the PL/SQL block) are passed down to the Database Server.
▪ The database server contains the SQL Executor, which runs the SQL commands against
Database Server or Oracle Server
the database.
▪ The PL/SQL engine processes the procedural logic, and whenever a SQL statement is
encountered, it hands that statement off to the database server to execute. The results
SQL SQL Executor from SQL execution are then returned to the PL/SQL engine to continue processing any
remaining PL/SQL logic.

4. Database Server
▪ Stores data and executes SQL statements using a SQL executor.
▪ Interacts with the PL/SQL engine for data retrieval and manipulation.

25
High Secured

Error Code
Handling reusability

Extremely Looping
Flexible Statement

Why Use PL/SQL?


Key Features & Fast Code
execution
PL/SQL
Features
Portable
Application

Benefits

Better Extension of
Performance SQL

Procedural Conditional
Language Statement
Reduces
Network
Traffic
26
PL/SQL Key Features and Benefits - Examples

Feature Description Example


PL/SQL is designed for high-performance transaction processing, A PL/SQL block that retrieves and processes thousands of
High Performance
optimizing database operations. records faster than a standard SQL query.
Creating a procedure to calculate tax, which can be called
Supports code reusability, allowing you to write modular code that can be
Code Reusability whenever needed, instead of rewriting the tax calculation
reused across different programs.
logic.
Provides robust error handling by returning user-friendly error messages Using EXCEPTION to catch a NO_DATA_FOUND error and
Error Handling
when errors occur. return a custom message.
Procedural Language Includes procedural language constructs like conditional statements Using an IF...ELSE statement to check a condition and a FOR
Capability (IF...ELSE) and loops (FOR loop). loop to iterate over a range of values.
Consists of nested blocks of code, where each block is a unit of task or A block containing variable declarations, SQL statements, and
Block Structure
logical module. an exception-handling section, all within a single logical unit.
Oracle engine processes multiple SQL statements in a single block, A PL/SQL block that executes multiple SQL operations (e.g.,
Better Performance
reducing network traffic. INSERT, UPDATE, DELETE) in a single transaction.

Allows declaring variables that can be used and manipulated within the Declaring a variable to store an employee's salary and then
Variable Declaration
block. updating it within the same block.

Looping and Conditional Supports loops (FOR, WHILE) and conditional statements (IF...ELSE) for A FOR loop to iterate over a list of employee IDs and apply a
Statements complex control flows. bonus if the salary exceeds a certain amount.
Multiple SQL statements are processed as a single block, minimizing Combining several INSERT operations in one PL/SQL block
Reduce Network Traffic
network interactions with the database. instead of executing them individually.
27
PL/SQL applications are portable across different operating systems A PL/SQL procedure created on an Oracle database in
Portable Applications
Anonymous PL/SQL Block
-- Declare the PL/SQL block
DECLARE
-- Declare a variable `v_salary` of type NUMBER with a precision of 8 digits
and 2 decimal places
v_salary NUMBER(8,2);

-- Start the executable section of the PL/SQL block Anonymous PL/SQL Block:
BEGIN ▪ Not Named: It is not stored with a name in the database.
-- Execute a SELECT statement to retrieve the salary of the employee with ▪ Temporary: Executed once and then discarded.
employee_id = 1001
-- Store the retrieved salary into the variable `v_salary` Key Points
SELECT salary INTO v_salary FROM employees WHERE employee_id = 1001;
▪ Variable Declaration: v_salary is defined to store the salary of
-- Check if the value of `v_salary` is greater than 5000 an employee.
IF v_salary > 5000 THEN ▪ Data Retrieval: The SELECT INTO statement retrieves data from
-- If the condition is true (i.e., `v_salary` is greater than 5000), output 'High the database and stores it in the variable.
salary' ▪ Conditional Logic: The IF-THEN-ELSE construct is used to
DBMS_OUTPUT.PUT_LINE('High salary'); perform different actions based on the value of v_salary.
ELSE ▪ Output: DBMS_OUTPUT.PUT_LINE is used to display messages
-- If the condition is false (i.e., `v_salary` is 5000 or less), output 'Low based on the condition.
salary'
DBMS_OUTPUT.PUT_LINE('Low salary');
END IF;

-- End of the executable section


END;
28
Features Higher Performance & Code
Reusability
High Performance

BEGIN ▪ FOR employee_record IN (SELECT first_name FROM employees WHERE


-- Loop through each record from the 'employees' table where department_id is 10 department_id = 10):
FOR rec IN (SELECT * FROM employees WHERE department_id = 10) LOOP This loop iterates through the result set of the query, which retrieves the
-- Output the first name of each employee in the result set first_name of employees in department 10.
DBMS_OUTPUT.PUT_LINE('Employee: ' || rec.first_name);
END LOOP; ▪ DBMS_OUTPUT.PUT_LINE(employee_record.first_name);:
END; This line prints the first_name of each employee to the output.

Make sure that DBMS_OUTPUT is enabled in your environment to see the output.
You can enable it in SQL*Plus or SQL Developer by executing:

▪ SET SERVEROUTPUT ON;

Code Reusability

CREATE OR REPLACE PROCEDURE calculate_tax (p_salary IN NUMBER) IS


▪ Procedure Name: calculate_tax
-- Declare a variable to store calculated tax
▪ Input Parameter: p_salary (of type NUMBER)
v_tax NUMBER;
▪ Variable: v_tax is declared to store the calculated tax.
BEGIN
▪ Main Logic: It calculates 10% of the salary (p_salary * 0.10) and assigns it to
-- Calculate 10% tax on the input salary
v_tax.
v_tax := p_salary * 0.10;
▪ Output: The calculated tax is printed using DBMS_OUTPUT.PUT_LINE.
-- Output the calculated tax value
DBMS_OUTPUT.PUT_LINE('Tax: ' || v_tax); 29
END;
Error Handling & Procedural Language
Capability
Error Handling

BEGIN
-- Retrieve salary of employee with employee_id 999 and store in v_salary ▪ Main Logic: The block tries to retrieve the salary of an employee with
SELECT salary INTO v_salary FROM employees WHERE employee_id = 999; employee_id = 999 and store it in v_salary.

EXCEPTION ▪ Exception Handling: If no employee is found with that ID, the


-- Handle case when no record is found for the given employee_id NO_DATA_FOUND exception is caught, and a message is printed using
WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE.
DBMS_OUTPUT.PUT_LINE('No employee found with the given ID.');
END;

Procedural language Capability


▪ IF v_salary > 5000 THEN:
▪ This line checks if the variable v_salary (employee salary) is greater than
BEGIN
5000.
-- Check if the salary is greater than 5000
▪ DBMS_OUTPUT.PUT_LINE('High salary');:
IF v_salary > 5000 THEN
▪ If the condition is true (salary > 5000), it prints "High salary" to the output.
-- If salary is greater than 5000, print "High salary"
▪ ELSE:
DBMS_OUTPUT.PUT_LINE('High salary');
▪ If the salary is less than or equal to 5000, the code executes the block in
ELSE
the ELSE statement.
-- If salary is 5000 or less, print "Low salary"
▪ DBMS_OUTPUT.PUT_LINE('Low salary');:
DBMS_OUTPUT.PUT_LINE('Low salary');
▪ This line prints "Low salary" if the salary is 5000 or less.
END IF;
▪ END IF;:
END;
▪ Ends the conditional block.
30
Block Structure & Better Performance
Block Structure

DECLARE
-- Declare a variable to store the salary
v_salary NUMBER;
BEGIN ▪ Main Logic: The block tries to retrieve the salary of an employee
-- Select the salary of the employee with ID 100 into the v_salary variable with employee_id = 999 and store it in v_salary.
SELECT salary INTO v_salary FROM employees WHERE employee_id = 100;

-- Check if the salary is greater than 5000 and print 'High salary' if true ▪ Exception Handling: If no employee is found with that ID, the
IF v_salary > 5000 THEN NO_DATA_FOUND exception is caught, and a message is printed
DBMS_OUTPUT.PUT_LINE('High salary'); using DBMS_OUTPUT.PUT_LINE.
END IF;

EXCEPTION
-- Handle the case where no employee with the specified ID is found
WHEN NO_DATA_FOUND THEN Better Performance
DBMS_OUTPUT.PUT_LINE('No employee found');
END; BEGIN
-- Update salaries in department 10 by 10%
UPDATE employees SET salary = salary * 1.10 WHERE department_id = 10;

-- Delete employee with employee_id = 999


▪ Update: Increases salaries by 10% for all employees in department 10. DELETE FROM employees WHERE employee_id = 999;
▪ Delete: Removes the employee with employee_id = 999.
▪ Commit: Saves both changes in a single transaction to the database. -- Commit both operations in one transaction
COMMIT;
This block efficiently handles both operations together and ensures data consistency. END;

31
Variable & Looping and Condition Statement
Variable Declaration
▪ Variable Declaration:
DECLARE o v_bonus: Initialized to 1000.
-- Declare and initialize bonus variable o v_salary: Declared to hold the employee's salary.
v_bonus NUMBER := 1000; ▪ Retrieve Salary:
-- Declare salary variable o Fetches the salary of the employee with employee_id = 100 into
v_salary NUMBER; v_salary.
BEGIN ▪ Calculate New Salary:
-- Retrieve the salary of the employee with ID 100 o Adds the bonus to the retrieved salary.
SELECT salary INTO v_salary FROM employees WHERE employee_id = ▪ Output:
100; o Displays the updated salary with the bonus added.

-- Add bonus to the retrieved salary


v_salary := v_salary + v_bonus; Looping and Conditional Statements

-- Print the new salary BEGIN


DBMS_OUTPUT.PUT_LINE('New salary: ' || v_salary); -- Loop through numbers 1 to 5
FOR i IN 1..5 LOOP
-- Check if the current number is 3
IF i = 3 THEN
-- Print a special message for the number 3
▪ Loop: DBMS_OUTPUT.PUT_LINE('Special case for 3');
o Iterates from 1 to 5, with i taking each value in this range. ELSE
▪ Condition: -- Print the current number
o If i is 3, prints "Special case for 3". DBMS_OUTPUT.PUT_LINE('Number: ' || i);
o For other values of i, prints "Number: " followed by the value of i. END IF;
END LOOP; 32
END;
Reduce Network Traffic & Portable Application

Reduce Network Traffic ▪ Insert Statements:


o Adds two employees to the employees table: one with ID 101 and name 'John', and
BEGIN another with ID 102 and name 'Jane'.
-- Insert a new employee with ID 101 and name 'John' ▪ Commit:
INSERT INTO employees (employee_id, first_name) VALUES (101, 'John'); o Saves both insertions in a single transaction, making the changes permanent.
▪ Batch Inserts in PL/SQL Block:
-- Insert another employee with ID 102 and name 'Jane' o Both INSERT statements are sent as a single request.
INSERT INTO employees (employee_id, first_name) VALUES (102, 'Jane'); o A single commit operation finalizes all changes.

-- Commit the transaction to save the changes By consolidating operations into a single PL/SQL block, network traffic is optimized, leading to
COMMIT; better performance and reduced latency.
END;

Portable Application

▪ Procedure: -- This procedure will run on any Oracle Database regardless of OS


o CREATE OR REPLACE PROCEDURE hello_world IS: Defines a new procedure CREATE OR REPLACE PROCEDURE hello_world IS
named hello_world. BEGIN
o BEGIN: Starts the executable part of the procedure. -- Output a simple greeting message
o DBMS_OUTPUT.PUT_LINE('Hello, World!');: Outputs the string "Hello, World!" to DBMS_OUTPUT.PUT_LINE('Hello, World!');
the console. END;
o END;: Ends the procedure. /
▪ Execution: This procedure can be executed in any environment where Oracle Database is
installed, making it highly portable across different operating systems and versions of Oracle 33
Database.
Procedure Implementation & Solution
CREATE OR REPLACE PROCEDURE Add_Numbers_With_Increment(
num1 IN NUMBER,
num2 IN NUMBER, ▪ num1 and num2 are the numbers to be added.
increment IN NUMBER, ▪ increment is the value to be added to the sum of the two numbers.
result OUT NUMBER ▪ result is an output parameter that will hold the final result.
) AS ▪ DBMS_OUTPUT.PUT_LINE is used to print the result in the console.
BEGIN
-- Add the two numbers and the increment
result := (num1 + num2) + increment;

-- Output the result


DBMS_OUTPUT.PUT_LINE('The sum of ' || num1 || ' and ' || num2 ||
' with an increment of ' || increment ||
' is: ' || result);
END; Call the procedure
/
DECLARE
▪ The DECLARE block defines sum_result to store the output.
sum_result NUMBER;
▪ The procedure Add_Numbers_With_Increment(5, 10, 2, sum_result) is called with: BEGIN
o 5 and 10 as the two numbers to add. -- Call the procedure
o 2 as the increment. Add_Numbers_With_Increment(5, 10, 2, sum_result);
o sum_result to hold the result (17).
▪ The procedure computes (5 + 10) + 2 = 17 and stores it in sum_result. -- Display the final result
▪ DBMS_OUTPUT.PUT_LINE prints the final result: "Final Result: 17". DBMS_OUTPUT.PUT_LINE('Final Result: ' || sum_result);
END;
▪ The sum of 5 and 10 with an increment of 2 is: 17 /
▪ Final Result: 17 34
Oracle SQL vs PL/SQL
Feature Oracle SQL Oracle PL/SQL

Type Declarative (Non-Procedural) Procedural Language (Extension of SQL)

Purpose Data querying and manipulation Procedural logic and complex operations

Execution Executes single statements Executes blocks of code (multiple SQL statements and logic)

Control Structures No control structures (loops, conditions) Supports loops, conditions, exceptions

Reusability No reusable logic Supports reusable logic (procedures, functions)

Transaction Handling Manages transactions (COMMIT, ROLLBACK) Handles transactions within a block

Error Handling Limited error handling Advanced error handling using EXCEPTION blocks

Integration Focuses solely on data manipulation Integrates SQL within procedural code

35
Advantages of Oracle Database over other
RDBMS systems
Scalability and Performance High Availability and Disaster Recovery Security
▪Horizontal and vertical scalability. ▪Oracle Data Guard for failover and data ▪Advanced encryption (in transit and at rest).
▪Real Application Clusters (RAC) for load protection. ▪Virtual Private Database (VPD) for fine-grained
balancing and high availability. ▪Automatic Storage Management (ASM) for access control.
▪Advanced query optimization. storage optimization. ▪Data masking and redaction.
▪Flashback Technology for quick data recovery.

Support for Advanced Data Types Cross-Platform Flexibility Enterprise-Level Features


▪Support for XML, JSON, spatial data, and ▪Runs on multiple platforms (Windows, Linux, ▪Partitioning for improved query performance.
multimedia. Unix, Solaris). ▪Oracle Exadata for optimized performance.
▪Object-relational model for complex data ▪Cloud compatibility (Oracle Cloud, AWS, Azure). ▪ Multitenant architecture for managing multiple
structures. databases.

Comprehensive Tooling and Ecosystem Support and Community Automation


▪Oracle Enterprise Manager (OEM) for ▪24/7 enterprise-level support. ▪Autonomous database for automatic tuning,
centralized monitoring and management. ▪Active user community and extensive backups, and patching.
▪Data integration and business intelligence tools. documentation.

Compliance and Auditing


▪ Extensive auditing tools for regulatory
compliance (GDPR, HIPAA, etc.).

36
PL/SQL Disadvantage

Licensing Costs High Memory Usage Limited Web Support


▪ Oracle's PL/SQL tools are expensive, ▪ Stored procedures in PL/SQL can use a ▪ PL/SQL is mainly for database tasks
making it costly for smaller organizations. lot of memory, which may slow down and has limited capabilities for building
the system. modern web applications compared to
languages like PHP or Python.

Maintenance Issues Difficult Debugging Steep Learning Curve


▪ Changes in the database often require ▪ PL/SQL lacks advanced debugging ▪ PL/SQL is difficult for beginners to learn
updates in the code, leading to more tools, making it harder to find and fix quickly due to its complex syntax and
maintenance work. errors. structure.

Database DependencePL
▪ SQL works only with Oracle databases,
so it can’t be used with other databases
or platforms easily.

37
Summary of Oracle Environment Terms
1. Oracle Database Instance
7. Oracle Multitenant Architecture (Optional)
Definition: The combination of memory structures and background processes that manage database operations.
▪Memory Structures:
Definition: Architecture introduced in Oracle 12c for managing multiple databases within a single
oSGA (System Global Area): Shared memory region for all users. container.
oPGA (Program Global Area): Memory region specific to a user process. ▪Container Database (CDB): Houses multiple Pluggable Databases (PDBs).
▪Background Processes: Essential processes that handle tasks such as writing to files and managing memory. ▪Benefits: Improved consolidation, simplified upgrades, and efficient resource management.
2. Physical Structures
Definition: Files that physically store the database’s data and metadata. 8. Oracle Data Guard (High Availability)
▪Data Files: Store actual database data.
▪Control Files: Maintain information about the structure of the database. Definition: High availability and disaster recovery solution.
▪Redo Log Files: Record all changes made to the database for recovery purposes. ▪Standby Databases: Copies of the primary database for failover scenarios.
▪Switch Over: Ability to manually or automatically move operations to a standby database.
3. Logical Structures
Definition: Components that define how data is logically organized within the database.
▪Tablespaces: High-level logical containers for data storage. 9. Oracle Backup and Recovery
▪Segments: Space allocated for a specific type of data, such as a table or index.
▪Extents: Contiguous blocks of space within a segment. Definition: Tools and technologies for safeguarding data.
▪Blocks: Smallest unit of storage in the database. ▪RMAN (Recovery Manager): Main tool for database backup, restore, and recovery.
▪Flashback Technology: Allows rewinding the database to a specific point in time.
4. Schema Objects
Definition: Logical database objects owned by a user. 10. Oracle RAC (Real Application Clusters)
▪Tables: Store data in rows and columns.
▪Indexes: Improve query performance by allowing faster data access. Definition: Clustering solution for high availability and scalability.
▪Views: Virtual tables created from queries. ▪Features:
▪Sequences: Generate unique numeric values, often for primary keys. oMultiple instances accessing the same database.
▪Synonyms: Aliases for tables, views, or other objects to simplify access. oLoad balancing and failover for continuous availability.
5. User and Security Management
Definition: Security model based on user roles and privileges. 11. Oracle Enterprise Manager (OEM)
▪Users and Schemas: Users own schemas containing database objects.
▪Roles: Collections of privileges assigned to users. Definition: Oracle's web-based platform for database and infrastructure management.
▪System Privileges: Permissions for administrative tasks (e.g., creating tables). ▪Capabilities:
▪Object Privileges: Permissions on specific objects (e.g., SELECT, INSERT, UPDATE). oPerformance monitoring.
oDatabase administration.
6. Oracle Network Environment oBackup configuration and management.
Definition: Tools enabling communication between clients and the database.
▪Listeners: Processes that handle client connection requests.
▪TNS (Transparent Network Substrate): Manages connection addresses between clients and servers. 38
▪Database Links: Facilitate operations between multiple databases.
Conclusion: Key Takeaways PL/SQL
5. Disadvantages of PL/SQL
1. SQL vs. PL/SQL
▪Oracle-specific: Limits portability to other databases.
•SQL: Used for single queries to retrieve/manipulate data (SELECT, INSERT, etc.). ▪Complexity: Harder to debug and maintain procedural logic.
•PL/SQL: Extends SQL with procedural logic (loops, conditionals, error handling)
for tasks like stored procedures and triggers.
6. Practical Scenarios

2. Why Choose PL/SQL? ▪When PL/SQL improves performance:


Example: Processing payroll for 10,000 employees with custom logic in one
block.
•Batch processing: Execute multiple SQL commands in a single block. ▪When SQL is preferable:
•Error handling: Manage exceptions effectively. Simple queries, ad-hoc analysis, or cross-database portability.
•Encapsulation: Store business logic in procedures/functions for reuse.
Practice Exercises
3. When Not to Use PL/SQL 1.Write an SQL query to find the top 10 highest-paid employees.
2.Create a PL/SQL block to calculate and store average salaries by
department.
•For simple queries: Use plain SQL for one-off tasks.
3.Handle duplicate errors in a PL/SQL procedure.
•For heavy computations: Offload to application logic.
4.Compare performance: Batch update in SQL vs. PL/SQL.
•For portability: PL/SQL is Oracle-specific.

4. Advantages of PL/SQL

•Improved performance: Reduces database calls by bundling logic.


•Security: Protects data with stored procedures.
•Reusability: Encapsulates complex logic.

39
Keep Learning!
40
Keep Learning!

41

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy