Skip to main content

Welcome to DBA Master – Database Tips, Tricks, and Tutorials

Welcome to DBA Master ! This blog is dedicated to all things related to database administration , SQL optimization , and performance tuning . Whether you're a beginner or a seasoned DBA, you'll find practical guides, troubleshooting tips, and real-world tutorials to help you work smarter with data. What to Expect: SQL performance tuning tips Indexing strategies Backup and recovery best practices High availability and replication techniques Database creation, configuration, and setup Monitoring queries and scripts for proactive performance management Migration guides across different database platforms Security essentials and best practices Recommended tools for DBAs Real-world error fixes and how to solve them Stay tuned — exciting content is coming soon. Feel free to bookmark and share: www.dbamaster.com ! Thanks for visiting!

PLSQL Introduction

What is PL/SQL?

PL/SQL (Procedural Language for SQL) is Oracle's procedural extension of SQL, designed specifically for working within the Oracle database. It adds procedural constructs like loops, conditions, and error handling to SQL. PL/SQL allows developers to combine SQL statements with procedural code, creating reusable units such as procedures, functions, packages, and triggers.

Features of PL/SQL

  1. Block Structure: PL/SQL programs are structured into blocks of code, making it easier to manage, maintain, and debug.

·        Anonymous Block: Code that can be executed directly without storing it in the database.

·        Named Block: Procedures, Functions, Packages that are stored in the database.

  1. Error Handling: PL/SQL provides robust error handling using exceptions. This feature allows programmers to manage runtime errors effectively.
  2. Control Structures: It supports control structures like loops, conditions (IF-THEN-ELSE), and branches that are necessary for procedural logic.
  3. Cursors: PL/SQL provides implicit and explicit cursors to retrieve data row-by-row from a result set.
  4. Modular Programming: You can break your program into smaller manageable units like procedures, functions, packages, and triggers.
  5. Integration with SQL: PL/SQL allows you to execute SQL queries, including DML (Data Manipulation Language) and DDL (Data Definition Language), directly within its code.
  6. Triggers: PL/SQL supports triggers that automatically execute code in response to specific events on a table or a view, such as insertions or updates.
  7. Packages: It allows grouping procedures, functions, variables, and other PL/SQL code into packages to make code reusable and easier to manage.
  8. Portability: PL/SQL programs are portable between Oracle databases on different platforms.

Advantages of PL/SQL

  1. Tight Integration with SQL: PL/SQL works natively with SQL, allowing developers to combine procedural and declarative code seamlessly.
  2. Increased Performance: By bundling SQL statements into PL/SQL blocks, the number of calls between the application and the database is minimized, reducing network traffic and improving performance.
  3. Error Handling: PL/SQL provides robust mechanisms for catching and managing exceptions, which improves the stability and maintainability of applications.
  4. Modular Programming: It promotes modularity by enabling the creation of procedures, functions, and packages, which improves code reusability and maintainability.
  5. Security: Stored procedures and functions provide an extra layer of security because access to the underlying database can be controlled through controlled execution of PL/SQL code.
  6. Support for Complex Business Logic: PL/SQL can handle complex business rules and logic within the database itself, reducing the need for application-side processing and ensuring data consistency.
  7. Transaction Management: PL/SQL supports complex transaction management with the ability to COMMIT, ROLLBACK, and SAVEPOINT operations to ensure data integrity.
  8. Reduced Network Traffic: Since PL/SQL code executes within the database server, it reduces the need for back-and-forth communication between the client and server, reducing overall network traffic.

Types Of Blocks

·        Anonymous Blocks: These are unnamed PL/SQL code blocks that can be executed without being stored in the database.

·        Named Blocks: These include stored procedures, functions, and packages that are saved in the database for repeated use.

Difference between anonymous blocks and named blocks

Anonymous Block

Named Block (Procedure/Function)

No name (anonymous)

Has a name (Procedure/Function/Package)

Not stored in the database

