rdbms.pdf plsql database system notes for students to studyrarelyused
PL/SQL is a powerful procedural extension for SQL developed by Oracle, integrating features of both SQL and programming languages. It supports various programming structures, error handling, and can be utilized for web applications, with advantages like high performance and portability. PL/SQL consists of logical blocks with specific syntax, supporting complex data types, loops, and subprograms for modular programming.
The document discusses PL/SQL, its advantages over SQL, and its basic structure and components. PL/SQL was developed by Oracle Corporation as a procedural extension to SQL. It allows for programming constructs like loops and conditionals. A PL/SQL block consists of a declare, begin, exception, and end section. It supports data types, variables, constants, control structures, and cursors. Cursors store the results of a SQL query and can be either implicit or explicitly defined.
PL/SQL Complete Tutorial. All Topics CoveredDanish Mehraj
This document is a comprehensive tutorial on PL/SQL, a procedural language extension for SQL developed by Oracle. It covers the basics of PL/SQL, its features, advantages, and programming constructs, providing guidance for software professionals aiming to gain intermediate expertise. Key topics include data types, syntax, variables, and the structure of PL/SQL programming.
The document provides an introduction to PL/SQL, a procedural language extension for SQL that allows developers to create blocks of code for efficient database interaction. It covers the structure of PL/SQL blocks, including data types, variables, control structures (conditional statements and loops), cursors, procedures, and functions. Furthermore, it explains the advantages of using PL/SQL for performance improvement in database operations compared to executing single SQL queries.
The document outlines PL/SQL, an extension of SQL that combines data manipulation with procedural programming, enabling the creation of schema objects like stored procedures, functions, packages, triggers, and cursors. It details the structure of PL/SQL blocks, including sections for declaration, execution, and exception handling, as well as how to use variables and control structures like loops and conditional statements. The document also illustrates the integration of SQL commands within PL/SQL programs, emphasizing the need for careful management of data types and execution flow.
PL/SQL is a procedural language extension for SQL that allows for the processing of SQL and procedural language elements. It was developed by Oracle Corporation to enhance the capabilities of SQL. PL/SQL code is organized into blocks that contain a declarative section, executable section, and exception section. It is an embedded language executed by the Oracle database server and is used for developing stored procedures and triggers.
PL/SQL is a combination of SQL and procedural programming languages. It allows developers to perform operations like control flow statements, variable declarations, and exception handling. PL/SQL code is organized into blocks that contain a declarative part, an executable part, and an optional exception-handling part. Variables and other objects can be declared locally or globally depending on their scope. Control structures like IF-THEN-ELSE, CASE, and loops allow conditional and iterative execution. Procedures and functions can also be created to reuse code.
PL SQL.pptx in computer language in databaseironman82715
PL/SQL is a procedural extension of SQL that enables combining SQL statements with procedural constructs like loops and conditionals. It allows for modular programming through blocks, error handling, and supporting features such as cursors and variable declarations. Key components include defining functions and procedures, handling exceptions, and creating triggers for various database events.
PL/SQL is Oracle's procedural language extension to SQL that allows developers to write programs that combine SQL statements to manipulate data with procedural programming constructs like variables, conditions, and loops. PL/SQL code can be executed on the Oracle server for improved performance compared to executing multiple SQL statements individually. PL/SQL blocks contain a declaration section, executable section, and optional exception handling section. Named blocks can be stored in the database as procedures, functions, or packages while anonymous blocks are executed once.
This document provides an overview of PL/SQL programming. It outlines an agenda that introduces PL/SQL and covers basic and advanced syntax. The introduction defines PL/SQL and outlines its advantages like block structures, procedural capabilities, and error handling. Basic syntax covers blocks, operators, comments, variables and data types. Advanced topics include cursors, procedures, functions, parameters, and exception handling. Triggers are also introduced as PL/SQL blocks triggered by data changes. Examples are provided throughout to illustrate key PL/SQL concepts.
PL/SQL (Procedural Language/Structured Query Language) is Oracle Corporation's procedural extension
for SQL and the Oracle relational database. PL/SQL is available in Oracle Database (since version 7).
PL/SQL (Procedural Language extensions to SQL) is designed specifically for the seamless processing of
SQL commands. PL/SQL stored and compiled in the database, runs within the Oracle executable and
inherits the robustness, security, and portability of the Oracle Database.
PL/SQL is a combination of SQL along with the procedural features of programming languages.
SQL Programming in database Management Systemssuserb8d5cb
PL/SQL is a block-structured procedural language that enhances SQL with procedural statements, improving execution speed and allowing for various programming features such as exception handling and data type management. It is straightforward to learn, making it a portable choice for Oracle database development. Key features include control structures like conditional, iterative, and sequential statements, as well as exception handling for runtime errors.
Oracle PL/SQL online training | PL/SQL online Trainingsuresh
PL/SQL is Oracle's procedural language extension to SQL that allows mixing of SQL statements and procedural logic like conditionals and loops. It uses SQL for data manipulation and its own control structures for processing. PL/SQL program units include anonymous blocks and stored procedures. Stored procedures are reusable blocks of code stored in the database under a name that can be executed. PL/SQL provides features like variables, control structures, exception handling, and modular programming with functions and procedures.
This document provides an overview of PL/SQL including:
- PL/SQL block structure with declare, execution, and exception sections
- Variables, constants, datatypes
- Control structures like IF/ELSE statements and loop structures
- Procedures and functions
- Uses of PL/SQL include combining SQL with procedural logic, writing reusable code, and handling exceptions.
The document provides an introduction to PL/SQL, explaining its architecture, basic syntax, and key components such as procedures, functions, cursors, and packages. It highlights how PL/SQL extends SQL by allowing procedural programming, thereby offering enhanced data manipulation capabilities. The document concludes by emphasizing the advantages of PL/SQL, including its integration with SQL, high performance, portability, and security.
PL/SQL is Oracle Corporation's procedural extension for SQL that allows storing compiled code in a database. It combines SQL with procedural programming features. PL/SQL code is written in blocks that declare variables and handle exceptions, with an executable section using control structures like loops. It prints messages using dbms_output and supports object-oriented programming and web application development.
PL/SQL is Oracle Corporation's procedural extension for SQL that allows storing compiled code in a database. It combines SQL with procedural programming features. PL/SQL code is written in blocks that declare variables and handle exceptions, with an executable section using control structures like loops. It prints messages using dbms_output and supports object-oriented programming and web application development.
PL/SQL is Oracle Corporation's procedural extension for SQL that allows storing compiled code in a database. It combines SQL with procedural programming features. PL/SQL code is written in blocks that declare variables and handle exceptions, with an executable section using control structures like loops. It prints messages using dbms_output and supports object-oriented programming and web application development.
The document provides an overview of PL/SQL, a procedural language extension to SQL used for Oracle databases, detailing its block structure, variable declarations, flow control, and exception handling. It outlines the benefits of using PL/SQL, such as improved performance and integration of procedural constructs, and includes examples of variable declarations, control structures (if statements, case statements), and loop constructs. Additionally, it discusses guidelines for naming and initializing variables, along with the use of bind variables and the %type attribute.
PL/SQL is a database-oriented programming language that extends SQL with procedural capabilities like condition checking, looping, and branching. It allows programmers to handle errors and display user-friendly error messages. PL/SQL code is organized into declarative regions, and it can define variables, constants, cursors, procedures, and functions. Cursors are used to process result sets from a SQL query row by row.
PL/SQL is a block structured language that enables developers to combine the ...renuka b
PL/SQL is an extension of SQL used in Oracle that combines the power of data manipulation with procedural programming capabilities, allowing developers to write complex queries and programs. It features a structured block architecture comprising declaration, execution, and exception-handling sections, enabling features like error handling and programmatic control. Key components include the PL/SQL engine, which processes code, and the database server, which stores data and executes SQL statements from PL/SQL blocks.
PL/SQL is an extension of SQL that allows procedural logic to be added to SQL statements and queries. Key features of PL/SQL include blocks, exceptions, cursors, procedures, functions, packages, and triggers. A PL/SQL block contains a declare section to define variables, an executable section to contain program logic, and an optional exception section. Exceptions can be predefined, non-predefined, or user-defined. The document provides examples of handling different types of exceptions within PL/SQL blocks to avoid abnormal program termination.
This document contains lecture material on Relational Database Management Systems (RDBMS) and PL/SQL prepared by D.GAYA, an Assistant Professor of Computer Science at Pondicherry University Community College. The document covers PL/SQL concepts such as blocks, variables, data manipulation using DML statements, triggers, procedures, functions, packages, and exception handling. It provides examples and explanations of PL/SQL blocks, variable declaration and assignment, data types, and manipulating data through insertion, updating, deletion, and selection using SQL statements within PL/SQL blocks. The document is intended to teach second year B.Voc students in the Software Development program about PL/SQL and RDBMS.
The document provides an overview of PL/SQL and server-side database programming. It discusses:
1) What PL/SQL is and how it extends SQL with programming features like variables, loops, and conditionals to allow for procedural logic on the server-side.
2) The advantages of server-side programming using PL/SQL over client-side programming, including improved performance due to reduced network traffic and ability to reuse code.
3) Key PL/SQL concepts like blocks, data types, scope rules, operators, program flow control structures, exceptions, and subprograms like procedures and functions.
PL/SQL is a block-structured language used for accessing and manipulating Oracle databases. A PL/SQL block contains three parts: a declarative section, executable section, and exception-handling section. PL/SQL supports both scalar and composite datatypes. Control structures include conditional statements like IF-THEN-ELSE and CASE, and iterative statements like LOOP, WHILE, and FOR. Database interaction is done through SQL statements and cursors, which allow processing of multiple rows returned from a query.
PL/SQL, or Procedural Language/Structured Query Language, is an Oracle-specific programming language that extends SQL by incorporating procedural programming capabilities such as control structures and exception handling. It enables developers to write stored procedures, functions, and triggers directly in the database, supporting robust database application development. PL/SQL includes data types, variable declarations, and lexical units, making it essential for managing relational databases.
PL/SQL is a combination of SQL and procedural programming languages. It allows developers to perform operations like control flow statements, variable declarations, and exception handling. PL/SQL code is organized into blocks that contain a declarative part, an executable part, and an optional exception-handling part. Variables and other objects can be declared locally or globally depending on their scope. Control structures like IF-THEN-ELSE, CASE, and loops allow conditional and iterative execution. Procedures and functions can also be created to reuse code.
PL SQL.pptx in computer language in databaseironman82715
PL/SQL is a procedural extension of SQL that enables combining SQL statements with procedural constructs like loops and conditionals. It allows for modular programming through blocks, error handling, and supporting features such as cursors and variable declarations. Key components include defining functions and procedures, handling exceptions, and creating triggers for various database events.
PL/SQL is Oracle's procedural language extension to SQL that allows developers to write programs that combine SQL statements to manipulate data with procedural programming constructs like variables, conditions, and loops. PL/SQL code can be executed on the Oracle server for improved performance compared to executing multiple SQL statements individually. PL/SQL blocks contain a declaration section, executable section, and optional exception handling section. Named blocks can be stored in the database as procedures, functions, or packages while anonymous blocks are executed once.
This document provides an overview of PL/SQL programming. It outlines an agenda that introduces PL/SQL and covers basic and advanced syntax. The introduction defines PL/SQL and outlines its advantages like block structures, procedural capabilities, and error handling. Basic syntax covers blocks, operators, comments, variables and data types. Advanced topics include cursors, procedures, functions, parameters, and exception handling. Triggers are also introduced as PL/SQL blocks triggered by data changes. Examples are provided throughout to illustrate key PL/SQL concepts.
PL/SQL (Procedural Language/Structured Query Language) is Oracle Corporation's procedural extension
for SQL and the Oracle relational database. PL/SQL is available in Oracle Database (since version 7).
PL/SQL (Procedural Language extensions to SQL) is designed specifically for the seamless processing of
SQL commands. PL/SQL stored and compiled in the database, runs within the Oracle executable and
inherits the robustness, security, and portability of the Oracle Database.
PL/SQL is a combination of SQL along with the procedural features of programming languages.
SQL Programming in database Management Systemssuserb8d5cb
PL/SQL is a block-structured procedural language that enhances SQL with procedural statements, improving execution speed and allowing for various programming features such as exception handling and data type management. It is straightforward to learn, making it a portable choice for Oracle database development. Key features include control structures like conditional, iterative, and sequential statements, as well as exception handling for runtime errors.
Oracle PL/SQL online training | PL/SQL online Trainingsuresh
PL/SQL is Oracle's procedural language extension to SQL that allows mixing of SQL statements and procedural logic like conditionals and loops. It uses SQL for data manipulation and its own control structures for processing. PL/SQL program units include anonymous blocks and stored procedures. Stored procedures are reusable blocks of code stored in the database under a name that can be executed. PL/SQL provides features like variables, control structures, exception handling, and modular programming with functions and procedures.
This document provides an overview of PL/SQL including:
- PL/SQL block structure with declare, execution, and exception sections
- Variables, constants, datatypes
- Control structures like IF/ELSE statements and loop structures
- Procedures and functions
- Uses of PL/SQL include combining SQL with procedural logic, writing reusable code, and handling exceptions.
The document provides an introduction to PL/SQL, explaining its architecture, basic syntax, and key components such as procedures, functions, cursors, and packages. It highlights how PL/SQL extends SQL by allowing procedural programming, thereby offering enhanced data manipulation capabilities. The document concludes by emphasizing the advantages of PL/SQL, including its integration with SQL, high performance, portability, and security.
PL/SQL is Oracle Corporation's procedural extension for SQL that allows storing compiled code in a database. It combines SQL with procedural programming features. PL/SQL code is written in blocks that declare variables and handle exceptions, with an executable section using control structures like loops. It prints messages using dbms_output and supports object-oriented programming and web application development.
PL/SQL is Oracle Corporation's procedural extension for SQL that allows storing compiled code in a database. It combines SQL with procedural programming features. PL/SQL code is written in blocks that declare variables and handle exceptions, with an executable section using control structures like loops. It prints messages using dbms_output and supports object-oriented programming and web application development.
PL/SQL is Oracle Corporation's procedural extension for SQL that allows storing compiled code in a database. It combines SQL with procedural programming features. PL/SQL code is written in blocks that declare variables and handle exceptions, with an executable section using control structures like loops. It prints messages using dbms_output and supports object-oriented programming and web application development.
The document provides an overview of PL/SQL, a procedural language extension to SQL used for Oracle databases, detailing its block structure, variable declarations, flow control, and exception handling. It outlines the benefits of using PL/SQL, such as improved performance and integration of procedural constructs, and includes examples of variable declarations, control structures (if statements, case statements), and loop constructs. Additionally, it discusses guidelines for naming and initializing variables, along with the use of bind variables and the %type attribute.
PL/SQL is a database-oriented programming language that extends SQL with procedural capabilities like condition checking, looping, and branching. It allows programmers to handle errors and display user-friendly error messages. PL/SQL code is organized into declarative regions, and it can define variables, constants, cursors, procedures, and functions. Cursors are used to process result sets from a SQL query row by row.
PL/SQL is a block structured language that enables developers to combine the ...renuka b
PL/SQL is an extension of SQL used in Oracle that combines the power of data manipulation with procedural programming capabilities, allowing developers to write complex queries and programs. It features a structured block architecture comprising declaration, execution, and exception-handling sections, enabling features like error handling and programmatic control. Key components include the PL/SQL engine, which processes code, and the database server, which stores data and executes SQL statements from PL/SQL blocks.
PL/SQL is an extension of SQL that allows procedural logic to be added to SQL statements and queries. Key features of PL/SQL include blocks, exceptions, cursors, procedures, functions, packages, and triggers. A PL/SQL block contains a declare section to define variables, an executable section to contain program logic, and an optional exception section. Exceptions can be predefined, non-predefined, or user-defined. The document provides examples of handling different types of exceptions within PL/SQL blocks to avoid abnormal program termination.
This document contains lecture material on Relational Database Management Systems (RDBMS) and PL/SQL prepared by D.GAYA, an Assistant Professor of Computer Science at Pondicherry University Community College. The document covers PL/SQL concepts such as blocks, variables, data manipulation using DML statements, triggers, procedures, functions, packages, and exception handling. It provides examples and explanations of PL/SQL blocks, variable declaration and assignment, data types, and manipulating data through insertion, updating, deletion, and selection using SQL statements within PL/SQL blocks. The document is intended to teach second year B.Voc students in the Software Development program about PL/SQL and RDBMS.
The document provides an overview of PL/SQL and server-side database programming. It discusses:
1) What PL/SQL is and how it extends SQL with programming features like variables, loops, and conditionals to allow for procedural logic on the server-side.
2) The advantages of server-side programming using PL/SQL over client-side programming, including improved performance due to reduced network traffic and ability to reuse code.
3) Key PL/SQL concepts like blocks, data types, scope rules, operators, program flow control structures, exceptions, and subprograms like procedures and functions.
PL/SQL is a block-structured language used for accessing and manipulating Oracle databases. A PL/SQL block contains three parts: a declarative section, executable section, and exception-handling section. PL/SQL supports both scalar and composite datatypes. Control structures include conditional statements like IF-THEN-ELSE and CASE, and iterative statements like LOOP, WHILE, and FOR. Database interaction is done through SQL statements and cursors, which allow processing of multiple rows returned from a query.
PL/SQL, or Procedural Language/Structured Query Language, is an Oracle-specific programming language that extends SQL by incorporating procedural programming capabilities such as control structures and exception handling. It enables developers to write stored procedures, functions, and triggers directly in the database, supporting robust database application development. PL/SQL includes data types, variable declarations, and lexical units, making it essential for managing relational databases.
HADOOP ECO SYSTEM Pig: Introduction to PIG, Execution Modes of Pig, Comp...RajendraKankrale1
The document outlines the syllabus for a Big Data Analytics course focusing on the Hadoop ecosystem including key components like Pig, Hive, HBase, Flume, Sqoop, Oozie, Zookeeper, and Mahout. Each component is briefly described, highlighting its role and functionality within the Hadoop framework. The course aims to equip students with knowledge of data processing, storage, and analysis using various tools and languages associated with big data.
The document outlines a course on Big Data Analytics with a focus on Apache Hadoop and MapReduce. It provides a detailed history of Hadoop's development, detailing its founders, significant milestones, and how it evolved from earlier technologies to effectively manage and process large datasets. Additionally, it explains the architecture of Hadoop's components, including HDFS and YARN, highlighting their roles in data storage, fault tolerance, and efficient processing.
Unit2_Regression, ADVANCED ANALYTICAL THEORY AND METHODS USING PYTHONRajendraKankrale1
The document outlines a course on Big Data Analytics focusing on Advanced Analytical Theory and Methods using Python, specifically regression techniques. It covers concepts such as linear and multiple linear regression, evaluates models using metrics like mean squared error and R-squared, and details the implementation using libraries like scikit-learn. Additionally, it explains the significance of regression in data analysis for predicting continuous values based on independent variables.
Unit-I_Big data life cycle.pptx, sources of Big DataRajendraKankrale1
The document outlines the Big Data Analytics life cycle, detailing six key phases: discovery, data preparation, model planning, model building, communication results, and operationalization. It emphasizes the significance of big data analytics in improving business decision-making, predicting trends, and enhancing customer experiences, while also highlighting various tools and applications across sectors like healthcare, retail, and banking. Additionally, the document describes different types of big data analytics and the importance of ensuring high data quality throughout the lifecycle.
Structured Programming with C++ :: Kjell BackmanShabista Imam
Step into the world of high-performance programming with the Complete Guidance Book of C++ Programming—a definitive resource for mastering one of the most powerful and versatile languages in computer science.
Whether you're a beginner looking to learn the fundamentals or an intermediate developer aiming to sharpen your skills, this book walks you through C++ from the ground up. You'll start with basics like variables, control structures, and functions, then progress to object-oriented programming (OOP), memory management, file handling, templates, and the Standard Template Library (STL).
Complete guidance book of Asp.Net Web APIShabista Imam
Unlock the full potential of modern web development with the Complete Guidance Book of ASP.NET Web API—your all-in-one resource for mastering RESTful services using Microsoft’s powerful ASP.NET Core framework. This book takes you on a step-by-step journey from beginner to expert, covering everything from routing and controllers to security, performance optimization, and real-world architecture.
Comparison of Flexible and Rigid Pavements in BangladeshArifur Rahman
In Bangladesh, flexible and rigid pavements are commonly used for road infrastructure, each with distinct characteristics and performance under local climatic and traffic conditions. Flexible pavements, composed of bituminous layers, are more adaptable to subgrade movements and are widely used due to lower initial costs, but they require frequent maintenance under heavy traffic and monsoon-related moisture damage. In contrast, rigid pavements, made from concrete, offer longer service life, higher load-carrying capacity, and better resistance to water damage, making them suitable for highways and industrial zones, although they involve higher construction costs and longer curing times. The choice between the two depends on factors like traffic volume, maintenance capacity, and budget considerations.
Slides from IEEE PEDG 2025 Conference in Nanajing. Addresses need for re-examining grid stability when using large numbers of inverter-based resources.
Call For Papers - 17th International Conference on Wireless & Mobile Networks...hosseinihamid192023
17th International Conference on Wireless & Mobile Networks (WiMoNe 2025) will provide
an excellent international forum for sharing knowledge and results in theory, methodology and
applications of Wireless & Mobile computing Environment. Current information age is witnessing
a dramatic use of digital and electronic devices in the workplace and beyond. Wireless, Mobile
Networks & its applications had received a significant and sustained research interest in terms of
designing and deploying large scale and high performance computational applications in real life.
The aim of the conference is to provide a platform to the researchers and practitioners from both
academia as well as industry to meet and share cutting-edge development in the field.
Generative AI & Scientific Research : Catalyst for Innovation, Ethics & ImpactAlqualsaDIResearchGr
Invited keynote at the Artificial Intelligence Symposium on AI-powered Research Innovation, taking place at ENSEM (L'École Nationale Supérieure d'Électricité et de Mécanique), Casablanca on June 21, 2025. I’ll be giving a keynote titled: "Generative AI & Scientific Research: Catalyst for Innovation, Ethics & Impact". Looking forward to engaging with researchers and doctoral students on how Generative AI is reshaping the future of science, from discovery to governance — with both opportunities and responsibilities in focus.
#AI hashtag#GenerativeAI #ScientificResearch #Innovation #Ethics #Keynote #AIinScience #GAI #ResearchInnovation #Casablanca
1. Thinking, Creative Thinking, Innovation
2. Societies Evolution from 1.0 to 5.0
3. AI - 3P Approach, Use Cases & Innovation
4. GAI & Creativity
5. TrustWorthy AI
6. Guidelines on The Responsible use of GAI In Research
May 2025: Top 10 Read Articles in Data Mining & Knowledge Management ProcessIJDKP
Data mining and knowledge discovery in databases have been attracting a significant amount of research, industry, and media attention of late. There is an urgent need for a new generation of computational theories and tools to assist researchers in extracting useful information from the rapidly growing volumes of digital data.
This Journal provides a forum for researchers who address this issue and to present their work in a peer-reviewed open access forum. Authors are solicited to contribute to the Journal by submitting articles that illustrate research results, projects, surveying works and industrial experiences that describe significant advances in the following areas, but are not limited to these topics only.
1. Database Management System (DBMS)
Sanjivani Rural Education Society’s
Sanjivani College of Engineering, Kopargaon-423603
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
NACC ‘A’ Grade Accredited, ISO 9001:2015 Certified
Department of Information Technology
(NBAAccredited)
Mr. R. N. Kankrale
Assistant Professor
SY IT
2. Introduction to PL/SQL
• PL/SQL is Procedural Language for SQL. It is designed by Oracle
Corporation in the early 90's to enhance SQL. It is combination of SQL
along with the procedural features wherein it is easy to both read and
write. PL/SQL is high performing transaction-processing language,
which is completely portable. It dispenses a built-in, interpreted and
OS independent programming environment. User can directly call to
database from external programming language calls. PL/SQL
incoporates procedural language elements such as loops and
conditions. It can manage run-time error and allows declaration of
constants and variables, procedures and functions, types and
variables. In this, all the statements of a block are moved to oracle
engine at once which decreases the traffic and increases processing
speed.
DBMS – Unit-III PL/SQL Department of Information Technology
3. Introduction to PL/SQL
DBMS – Unit-III PL/SQL Department of Information Technology
PL/SQL in MySQL – Explanation and Alternative Approach
Does MySQL Support PL/SQL?
No, PL/SQL (Procedural Language/SQL) is specifically used in Oracle Database.
MySQL does not support PL/SQL, but it has a similar feature called Procedural
SQL (PSM - Persistent Stored Modules), which includes:
✅ Stored Procedures
✅ Functions
✅ Triggers
✅ Cursors
✅ Exception Handling
In MySQL, we use stored procedures and begin-end blocks to implement
procedural programming, similar to PL/SQL.
4. Introduction to PL/SQL
DBMS – Unit-III PL/SQL Department of Information Technology
PL/SQL (Oracle) MySQL Equivalent
BEGIN ... END; BEGIN ... END;
EXCEPTION DECLARE HANDLER
LOOP LOOP ... END LOOP;
CURSOR CURSOR
IF-THEN-ELSE IF-THEN-ELSE
RAISE SIGNAL SQLSTATE
7. Introduction to PL/SQL
DBMS – Unit-III PL/SQL Department of Information Technology
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.
8. Structure of PL/SQL Block
• 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.
DBMS – Unit-III PL/SQL Department of Information Technology
9. Introduction to PL/SQL
DBMS – Unit-III PL/SQL Department of Information Technology
DECLARE
declaration statements;
BEGIN
executable statements
EXCEPTIONS
exception handling statements
END;
10. Structure of PL/SQL Block
• DECLARE
• declaration statements;
• BEGIN
• executable statements
• EXCEPTIONS
• exception handling statements
• END;
DBMS – Unit-III PL/SQL Department of Information Technology
11. Structure of PL/SQL Block
• 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.
DBMS – Unit-III PL/SQL Department of Information Technology
12. PL/SQL Variables
• Following is the syntax for declaring variable:
• variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value]
• Here, variable_name is a valid identifier in PL/SQL and datatype must be valid
PL/SQL data type. A data type with size, scale or precision limit is called a
constrained declaration. The constrained declaration needs less memory than
unconstrained declaration.
• Example:
• Radius Number := 5;
• Date_of_birth date;
DBMS – Unit-III PL/SQL Department of Information Technology
13. PL/SQL Variables
• SQL> SET SERVEROUTPUT ON;
• SQL> DECLARE
• var1 INTEGER;
• var2 REAL;
• var3 varchar2(20) ;
• BEGIN
• null;
• END;
• /
• Output:
• PL/SQL procedure successfully completed.
DBMS – Unit-III PL/SQL Department of Information Technology
14. PL/SQL Variables
• 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 :
• SQL> SET SERVEROUTPUT ON;
• SQL> DECLARE
• var varchar2(40) := 'GeeksForGeeks' ;
• BEGIN
• dbms_output.put_line(var);
• END;
• /
• Output:
• GeeksForGeeks
• PL/SQL procedure successfully completed.
DBMS – Unit-III PL/SQL Department of Information Technology
15. PL/SQL Variables
• --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;
• /
DBMS – Unit-III PL/SQL Department of Information Technology
16. PL/SQL Variables
• Enter value for a: 2
• Enter value for b: 3
• Sum of 2 and 3 is = 5
• PL/SQL procedure successfully completed.
DBMS – Unit-III PL/SQL Department of Information Technology
17. Decision Making in PL/SQL
• (if-then , if-then-else, Nested if-then, if-then-elsif-then-else )
Improve
• declare
• -- declare the values here
• begin
• if condition then
• dbms_output.put_line('output');
• end if;
• dbms_output.put_line('output2');
• end;
DBMS – Unit-III PL/SQL Department of Information Technology
18. Decision Making in PL/SQL
-- pl/sql program to illustrate If statement
declare
num1 number:= 10;
num2 number:= 20;
begin
if num1 > num2 then
dbms_output.put_line('num1 small');
end if;
dbms_output.put_line('I am Not in if');
end;
DBMS – Unit-III PL/SQL Department of Information Technology
19. Decision Making in PL/SQL
-- pl/sql program to illustrate If else statement
declare
num1 number:= 10;
num2 number:= 20;
begin
if num1 < num2 then
dbms_output.put_line('i am in if block');
ELSE
dbms_output.put_line('i am in else Block');
end if;
dbms_output.put_line('i am not in if or else Block');
end;
DBMS – Unit-III PL/SQL Department of Information Technology
20. Decision Making in PL/SQL
Output:-
i'm in if Block
i'm not in if and not in else Block
DBMS – Unit-III PL/SQL Department of Information Technology
21. Decision Making in PL/SQL
DBMS – Unit-III PL/SQL Department of Information Technology
22. DBMS – Unit-III PL/SQL Department of Information Technology
-- pl/sql program to illustrate nested If statement
declare
num1 number:= 10;
num2 number:= 20;
num3 number:= 20;
begin
if num1 < num2 then
dbms_output.put_line('num1 small num2');
if num1 < num3 then
dbms_output.put_line('num1 small num3 also');
end if;
end if;
dbms_output.put_line('after end if');
end;
Decision Making in PL/SQL
23. Decision Making in PL/SQL
DBMS – Unit-III PL/SQL Department of Information Technology
if-then-
elsif-
then-
else
ladder
24. DBMS – Unit-III PL/SQL Department of Information Technology
if-then-elsif-then-else ladder
-- pl/sql program to illustrate if-then-elif-then-else ladder
declare
num1 number:= 10;
num2 number:= 20;
begin
if num1 < num2 then
dbms_output.put_line('num1 small');
ELSEIF num1 = num2 then
dbms_output.put_line('both equal');
ELSE
dbms_output.put_line('num2 greater');
end if;
dbms_output.put_line('after end if');
end;
25. PL/SQL Case Statement
DBMS – Unit-III PL/SQL Department of Information Technology
• The PL/SQL CASE statement facilitates you to execute a sequence of statements
based on a selector. A selector can be anything such as variable, function or an
expression that the CASE statement checks to a boolean value.
• The CASE statement works like the IF statement, only using the keyword WHEN. A
CASE statement is evaluated from top to bottom. If it get the condition TRUE, then
the corresponding THEN clause is executed and the execution goes to the END CASE
clause.
26. PL/SQL Case Statement
DBMS – Unit-III PL/SQL Department of Information Technology
Syntax for the CASE Statement:
1.CASE [ expression ]
2.WHEN condition_1 THEN result_1
3. WHEN condition_2 THEN result_2
4. ...
5. WHEN condition_n THEN result_n
6. ELSE result
7.END
27. Example of PL/SQL case statement
DBMS – Unit-III PL/SQL Department of Information Technology
1.DECLARE
2. grade char(1) := 'A';
3.BEGIN
4. CASE grade
5. when 'A' then dbms_output.put_line('Excellent');
6. when 'B' then dbms_output.put_line('Very good');
7. when 'C' then dbms_output.put_line('Good');
8. when 'D' then dbms_output.put_line('Average');
9. when 'F' then dbms_output.put_line('Passed with Grace')
;
10. else dbms_output.put_line('Failed');
11. END CASE;
12.END;
28. Example of PL/SQL case statement
DBMS – Unit-III PL/SQL Department of Information Technology
1.After the execution of above code, you will get the
following result:
Excellent
PL/SQL procedure successfully completed.
29. PL/SQL Loop
DBMS – Unit-III PL/SQL Department of Information Technology
1.The PL/SQL loops are used to repeat the execution of one or more statements for
specified number of times. These are also known as iterative control statements.
Syntax for a basic loop:
2.LOOP
3. Sequence of statements;
4.END LOOP;
Types of PL/SQL Loops
There are 4 types of PL/SQL Loops.
5.Basic Loop / Exit Loop
6.While Loop
7.For Loop
8.Cursor For Loop
30. PL/SQL Loop
DBMS – Unit-III PL/SQL Department of Information Technology
PL/SQL Exit Loop (Basic Loop)
PL/SQL exit loop is used when a set of statements is to be executed at least
once before the termination of the loop. There must be an EXIT condition
specified in the loop, otherwise the loop will get into an infinite number of
iterations. After the occurrence of EXIT condition, the process exits the loop.
Syntax of basic loop:
1.LOOP
2. Sequence of statements;
3.END LOOP;
31. PL/SQL Loop
DBMS – Unit-III PL/SQL Department of Information Technology
Syntax of exit loop:
1.LOOP
2. statements;
3. EXIT;
4. {or EXIT WHEN condition;}
5.END LOOP;
32. Example of PL/SQL EXIT Loop
DBMS – Unit-III PL/SQL Department of Information Technology
1.DECLARE
2.i NUMBER := 1;
3.BEGIN
4.LOOP
5.EXIT WHEN i>10;
6.DBMS_OUTPUT.PUT_LINE(i);
7.i := i+1;
8.END LOOP;
9.END;
33. Example of PL/SQL EXIT Loop
DBMS – Unit-III PL/SQL Department of Information Technology
After the execution of the above code, you will get the following result:
1
2
3
4
5
6
7
8
9
10
34. Example of PL/SQL EXIT Loop
DBMS – Unit-III PL/SQL Department of Information Technology
Note: You must follow these steps while using PL/SQL Exit Loop.
• Initialize a variable before the loop body
• Increment the variable in the loop.
• You should use EXIT WHEN statement to exit from the Loop.
Otherwise the EXIT statement without WHEN condition, the
statements in the Loop is executed only once.
35. Example 2 of PL/SQL EXIT Loop
DBMS – Unit-III PL/SQL Department of Information Technology
1.DECLARE
2.VAR1 NUMBER;
3.VAR2 NUMBER;
4.BEGIN
5.VAR1:=100;
6.VAR2:=1;
7.LOOP
8.DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
9.IF (VAR2=10) THEN
10.EXIT;
11.END IF;
12.VAR2:=VAR2+1;
13.END LOOP;
14.END;
36. Example 2 of PL/SQL EXIT Loop
DBMS – Unit-III PL/SQL Department of Information Technology
Output:
100
200
300
400
500
600
700
800
900
1000
37. PL/SQL While Loop
DBMS – Unit-III PL/SQL Department of Information Technology
PL/SQL while loop is used when a set of statements has to be executed as long as a
condition is true, the While loop is used. The condition is decided at the beginning of
each iteration and continues until the condition becomes false.
Syntax of while loop:
1.WHILE <condition>
2. LOOP statements;
3.END LOOP;
38. PL/SQL While Loop
DBMS – Unit-III PL/SQL Department of Information Technology
Example of PL/SQL While Loop
Let's see a simple example of PL/SQL WHILE loop.
1.DECLARE
2.i INTEGER := 1;
3.BEGIN
4.WHILE i <= 10 LOOP
5.DBMS_OUTPUT.PUT_LINE(i);
6.i := i+1;
7.END LOOP;
8.END;
39. PL/SQL While Loop
DBMS – Unit-III PL/SQL Department of Information Technology
After the execution of the above code, you will get the following
result:
1
2
3
4
5
6
7
8
9
10
40. PL/SQL While Loop
DBMS – Unit-III PL/SQL Department of Information Technology
PL/SQL WHILE Loop Example 2
1.DECLARE
2.VAR1 NUMBER;
3.VAR2 NUMBER;
4.BEGIN
5.VAR1:=200;
6.VAR2:=1;
7.WHILE (VAR2<=10)
8.LOOP
9.DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
10.VAR2:=VAR2+1;
11.END LOOP;
12.END;
41. PL/SQL While Loop
DBMS – Unit-III PL/SQL Department of Information Technology
Output:
200
400
600
800
1000
1200
1400
1600
1800
2000
42. PL/SQL FOR Loop
DBMS – Unit-III PL/SQL Department of Information Technology
PL/SQL FOR Loop
PL/SQL for loop is used when you want to execute a set of
statements for a predetermined number of times. The loop is
iterated between the start and end integer values. The counter is
always incremented by 1 and once the counter reaches the value
of end integer, the loop ends.
Syntax of for loop:
1.FOR counter IN initial_value .. final_value LOOP
2. LOOP statements;
3.END LOOP;
43. PL/SQL FOR Loop
DBMS – Unit-III PL/SQL Department of Information Technology
PL/SQL For Loop Example 1
Let's see a simple example of PL/SQL FOR loop.
1.BEGIN
2.FOR k IN 1..10 LOOP
3.-- note that k was not declared
4.DBMS_OUTPUT.PUT_LINE(k);
5.END LOOP;
6.END;
44. PL/SQL FOR Loop
DBMS – Unit-III PL/SQL Department of Information Technology
PL/SQL For Loop Example 2
1.DECLARE
2.VAR1 NUMBER;
3.BEGIN
4.VAR1:=10;
5.FOR VAR2 IN 1..10
6.LOOP
7.DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
8.END LOOP;
9.END;
45. PL/SQL FOR Loop
DBMS – Unit-III PL/SQL Department of Information Technology
PL/SQL For Loop REVERSE Example 3
Let's see an example of PL/SQL for loop where we are using REVERSE
keyword.
1.DECLARE
2.VAR1 NUMBER;
3.BEGIN
4.VAR1:=10;
5.FOR VAR2 IN REVERSE 10..1
6.LOOP
7.DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
8.END LOOP;
9.END;
46. PL/SQL Procedure
DBMS – Unit-III PL/SQL Department of Information Technology
The PL/SQL stored procedure or simply a procedure is a PL/SQL
block which performs one or more specific tasks. It is just like
procedures in other programming languages.
The procedure contains a header and a body.
• Header: The header contains the name of the procedure and
the parameters or variables passed to the procedure.
• Body: The body contains a declaration section, execution
section and exception section similar to a general PL/SQL block.
47. PL/SQL Procedure
DBMS – Unit-III PL/SQL Department of Information Technology
DELIMITER $$
CREATE PROCEDURE GetCustomers()
BEGIN
SELECT
customerName,
city,
state,
postalCode,
country
FROM
customers
ORDER BY customerName;
END$$
DELIMITER ;
48. PL/SQL Procedure
DBMS – Unit-III PL/SQL Department of Information Technology
After saving the stored procedure, you can invoke it by using the CALL
statement:
CALL GetCustomers();
49. MySQL stored procedure parameters
DBMS – Unit-III PL/SQL Department of Information Technology
A parameter in a stored procedure has one of three modes: IN, OUT, or INOUT.
IN parameters
IN is the default mode. When defining an IN parameter in a stored procedure, the calling
program must pass an argument to the stored procedure.
Additionally, the value of an IN parameter is protected. This means that even if you
change the value of the IN parameter inside the stored procedure, its original value
remains unchanged after the stored procedure ends. In other words, the stored procedure
works only on the copy of the IN parameter.
50. MySQL stored procedure parameters
DBMS – Unit-III PL/SQL Department of Information Technology
OUT parameters
The value of an OUT parameter can be modified within the stored
procedure, and its updated value is then passed back to the calling
program.
INOUT parameters
An INOUT parameter is a combination of IN and OUT parameters. This
means that the calling program may pass the argument, and the stored
procedure can modify the INOUT parameter and pass the new value back to
the calling program.
Defining a parameter
Here is the basic syntax for defining a parameter in stored procedures:
[IN | OUT | INOUT] parameter_name datatype[(length)]
51. MySQL stored procedure parameter examples
DBMS – Unit-III PL/SQL Department of Information Technology
The IN parameter example
The following example creates a stored procedure that finds all offices that are located in a country
specified by the input parameter countryName:
DELIMITER //
CREATE PROCEDURE GetOfficeByCountry(IN countryName VARCHAR(255))
BEGIN
SELECT *
FROM offices
WHERE country = countryName;
END //
DELIMITER ;
52. MySQL stored procedure parameter examples
DBMS – Unit-III PL/SQL Department of Information Technology
office_id office_name city country phone
1 Head Office New York USA +1-212-555-1234
2 Branch Office Los Angeles USA +1-310-555-5678
3 European HQ London UK +44-20-555-7890
4 Asia Pacific Office Tokyo Japan +81-3-555-6789
5 South America Office São Paulo Brazil +55-11-555-4321
offices
53. MySQL stored procedure parameter examples
DBMS – Unit-III PL/SQL Department of Information Technology
The IN parameter example
The following example creates a stored procedure that finds all offices that are located in a country
specified by the input parameter countryName:
DELIMITER //
CREATE PROCEDURE GetOfficeByCountry(IN countryName VARCHAR(255))
BEGIN
SELECT *
FROM offices
WHERE country = countryName;
END //
DELIMITER ;
CALL GetOfficeByCountry('France’);
CALL GetOfficeByCountry('USA');
54. MySQL stored procedure parameter examples
DBMS – Unit-III PL/SQL Department of Information Technology
The IN parameter example
Because the countryName is the IN parameter, you must pass an argument. If you don’t do so, you’ll get an
error:
CALL GetOfficeByCountry();
Error Code: 1318. Incorrect number of arguments for PROCEDURE
classicmodels.GetOfficeByCountry; expected 1, got 0
55. MySQL stored procedure parameter examples
DBMS – Unit-III PL/SQL Department of Information Technology
The OUT-parameter example
The following defines a stored procedure that returns the number of orders based on their order status.
DELIMITER $$
CREATE PROCEDURE GetOrderCountByStatus (IN orderStatus VARCHAR(25),OUT total INT)
BEGIN
SELECT COUNT(orderNumber)
INTO total
FROM orders
WHERE status = orderStatus;
END$$
DELIMITER ;
56. MySQL stored procedure parameter examples
DBMS – Unit-III PL/SQL Department of Information Technology
The stored procedure GetOrderCountByStatus() has two parameters:
The orderStatus is the IN parameter specifies the status of orders to return.
The total is the OUT parameter that stores the number of orders in a specific status.
To find the number of orders that already shipped, you call GetOrderCountByStatus and pass the order status
as of Shipped, and also pass a session variable ( @total ) to receive the return value.
CALL GetOrderCountByStatus('Shipped',@total);
SELECT @total;
+--------+
| @total |
+--------+
| 303 |
+--------+
1 row in set (0.00 sec)
57. MySQL stored procedure parameter examples
DBMS – Unit-III PL/SQL Department of Information Technology
CALL GetOrderCountByStatus('In Process',@total);
SELECT @total AS total_in_process;
+------------------+
| total_in_process |
+------------------+
| 6 |
+------------------+
1 row in set (0.00 sec)
58. MySQL stored procedure parameter examples
DBMS – Unit-III PL/SQL Department of Information Technology
The INOUT parameter example
The following example demonstrates how to use an INOUT parameter in a stored
procedure:
DELIMITER $$
CREATE PROCEDURE SetCounter(INOUT counter INT,IN inc INT)
BEGIN
SET counter = counter + inc;
END$$
DELIMITER ;
In this example, the stored procedure SetCounter() accepts one INOUT
parameter ( counter ) and one IN parameter ( inc ). It increases the counter
( counter ) by the value specified by the inc parameter.
59. MySQL stored procedure parameter examples
DBMS – Unit-III PL/SQL Department of Information Technology
The INOUT parameter example
These statements illustrate how to call the SetSounter stored procedure:
SET @counter = 1;
CALL SetCounter(@counter,1); -- 2
CALL SetCounter(@counter,1); -- 3
CALL SetCounter(@counter,5); -- 8
SELECT @counter; -- 8
Code language: SQL (Structured Query Language) (sql)
Here is the output:
61. MySQL Cursor
DBMS – Unit-III PL/SQL Department of Information Technology
In MySQL, a cursor is a database object used for iterating the result of a SELECT
statement.
Typically, you use cursors within stored procedures, triggers, and functions where you
need to process individual rows returned by a query one at a time.
Here’s the basic syntax of a cursor:
-- declare a cursor
DECLARE cursor_name CURSOR FOR
SELECT column1, column2
FROM your_table
WHERE your_condition;
62. MySQL Cursor
DBMS – Unit-III PL/SQL Department of Information Technology
-- open the cursor
OPEN cursor_name;
FETCH cursor_name INTO variable1, variable2;
-- process the data
-- close the cursor
CLOSE cursor_name;
63. MySQL Cursor
DBMS – Unit-III PL/SQL Department of Information Technology
When working with MySQL cursor, you must also declare a NOT FOUND handler to
manage the situation when the cursor cannot find any row.
Each time you call the FETCH statement; the cursor attempts to read the next row
in the result set. When the cursor reaches the end of the result set, it will not be
able to retrieve the data, and a condition is raised. The handler is used to handle
this condition.
To declare a NOT FOUND handler, you use the following syntax:
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
The finished is a variable to indicate that the cursor has reached the end of the
result set.
Notice that the handler declaration must appear after the variable and cursor
declarations within the stored procedures.
64. MySQL Cursor
DBMS – Unit-III PL/SQL Department of Information Technology
MySQL Cursor Example
We’ll develop a stored procedure that creates an email list of all employees in the
employees table in the sample database:
65. MySQL Cursor
DBMS – Unit-III PL/SQL Department of Information Technology
DELIMITER $$
CREATE PROCEDURE create_email_list (INOUT email_list TEXT)
BEGIN
DECLARE done BOOL DEFAULT false;
DECLARE email_address VARCHAR(100) DEFAULT "";
-- declare cursor for employee email
DECLARE cur CURSOR FOR SELECT email FROM employees;
66. MySQL Cursor
DBMS – Unit-III PL/SQL Department of Information Technology
-- declare NOT FOUND handler
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = true;
-- open the cursor
OPEN cur;
67. MySQL Cursor
DBMS – Unit-III PL/SQL Department of Information Technology
SET email_list = ‘ ';
process_email: LOOP
FETCH cur INTO email_address;
IF done = true THEN
LEAVE process_email;
END IF;
SET email_list = CONCAT(email_address,";",email_list);
END LOOP;
CLOSE cur;
END$$
DELIMITER ;
68. MySQL Cursor
DBMS – Unit-III PL/SQL Department of Information Technology
Example: Using a Cursor in MySQL
• We will create a stored procedure that loops through employees and calculates a
bonus for each employee.
• Step 1: Create an employees Table
• CREATE TABLE employees ( emp_id INT PRIMARY KEY, emp_name
VARCHAR(100), salary DECIMAL(10,2));
• INSERT INTO employees (emp_id, emp_name, salary) VALUES
• (1, 'John Doe', 5000.00),
• (2, 'Jane Smith', 6000.00),
• (3, 'Robert Brown', 4500.00);
69. MySQL Cursor
DBMS – Unit-III PL/SQL Department of Information Technology
DELIMITER //
CREATE PROCEDURE CalculateBonus()
BEGIN
-- Declare variables
DECLARE done INT DEFAULT 0;
DECLARE empId INT;
DECLARE empName VARCHAR(100);
DECLARE empSalary DECIMAL(10,2);
DECLARE empBonus DECIMAL(10,2);
--
70. MySQL Cursor
DBMS – Unit-III PL/SQL Department of Information Technology
-- Declare a cursor to fetch employee records
DECLARE emp_cursor CURSOR FOR
SELECT emp_id, emp_name, salary FROM employees;
-- Declare a handler for end of cursor
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
-- Open the cursor
OPEN emp_cursor;
71. DBMS – Unit-III PL/SQL Department of Information Technology
-- Loop through the records
read_loop: LOOP
FETCH emp_cursor INTO empId, empName, empSalary;
-- Exit loop if no more records
IF done THEN
LEAVE read_loop;
END IF;
-- Calculate a 10% bonus
SET empBonus = empSalary * 0.10;
72. MySQL Cursor
DBMS – Unit-III PL/SQL Department of Information Technology
-- Print employee bonus (in real case, we can insert into another table)
SELECT CONCAT(empName, ' gets a bonus of $', empBonus) AS BonusInfo;
END LOOP;
-- Close the cursor
CLOSE emp_cursor;
END //
DELIMITER ;
73. MySQL Cursor
DBMS – Unit-III PL/SQL Department of Information Technology
Step 4: Call the Procedure
CALL CalculateBonus();
Expected Output:
BonusInfo
--------------------------
John Doe gets a bonus of $500.00
Jane Smith gets a bonus of $600.00
Robert Brown gets a bonus of $450.00
74. MySQL Triggers
DBMS – Unit-III PL/SQL Department of Information Technology
In MySQL, a trigger is a stored program invoked automatically in response to
an event such as insert, update, or delete that occurs in the associated table.
For example, you can define a trigger that is invoked automatically before a
new row is inserted into a table.
75. MySQL Triggers
DBMS – Unit-III PL/SQL Department of Information Technology
• The SQL standard defines two types of triggers: row-level triggers and
statement-level triggers.
• A row-level trigger is activated for each row that is inserted, updated, or
deleted. For example, if a table has 100 rows inserted, updated, or deleted, the
trigger is automatically invoked 100 times for the 100 rows affected.
• A statement-level trigger is executed once for each transaction regardless of
how many rows are inserted, updated, or deleted.
76. MySQL Triggers
DBMS – Unit-III PL/SQL Department of Information Technology
MySQL supports only row-level triggers. It doesn’t support statement-
level triggers.
77. Advantages of triggers
DBMS – Unit-III PL/SQL Department of Information Technology
• Triggers provide another way to check the integrity of data.
• Triggers handle errors from the database layer.
• Triggers give an alternative way to run scheduled tasks. By using triggers, you
don’t have to wait for the scheduled events to run because the triggers are
invoked automatically before or after a change is made to the data in a table.
• Triggers can be useful for auditing the data changes in tables.
78. Disadvantages of triggers
DBMS – Unit-III PL/SQL Department of Information Technology
• Triggers can only provide extended validations, not all validations. For simple
validations, you can use the NOT NULL, UNIQUE, CHECK and FOREIGN KEY
constraints.
• Triggers can be difficult to troubleshoot because they execute automatically in the
database, which may not be visible to the client applications.
• Triggers may increase the overhead of the MySQL server.
79. Managing MySQL triggers
DBMS – Unit-III PL/SQL Department of Information Technology
• Introduction to MySQL SHOW TRIGGER statement
• The SHOW TRIGGERS statement list triggers defined for tables in the current database.
The following illustrates the basic syntax of the SHOW TRIGGERS statement:
SHOW TRIGGERS
[{FROM | IN} database_name]
[LIKE 'pattern' | WHERE search_condition];
80. Managing MySQL triggers
DBMS – Unit-III PL/SQL Department of Information Technology
In this syntax, if you don’t use the last two clauses, the SHOW TRIGGERS returns all
triggers in all databases:
SHOW TRIGGERS;
To show all triggers in a specific database, you specify the database name after
the FROM or IN keyword like this:
SHOW TRIGGERS
FROM database_name;
or
SHOW TRIGGERS
IN database_name;
81. Managing MySQL triggers
DBMS – Unit-III PL/SQL Department of Information Technology
To list triggers according to a pattern, you use the LIKE clause:
SHOW TRIGGERS
LIKE 'pattern';
Code language: SQL (Structured Query Language) (sql)
or
SHOW TRIGGERS
FROM database_name
LIKE 'pattern';
82. Managing MySQL triggers
DBMS – Unit-III PL/SQL Department of Information Technology
To find triggers that match a condition, you use the WHERE clause:
SHOW TRIGGERS
WHERE search_condition;
Code language: SQL (Structured Query Language) (sql)
or
SHOW TRIGGERS
FROM database_name
WHERE search_condition;
83. Managing MySQL triggers
DBMS – Unit-III PL/SQL Department of Information Technology
The SHOW TRIGGERS statement returns a result set that includes the following columns:
trigger: the name of the trigger
event: the event that invokes the trigger e.g., INSERT, UPDATE, or DELETE.
table: the table to which the trigger belongs.
statement: the body of the trigger.
timing: the activation time of the trigger, either BEFORE or AFTER.
created: the created time of the trigger.
sql_mode: the SQL_MODE when the trigger executes.
definer: the user account that created the trigger.
character_set_client
collation_connection
database collation
84. Managing MySQL triggers
DBMS – Unit-III PL/SQL Department of Information Technology
MySQL SHOW TRIGGER statement examples
SHOW TRIGGERS;
Code language: SQL (Structured Query Language) (sql)
The following example shows all triggers in the classicmodels database:
SHOW TRIGGERS
FROM classicmodels;
Code language: SQL (Structured Query Language) (sql)
The following statement list all the triggers associated with the employees table:
SHOW TRIGGERS
FROM classicmodels
WHERE table = 'employees';
85. Introduction to MySQL CREATE TRIGGER statement
DBMS – Unit-III PL/SQL Department of Information Technology
The CREATE TRIGGER statement allows you to create a new trigger
associated with a table.
CREATE TRIGGER trigger_name
{BEFORE | AFTER} {INSERT | UPDATE | DELETE}
ON table_name
FOR EACH ROW
BEGIN
-- Trigger body (SQL statements)
END;
86. Introduction to MySQL CREATE TRIGGER statement
DBMS – Unit-III PL/SQL Department of Information Technology
In this syntax:
• trigger_name: Name of the trigger.
• BEFORE or AFTER: Specifies when the trigger should be executed.
• INSERT, UPDATE, or DELETE: Specifies the type of operation that activates the
trigger.
• table_name: Name of the table on which the trigger is defined.
• FOR EACH ROW: Indicates that the trigger should be executed once for each
row affected by the triggering event.
• BEGIN and END: Delimit the trigger body, where you define the SQL statements
to be executed.
87. Introduction to MySQL CREATE TRIGGER statement
DBMS – Unit-III PL/SQL Department of Information Technology
The trigger body can access the values of the column being affected by the operation.
To distinguish between the value of the columns BEFORE and AFTER the event has fired,
you use the NEW and OLD modifiers. For example, if you update the value in the
description column, in the trigger body, you can access the value of the description column
before the update OLD.description and the new value NEW.description.
The following table illustrates the availability of the OLD and NEW modifiers:
Trigger Event OLD NEW
INSERT No Yes
UPDATE Yes Yes
DELETE Yes No
88. MySQL trigger example
DBMS – Unit-III PL/SQL Department of Information Technology
First, create a new table called items:
CREATE TABLE items (
id INT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
price DECIMAL(10, 2) NOT NULL
);
Second, insert a row into the items table:
INSERT INTO items(id, name, price)
VALUES (1, 'Item', 50.00);
89. MySQL trigger example
DBMS – Unit-III PL/SQL Department of Information Technology
Third, create the item_changes table to store the changes made to the data in the
items table:
CREATE TABLE item_changes (
change_id INT PRIMARY KEY AUTO_INCREMENT,
item_id INT,
change_type VARCHAR(10),
change_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (item_id) REFERENCES items(id)
);
90. MySQL trigger example
DBMS – Unit-III PL/SQL Department of Information Technology
Fourth, create a trigger called update_items_trigger associated with the items table:
DELIMITER //
CREATE TRIGGER update_items_trigger
AFTER UPDATE
ON items
FOR EACH ROW
BEGIN
INSERT INTO item_changes (item_id, change_type)
VALUES (NEW.id, 'UPDATE');
END;
//
DELIMITER ;
91. MySQL trigger example
DBMS – Unit-III PL/SQL Department of Information Technology
In this example:
The trigger is named update_items_trigger.
It is set to execute AFTER UPDATE on the items table.
The trigger body inserts a record into the item_changes table with the item_id and
change_type.
Now, whenever you update a row in the items table, the trigger will run to add the
corresponding record to the item_changes table.
Fifth, update a row in the items table:
UPDATE items
SET price = 60.00
WHERE id = 1;
92. MySQL trigger example
DBMS – Unit-III PL/SQL Department of Information Technology
Finally, retrieve data from the item_changes table to see the logged changes:
SELECT * FROM item_changes;
Output:
+-----------+---------+-------------+---------------------+
| change_id | item_id | change_type | change_timestamp |
+-----------+---------+-------------+---------------------+
| 1 | 1 | UPDATE | 2023-12-27 18:21:43 |
+-----------+---------+-------------+---------------------+
1 row in set (0.01 sec)