The Wayback Machine - https://web.archive.org/web/20240916002259/https://www.geeksforgeeks.org/plsql-introduction/
Open In App

PL/SQL Introduction

Last Updated : 23 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

PL/SQL is a block structured language that enables developers to combine the power of SQL with procedural statements.All the statements of a block are passed to oracle engine all at once which increases processing speed and decreases the traffic. 

Basics of PL/SQL

  • •PL/SQL stands for Procedural Language extensions to the Structured Query Language (SQL).
  •  PL/SQL is a combination of SQL along with the procedural features of programming languages.
  • Oracle uses a PL/SQL engine to processes the PL/SQL statements.
  • PL/SQL includes procedural language elements like conditions and loops. It allows declaration of constants and variables, procedures and functions, types and variable of those types and triggers.

Disadvantages of SQL:

  • SQL doesn’t provide the programmers with a technique of condition checking, looping and branching.
  • SQL statements are passed to Oracle engine one at a time which increases traffic and decreases speed.
  • SQL has no facility of error checking during manipulation of data.

Features of PL/SQL:

  1. PL/SQL is basically a procedural language, which provides the functionality of decision making, iteration and many more features of procedural programming languages.
  2. PL/SQL can execute a number of queries in one block using single command.
  3. One can create a PL/SQL unit such as procedures, functions, packages, triggers, and types, which are stored in the database for reuse by applications.
  4. PL/SQL provides a feature to handle the exception which occurs in PL/SQL block known as exception handling block.
  5. Applications written in PL/SQL are portable to computer hardware or operating system where Oracle is operational.
  6. PL/SQL Offers extensive error checking.

Differences between SQL and PL/SQL:

SQL PL/SQL
SQL is a single query that is used to perform DML and DDL operations. PL/SQL is a block of codes that used to write the entire program blocks/ procedure/ function, etc.
It is declarative, that defines what needs to be done, rather than how things need to be done. PL/SQL is procedural that defines how the things needs to be done.
Execute as a single statement. Execute as a whole block.
Mainly used to manipulate data. Mainly used to create an application.
Cannot contain PL/SQL code in it. It is an extension of SQL, so it can contain SQL inside it.

Structure of PL/SQL Block:

PL/SQL extends SQL by adding constructs found in procedural languages, resulting in a structural language that is more powerful than SQL. The basic unit in PL/SQL is a block. All PL/SQL programs are made up of blocks, which can be nested within each other.  

Typically, each block performs a logical action in the program. A block has the following structure:

DECLARE
    declaration statements;

BEGIN
    executable statements

EXCEPTIONS
    exception handling statements

END;
  • Declare section starts with DECLARE keyword in which variables, constants, records as cursors can be declared which stores data temporarily. It basically consists definition of PL/SQL identifiers. This part of the code is optional.
  • Execution section starts with BEGIN and ends with END keyword.This is a mandatory section and here the program logic is written to perform any task like loops and conditional statements. It supports all DML commands, DDL commands and SQL*PLUS built-in functions as well.
  • Exception section starts with EXCEPTION keyword.This section is optional which contains statements that are executed when a run-time error occurs. Any exceptions can be handled in this section.

PL/SQL identifiers

There are several PL/SQL identifiers such as variables, constants, procedures, cursors, triggers etc.

  1. Variables: Like several other programming languages, variables in PL/SQL must be declared prior to its use. They should have a valid name and data type as well. Syntax for declaration of variables:
variable_name datatype [NOT NULL := value ];
  1. Example to show how to declare variables in PL/SQL : 

C




SQL> SET SERVEROUTPUT ON;
 
SQL> DECLARE
    var1 INTEGER;
    var2 REAL;
    var3 varchar2(20) ;
 
BEGIN
    null;
END;
/


  1. Output:
PL/SQL procedure successfully completed.
  1. Explanation:
    • SET SERVEROUTPUT ON: It is used to display the buffer used by the dbms_output.
    • var1 INTEGER : It is the declaration of variable, named var1 which is of integer type. There are many other data types that can be used like float, int, real, smallint, long etc. It also supports variables used in SQL as well like NUMBER(prec, scale), varchar, varchar2 etc.
    • PL/SQL procedure successfully completed.: It is displayed when the code is compiled and executed successfully.
    • Slash (/) after END;: The slash (/) tells the SQL*Plus to execute the block.
    • Assignment operator (:=) : It is used to assign a value to a variable.
  2. Displaying Output: The outputs are displayed by using DBMS_OUTPUT which is a built-in package that enables the user to display output, debugging information, and send messages from PL/SQL blocks, subprograms, packages, and triggers. Let us see an example to see how to display a message using PL/SQL : 

C




SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
     var varchar2(40) := 'I love GeeksForGeeks' ;
 
  BEGIN
     dbms_output.put_line(var);
 
  END;
  /


  1. Output:
I love GeeksForGeeks

PL/SQL procedure successfully completed.
  1. Explanation:
    • dbms_output.put_line : This command is used to direct the PL/SQL output to a screen.
  2. Using Comments: Like in many other programming languages, in PL/SQL also, comments can be put within the code which has no effect in the code. There are two syntaxes to create comments in PL/SQL :
    • Single Line Comment: To create a single line comment , the symbol – – is used.
    • Multi Line Comment: To create comments that span over several lines, the symbol /* and */ is used.
  3. Taking input from user: Just like in other programming languages, in PL/SQL also, we can take input from the user and store it in a variable. Let us see an example to show how to take input from users in PL/SQL: 

C




SQL> SET SERVEROUTPUT ON;
 
SQL> DECLARE
 
      -- taking input for variable a
      a number := &a;      
       
      -- taking input for variable b
      b varchar2(30) := &b;    
 
  BEGIN
      null;
 
  END;
  /


  1. Output:
Enter value for a: 24
old   2: a number := &a;
new   2: a number := 24;
Enter value for b: 'GeeksForGeeks'
old   3: b varchar2(30) := &b;
new   3: b varchar2(30) := 'GeeksForGeeks';

PL/SQL procedure successfully completed.
  1. (***) Let us see an example on PL/SQL to demonstrate all above concepts in one single block of code. 

C




--PL/SQL code to print sum of two numbers taken from the user.
SQL> SET SERVEROUTPUT ON;
 
SQL> DECLARE
      
     -- taking input for variable a
     a integer := &a ;
      
     -- taking input for variable b
     b integer := &b ;
     c integer ;
 
  BEGIN
     c := a + b ;
     dbms_output.put_line('Sum of '||a||' and '||b||' is = '||c);
 
  END;
  /


Enter value for a: 2
Enter value for b: 3

Sum of 2 and 3 is = 5

PL/SQL procedure successfully completed.

PL/SQL Execution Environment:

The PL/SQL engine resides in the Oracle engine.The Oracle engine can process not only single SQL statement but also block of many statements.The call to Oracle engine needs to be made only once to execute any number of SQL statements if these SQL statements are bundled inside a PL/SQL block.



Similar Reads