Stored in the database schema

Executed immediately and discarded after execution

Can be invoked/called multiple times after definition

Not reusable after execution

Reusable and can be invoked by other programs or blocks

Quick, one-time, ad-hoc tasks

Repeated operations, modular programming

No, but can print or perform actions

Yes, functions return value

Structure of PL/SQL Block:

PL/SQL programs are divided into blocks, typically having the following structure:

  • Declaration Section: Declare variables, cursors, or exceptions.
  • Execution Section: Core logic where SQL statements, control statements, and procedure calls are placed.
  • Exception Handling Section: Manage errors or exceptions that may occur during execution.

DECLARE

declaration statements;

BEGIN

executable statements

EXCEPTIONS

exception handling statements

END;

 Example: (set serveroutput on;)

Begin

Dbms_output.put_line(‘welcome to pearldbs’);

End;

Data Types:

Category

Data Types

Numeric

NUMBER, BINARY_INTEGER, PLS_INTEGER, FLOAT, INTEGER, DECIMAL, etc.

Character

CHAR, VARCHAR2, LONG, CLOB, NCLOB, etc.

Date/Time

DATE, TIMESTAMP, INTERVAL YEAR TO MONTH, INTERVAL DAY TO SECOND

Boolean

BOOLEAN

LOBs

BLOB, CLOB, NCLOB, BFILE

Composite

RECORD, Associative Arrays, Nested Tables, Varrays

Cursor

SYS_REFCURSOR

Reference

REF, ROWID, UROWID

User-defined

Objects, User-defined types

Variable Declaration:

Variables

Variables are used to store data that can be changed during the execution of a PL/SQL block or subprogram.

variable_name data_type [:= initial_value];

Constants

Constants are similar to variables, but their value cannot be changed once assigned. Constants must be initialized at the time of declaration.

constant_name CONSTANT data_type := initial_value;

Records

A record is a composite data type that allows you to group multiple related data items of different types together. Each field in the record can hold a different type of data.

1.      %ROWTYPE

record_name table_name%ROWTYPE;

 

2.      User-Defined Record

TYPE record_type IS RECORD (

   field1 data_type,

   field2 data_type,

   fieldN data_type

);

record_name record_type;

  • Variables are mutable and hold a single data type.
  • Constants are immutable once assigned a value.
  • Records allow grouping of different fields (like a table row) and can hold multiple data types.

Example: (set serveroutput on;)

DECLARE

-- Constant declaration

company_name CONSTANT VARCHAR2(50) := 'ABC Corp';

-- Variable declaration

bonus NUMBER := 500;

-- Declaring a custom record type

TYPE employee_bonus_rec IS RECORD (

emp_name VARCHAR2(50),

emp_bonus NUMBER

);

employee_bonus employee_bonus_rec;  -- Record variable of type employee_bonus_rec

-- %ROWTYPE record declaration for the "employees" table

employee_record employees%ROWTYPE;

BEGIN

-- Fetching data into the %ROWTYPE record

SELECT * INTO employee_record FROM employees WHERE employee_id = 101;  -- Assuming employee_id 101 exists in the "employees" table   

--Assigning values to the custom record (user-defined record)

employee_bonus.emp_name := employee_record.first_name || ' ' || employee_record.last_name;

employee_bonus.emp_bonus := bonus;    -- Displaying the values

DBMS_OUTPUT.PUT_LINE('Company: ' || company_name);

DBMS_OUTPUT.PUT_LINE('Employee: ' || employee_bonus.emp_name);

DBMS_OUTPUT.PUT_LINE('Salary: ' || employee_record.salary);

DBMS_OUTPUT.PUT_LINE('Bonus: ' || employee_bonus.emp_bonus);

END;

Sample Table and Data:

CREATE TABLE employees (

   employee_id NUMBER PRIMARY KEY,

   first_name VARCHAR2(50),

   last_name VARCHAR2(50),

   salary NUMBER,

   hire_date DATE

);

 

