Lecture 03 1
Lecture 03 1
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
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.
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)
7
Oracle Architecture (1/2)
2. Listeners
▪ Listeners handle connections between user processes and the
Oracle database.
▪ They are configured using a listeners.ora file.
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.
This Is The Highest-level Diagram. Note That The Listener Process Often Runs Outside The Server, Especially In Clustered Environments.
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.
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.
Examples SELECT, INSERT, UPDATE, DELETE, CREATE, DROP. SET, SPOOL, DESCRIBE, PROMPT, SHOW.
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.
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.
Microsoft SQL Server T-SQL (Transact-SQL) Procedural extension used in Microsoft SQL Server.
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
Database Server
24
PL/SQL Architecture
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
Benefits
Better Extension of
Performance SQL
Procedural Conditional
Language Statement
Reduces
Network
Traffic
26
PL/SQL Key Features and Benefits - Examples
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;
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:
Code Reusability
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.
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;
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.
-- 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
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
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.
36
PL/SQL Disadvantage
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
4. Advantages of PL/SQL
39
Keep Learning!
40
Keep Learning!
41