Introduction of Relational Model and Codd Rules in DBMS
Pre-Requisite: Relational Model in DBMS It was proposed by Dr. E.F. Codd. It uses the concept of relations to represent each and every file. Relations are Two-Dimensional Tables. It is easy to implement and easy to simplification in the operations to manipulate the data. This is the most popular data model. It is simple to implement. It uses the pr
12 min read
PHP | MySQL Database Introduction
What is MySQL? MySQL is an open-source relational database management system (RDBMS). It is the most popular database system used with PHP. MySQL is developed, distributed, and supported by Oracle Corporation. The data in a MySQL database are stored in tables which consists of columns and rows.MySQL is a database system that runs on a server.MySQL
4 min read
Introduction to TimeStamp and Deadlock Prevention Schemes in DBMS
Deadlock occurs when each transaction T in a schedule of two or more transactions waiting for some item locked by some other transaction T' in the set. Thus, both end up in a deadlock situation, waiting for the other to release the lock on the item. Deadlocks are a common problem and we have introduced the problem while solving the Concurrency Cont
7 min read
Introduction to Large Objects (LOBs)
Large Objects(LOBs) are a collection of datatypes which is designed to hold a large amount of data. A LOB is able to hold up to maximum size ranging from 8 terabytes to 128 terabytes, depending upon how your database is configured. Storing data into LOBs helps you to manipulate & access data efficiently in your own application. Why use large ob
2 min read
Introduction of MS SQL Server
Data is a collection of facts and figures and we have humungous data available to the users via the internet and other sources. To manipulate the data, Structured Query Language (SQL) in short has been introduced years ago. There are different versions of SQL available in the market provided by different organizations. In this article, we shall see
2 min read
Introduction of MariaDB
MariaDB is one of the most popular open-source relational database management system and could be used as a great replacement of MySQL. It is developed by original developers of MySQL. MariaDB can also stores data in various tables. It is also part of most cloud offerings and default in most Linux distributions. To establish the relationship betwee
2 min read
Introduction to Apache CouchDB
Apache CouchDB was developed by Apache Software Foundation and initially released in 2005. CouchDB is written in Erlang. It is an open-source database that uses various different formats and protocols to store, transfer, and process its data. It uses JSON to store data, JavaScript as its query language using MapReduce, and HTTP for an API. Document
3 min read
Introduction to Couchbase
Couchbase Server is an open-source, distributed, multi-model NoSQL, JSON document database that is enhanced for interactive applications. It is also known as Membase. It was developed by Couchbase, Inc. and initially released in August 2010. It is written using C++, Erlang, C, Go languages. Its server is designed to provide us with easy-to-scale ke
3 min read
Introduction to PostgreSQL PL/pgSQL
In this, we will discuss the overview of PostgreSQL PL/pgSQL and will also cover the CRUD(CREATE, READ, UPDATE, DELETE) operations with the help of the example of each operation and finally will discuss the advantages and disadvantages of PostgreSQL PL/pgSQL. Let's discuss it one by one.PostgreSQL :It is a powerful, open-source object-relational da
4 min read
Introduction of Standby Database
Have you ever thought of scenario where primary database generated is corrupted and what is going to happen in this case? Since database is corrupted, how do we get values and update database by inserting new data? In order to face this situation and maintain the smooth functioning of system, there is concept of standby database. A standby database
2 min read
Introduction of Shadow Paging
Shadow Paging is recovery technique that is used to recover database. In this recovery technique, database is considered as made up of fixed size of logical units of storage which are referred as pages. pages are mapped into physical blocks of storage, with help of the page table which allow one entry for each logical page of database. This method
5 min read
Introduction of Enterprise Database
Today is world that is full of data. We have ample number of resources which generate data on daily basis and all these data are stored in very secure manner in databases. All data is linked to each other in Database. With help of database, it becomes easy to, insert, use and remove data as per need. For example, If we consider blog website data st
4 min read
Introduction to Transaction Processing
Single user system : In this at-most, only one user at a time can use the system. Multi-user system : In the same, many users can access the system concurrently. Concurrency can be provided through : Interleaved Processing - In this, the concurrent execution of processes is interleaved in a single CPU. The transactions are interleaved, meaning the
2 min read
Introduction of Parallel Database
In this article, we will discuss the overview of Parallel Databases and then will emphasize their needs and advantages, and then finally, will cover the performance measurement factor-like Speedup and Scale-up with examples. Let's discuss it one by one. Parallel Databases :Nowadays organizations need to handle a huge amount of data with a high tran
3 min read
Introduction to Informatica
Informatica is an IT firm established by Mr Dillon in California in the year 1995-96. People often refer to Informatica as software, but there are some technical tools developed by Informatica which they intend to mean. Informatica offers various data products like ETL, data migration, data integration, data virtualization, data masking, data repli
3 min read
Introduction of Shared Memory Segment
Introduction of Shared Memory Segment :The quickest kind of IPC accessible is shared memory. There is no kernel participation in transmitting data between processes after the memory is mapped into the address space of the processes that are sharing the memory region. However, some type of synchronization between the processes that save and retrieve
6 min read
Introduction to Graph Database on NoSQL
A graph database is a type of NoSQL database that is designed to handle data with complex relationships and interconnections. In a graph database, data is stored as nodes and edges, where nodes represent entities and edges represent the relationships between those entities. Graph databases are particularly well-suited for applications that require
8 min read
Introduction to NoSQL Cloud Database Services
NoSQL Cloud Database Services are cloud-based database services that provide scalable, high-performance, and cost-effective solutions for storing and retrieving data. NoSQL (Not Only SQL) databases are designed to handle large volumes of unstructured, semi-structured, and structured data, and can easily scale horizontally to accommodate increased d
6 min read
Introduction To Temporal Database
Pre-requisites: Database A temporal database is a database that needs some aspect of time for the organization of information. In the temporal database, each tuple in relation is associated with time. It stores information about the states of the real world and time. The temporal database does store information about past states it only stores info
3 min read
HQL | Introduction
Introduction Hibernate Query Language (HQL) is an easy to learn and powerful query language designed as an object-oriented extension to SQL that bridges the gap between the object-oriented systems and relational databases. The HQL syntax is very similar to the SQL syntax. it has a rich and powerful object-oriented query language available with the
4 min read
Introduction of 3-Tier Architecture in DBMS - Set 2
The 3-tier architecture is a commonly used architectural approach in Database Management Systems (DBMSs) for the design and development of applications that work with databases. The 3-tier architecture divides an application’s components into three tiers or layers. Each layer has its own set of responsibilities. DBMS 3-Tier architecture divides the
6 min read
Introduction of B-Tree
The limitations of traditional binary search trees can be frustrating. Meet the B-Tree, the multi-talented data structure that can handle massive amounts of data with ease. When it comes to storing and searching large amounts of data, traditional binary search trees can become impractical due to their poor performance and high memory usage. B-Trees
15+ min read
Introduction of B+ Tree
B + Tree is a variation of the B-tree data structure. In a B + tree, data pointers are stored only at the leaf nodes of the tree. In a B+ tree structure of a leaf node differs from the structure of internal nodes. The leaf nodes have an entry for every value of the search field, along with a data pointer to the record (or to the block that contains
8 min read
Introduction of Database Normalization
Normalization is an important process in database design that helps improve the database's efficiency, consistency, and accuracy. It makes it easier to manage and maintain the data and ensures that the database is adaptable to changing business needs. What is Database Normalization?Database normalization is the process of organizing the attributes
7 min read
What is Graph Database - Introduction
What is a Graph Database?A graph database (GDB) is a database that uses graph structures for storing data. It uses nodes, edges, and properties instead of tables or documents to represent and store data. The edges represent relationships between the nodes. This helps in retrieving data more easily and, in many cases, with one operation. Graph datab
4 min read
Introduction to NoSQL
NoSQL is a type of database management system (DBMS) that is designed to handle and store large volumes of unstructured and semi-structured data. Unlike traditional relational databases that use tables with pre-defined schemas to store data, NoSQL databases use flexible data models that can adapt to changes in data structures and are capable of sca
10 min read
Introduction of Relational Algebra in DBMS
Pre-Requisite: Relational Model in DBMS Relational Algebra is a procedural query language. Relational algebra mainly provides a theoretical foundation for relational databases and SQL. The main purpose of using Relational Algebra is to define operators that transform one or more input relations into an output relation. Given that these operators ac
4 min read
Introduction to SQLite
SQLite is a highly efficient, serverless, and self-contained SQL database engine that stands out for its simplicity and ease of integration. Designed to be embedded within applications, SQLite eliminates the need for separate database server processes and complex configurations. In this article, We will learn about SQLite in detail. What is SQLite?
9 min read
Introduction of ER Model
Peter Chen developed the ER diagram in 1976. The ER model was created to provide a simple and understandable model for representing the structure and logic of databases. It has since evolved into variations such as the Enhanced ER Model and the Object Relationship Model The Entity Relational Model is a model for identifying entities to be represent
10 min read
Introduction of DBMS (Database Management System)
A database is a collection of interrelated data that helps in the efficient retrieval, insertion, and deletion of data from the database and organizes the data in the form of tables, views, schemas, reports, etc. For Example, a university database organizes the data about students, faculty, admin staff, etc. which helps in the efficient retrieval,
8 min read
Article Tags :