INSERT INTO employees (employee_id, first_name, last_name, salary, hire_date)

VALUES (1001, 'John', 'Doe', 5000, TO_DATE('2022-01-15', 'YYYY-MM-DD'));

 

INSERT INTO employees (employee_id, first_name, last_name, salary, hire_date)

VALUES (1002, 'Jane', 'Smith', 6000, TO_DATE('2021-06-20', 'YYYY-MM-DD'));

 

INSERT INTO employees (employee_id, first_name, last_name, salary, hire_date)

VALUES (1003, 'Alice', 'Johnson', 5500, TO_DATE('2023-03-10', 'YYYY-MM-DD'));

 

INSERT INTO employees (employee_id, first_name, last_name, salary, hire_date)

VALUES (1004, 'Bob', 'Brown', 7000, TO_DATE('2020-11-25', 'YYYY-MM-DD'));

 

INSERT INTO employees (employee_id, first_name, last_name, salary, hire_date)

VALUES (1005, 'Carol', 'Davis', 6500, TO_DATE('2019-09-12', 'YYYY-MM-DD'));


Comments

Popular posts from this blog

Oracle Database 19C Performance Tunning - PART 1

Advantages: 1. Improved Query Performance •    Optimized SQL execution plans lead to faster query response times. •    Reduces unnecessary full table scans and improves indexing strategies. •    Parallel execution tuning speeds up large data processing tasks. 2. Better Resource Utilization •    Efficient use of CPU, memory, disk I/O, and network resources. •    Reduces contention on Redo Logs, Undo Tablespaces, and Buffer Cache. •    Helps in load balancing across multiple instances in RAC (Real Application Clusters). 3. Increased System Scalability •    Ensures that the database can handle a growing number of users and transactions. •    Proper tuning allows scaling without degrading performance. •    Optimized parallel processing ensures better performance on multi-core servers. 4. Lower Infrastructure Costs •    Reduces the need for add...

Oracle RMAN Backup And Restore

RMAN: (Oracle 8) RMAN (Recovery Manager) is a utility provided by Oracle Database to perform backup, restore, and recovery operations. It is a command line tool. Features of RMAN in Oracle 19c Comprehensive Backup Capabilities: Full and incremental backups. Block-level backups for efficient data storage. Archived redo log backups. Fast Recovery Area (FRA) integration for centralized backup storage. Efficient Recovery Options: Point-in-time recovery (PITR). Complete and incomplete recovery. Flashback database capabilities for quick undo of changes. Multitenant Database Support: RMAN fully supports container databases (CDBs) and pluggable databases (PDBs). Provides flexibility to back up and recover individual PDBs or entire CDBs. Automatic Space Management: Manages disk space in the FRA. Automatically deletes obsolete backups and archived logs. Data Deduplication and Compression: Backup optimization through block-level deduplication. Built-in compression algorithms to reduce storage req...

Oracle 19c Database Software Installation in OEL8

 Pre-requisites for OS level:            Set the static IP Address     Disable the Firewall (systemctl stop firewalld & systemctl disable firewalld)     set SELINUX=permissive on /etc/selinux/config  ##Need to restart the server use init 6 Oracle Installation Pre-requisites Methods     Automatic Setup     Manual Setup      Automatic requisites Setup: (avoid step 1 to step 5): dnf install -y oracle-database-preinstall-19c Install the dependencies: curl -o oracle-database-preinstall-19c-1.0-2.el8.x86_64.rpm https://yum.oracle.com/repo/OracleLinux/OL8/appstream/x86_64/getPackage/oracle-database-preinstall-19c-1.0-2.el8.x86_64.rpm dnf -y localinstall oracle-database-preinstall-19c-1.0-2.el8.x86_64.rpm Manual Setup: step 1: Add the karenl parameters and values vi /etc/sysctl.conf     fs.file-max = 6815744 kernel.sem = 250 32000 100 128 kernel....