SlideShare a Scribd company logo
1 of 12
Download to read offline
Cursors in MySQL
Tharindu Weerasinghe
www.tharinduweerasinghe.com
l
Cursors
A cursor is a structure that allows you to go over records
sequentially, and perform operations based on the results of
the cursor SELECT statement.
Cursors are created with a DECLARE CURSOR statement and
opened with an OPEN statement. Rows are read with a FETCH
statement before the cursor is finally closed with a CLOSE
statement.
A cursor should be created inside a Stored Programs.
l
Cursors
Cursors (Let's work out - Step1)
CREATE TABLE sampleTable
(sampleCol1 INT, sampleCol2 VARCHAR(10));
INSERT INTO sampleTable VALUES (1, "First");
INSERT INTO sampleTable VALUES (1, "Second");
Full .mysql script
is shown in the next slide
DROP TABLE IF EXISTS sampleTable;
CREATE TABLE sampleTable
(sampleCol1 INT, sampleCol2 VARCHAR(100));
INSERT INTO sampleTable VALUES (1, "First");
INSERT INTO sampleTable VALUES (2, "Second");
DROP PROCEDURE IF EXISTS sampleProc;
DELIMITER #
/*Create the Procedure */
CREATE PROCEDURE sampleProc()
BEGIN
  DECLARE x INT;
  /*Create the Cursor */
  DECLARE sampleCur CURSOR FOR SELECT sampleCol1 FROM sampleTable;
  /*Open the Cursor */
  OPEN sampleCur;
  /*Open the Loop to loop through the table according to the cursor SELECT */
  read_loop: LOOP
  /*FETCH the no.results to x*/
  FETCH sampleCur INTO x;
  IF (x > 0) THEN
     INSERT INTO sampleTable VALUES (1010, "InsideCur­Inside IF");  
  ELSE 
     INSERT INTO sampleTable VALUES (101010, "InsideCur­Outside IF");  
  END IF;
  LEAVE read_loop;
  END LOOP;
  CLOSE sampleCur;
END; 
#
A bit of a complex example
DROP TABLE IF EXISTS sampleTable1;
DROP TABLE IF EXISTS sampleTable2;
DROP TABLE IF EXISTS sampleTable3;
CREATE TABLE sampleTable1
(sampleCol1 INT, sampleCol2 VARCHAR(100));
CREATE TABLE sampleTable2
(sampleCol1 INT, sampleCol2 VARCHAR(100));
CREATE TABLE sampleTable3
(sampleCol1 INT, sampleCol2 VARCHAR(100));
INSERT INTO sampleTable1 VALUES (1, "First");
INSERT INTO sampleTable1 VALUES (2, "Second");
INSERT INTO sampleTable1 VALUES (3, "Third");
INSERT INTO sampleTable2 VALUES (10, "First");
INSERT INTO sampleTable2 VALUES (20, "Second");
INSERT INTO sampleTable2 VALUES (30, "Third");
DROP PROCEDURE IF EXISTS sampleProc;
DELIMITER #
/*Create the Procedure */
CREATE PROCEDURE sampleProc()
BEGIN
  DECLARE x,y INT;  
  DECLARE done INT DEFAULT FALSE;
  DECLARE sampleCur1 CURSOR FOR SELECT sampleCol1 FROM 
sampleTable1;
  DECLARE sampleCur2 CURSOR FOR SELECT sampleCol1 FROM 
sampleTable2;  
  
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
  OPEN sampleCur1;
  OPEN sampleCur2;  
  read_loop: LOOP  
  FETCH sampleCur1 INTO x;
  FETCH sampleCur2 INTO y;
  IF done THEN
      LEAVE read_loop;
    END IF;
  IF (x < y) THEN
     INSERT INTO sampleTable3 VALUES (1010, "InsideCur­Inside IF"); 
 
  ELSE 
     INSERT INTO sampleTable3 VALUES (101010, "InsideCur­Outside 
IF");  
  END IF;
  END LOOP;
  CLOSE sampleCur1;
  CLOSE sampleCur2;
END; 
#
Excercise:
1. Create three tables namely and have columns as follows:
1.1 Employee (EmpID, Name, Age)
1.2 Inventory (ItemID, ItemName, UsedEmpID)
1.3 EmpInvMatchTable (EmpID, ItemID)
2. Insert some relevant values to Employee and Inventory. Make sure there are values
in the Inventory table where it has some existing Employees using the items. And also
note that there are items which have no owner (means no EmplD)
3. Write a Procedure that has two cursors like in the sample, check the existing EmpIDs
in the Inventory table and if found then insert both the IDs (Emp and Item) to the third
table.
Note: You should execute the procedure and show me the results :)
Gratitude
References:
https://mariadb.com/kb/en/library/cursor-overview/
https://dev.mysql.com/doc/refman/8.0/en/cursors.html
http://www.mysqltutorial.org/mysql-cursor/

More Related Content

What's hot

Accelerating query processing with materialized views in Apache Hive
Accelerating query processing with materialized views in Apache HiveAccelerating query processing with materialized views in Apache Hive
Accelerating query processing with materialized views in Apache Hive
DataWorks Summit
 

What's hot (20)

PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slides
 
Oracle Database Performance Tuning Concept
Oracle Database Performance Tuning ConceptOracle Database Performance Tuning Concept
Oracle Database Performance Tuning Concept
 
SQLd360
SQLd360SQLd360
SQLd360
 
Introduction to Cassandra Architecture
Introduction to Cassandra ArchitectureIntroduction to Cassandra Architecture
Introduction to Cassandra Architecture
 
Oracle Performance Tuning Fundamentals
Oracle Performance Tuning FundamentalsOracle Performance Tuning Fundamentals
Oracle Performance Tuning Fundamentals
 
[Pgday.Seoul 2017] 6. GIN vs GiST 인덱스 이야기 - 박진우
[Pgday.Seoul 2017] 6. GIN vs GiST 인덱스 이야기 - 박진우[Pgday.Seoul 2017] 6. GIN vs GiST 인덱스 이야기 - 박진우
[Pgday.Seoul 2017] 6. GIN vs GiST 인덱스 이야기 - 박진우
 
Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)Presentation slides of Sequence Query Language (SQL)
Presentation slides of Sequence Query Language (SQL)
 
MySQL 8.0 EXPLAIN ANALYZE
MySQL 8.0 EXPLAIN ANALYZEMySQL 8.0 EXPLAIN ANALYZE
MySQL 8.0 EXPLAIN ANALYZE
 
All About JSON and ClickHouse - Tips, Tricks and New Features-2022-07-26-FINA...
All About JSON and ClickHouse - Tips, Tricks and New Features-2022-07-26-FINA...All About JSON and ClickHouse - Tips, Tricks and New Features-2022-07-26-FINA...
All About JSON and ClickHouse - Tips, Tricks and New Features-2022-07-26-FINA...
 
Best Practices to avoid ORA-01555
Best Practices to avoid ORA-01555Best Practices to avoid ORA-01555
Best Practices to avoid ORA-01555
 
Postgres Vision 2018: WAL: Everything You Want to Know
Postgres Vision 2018: WAL: Everything You Want to KnowPostgres Vision 2018: WAL: Everything You Want to Know
Postgres Vision 2018: WAL: Everything You Want to Know
 
Accelerating query processing with materialized views in Apache Hive
Accelerating query processing with materialized views in Apache HiveAccelerating query processing with materialized views in Apache Hive
Accelerating query processing with materialized views in Apache Hive
 
Pi Day 2022 - from IoT to MySQL HeatWave Database Service
Pi Day 2022 -  from IoT to MySQL HeatWave Database ServicePi Day 2022 -  from IoT to MySQL HeatWave Database Service
Pi Day 2022 - from IoT to MySQL HeatWave Database Service
 
ClickHouse Features for Advanced Users, by Aleksei Milovidov
ClickHouse Features for Advanced Users, by Aleksei MilovidovClickHouse Features for Advanced Users, by Aleksei Milovidov
ClickHouse Features for Advanced Users, by Aleksei Milovidov
 
Sql
SqlSql
Sql
 
My first 90 days with ClickHouse.pdf
My first 90 days with ClickHouse.pdfMy first 90 days with ClickHouse.pdf
My first 90 days with ClickHouse.pdf
 
Apache Flink Deep Dive
Apache Flink Deep DiveApache Flink Deep Dive
Apache Flink Deep Dive
 
Triggers en sql server 2019
Triggers en sql server 2019Triggers en sql server 2019
Triggers en sql server 2019
 
Procedures/functions of rdbms
Procedures/functions of rdbmsProcedures/functions of rdbms
Procedures/functions of rdbms
 
新機能によるデータベースシステムの改善ポイント
新機能によるデータベースシステムの改善ポイント新機能によるデータベースシステムの改善ポイント
新機能によるデータベースシステムの改善ポイント
 

Similar to Cursors in MySQL

Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standards
Alessandro Baratella
 

Similar to Cursors in MySQL (20)

sql.pptx
sql.pptxsql.pptx
sql.pptx
 
Sql lite android
Sql lite androidSql lite android
Sql lite android
 
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
 
SQL Injection: Amplifying Data Leakeage
SQL Injection: Amplifying Data LeakeageSQL Injection: Amplifying Data Leakeage
SQL Injection: Amplifying Data Leakeage
 
Sql12
Sql12Sql12
Sql12
 
Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standards
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako,
 
Validating The Existence of a Table Without Using DBA Metadata
Validating The Existence of a Table Without Using DBA MetadataValidating The Existence of a Table Without Using DBA Metadata
Validating The Existence of a Table Without Using DBA Metadata
 
Procedures andcursors
Procedures andcursorsProcedures andcursors
Procedures andcursors
 
PLSQL (1).ppt
PLSQL (1).pptPLSQL (1).ppt
PLSQL (1).ppt
 
从 Oracle 合并到 my sql npr 实例分析
从 Oracle 合并到 my sql   npr 实例分析从 Oracle 合并到 my sql   npr 实例分析
从 Oracle 合并到 my sql npr 实例分析
 
[Www.pkbulk.blogspot.com]dbms07
[Www.pkbulk.blogspot.com]dbms07[Www.pkbulk.blogspot.com]dbms07
[Www.pkbulk.blogspot.com]dbms07
 
Triggers n Cursors.ppt
Triggers n Cursors.pptTriggers n Cursors.ppt
Triggers n Cursors.ppt
 
Advanced sql injection 2
Advanced sql injection 2Advanced sql injection 2
Advanced sql injection 2
 
Slides11
Slides11Slides11
Slides11
 
JavaScript Looping Statements
JavaScript Looping StatementsJavaScript Looping Statements
JavaScript Looping Statements
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
My s qlbalidfnl
My s qlbalidfnlMy s qlbalidfnl
My s qlbalidfnl
 
PLSQL CURSOR
PLSQL CURSORPLSQL CURSOR
PLSQL CURSOR
 
sql.pdf
sql.pdfsql.pdf
sql.pdf
 

More from Tharindu Weerasinghe

More from Tharindu Weerasinghe (20)

C Propgramming.pdf
C Propgramming.pdfC Propgramming.pdf
C Propgramming.pdf
 
Basics of Computer Networks in Sinhala
Basics of Computer Networks in SinhalaBasics of Computer Networks in Sinhala
Basics of Computer Networks in Sinhala
 
Data Structures & Algorithms in Sinhala
Data Structures & Algorithms in SinhalaData Structures & Algorithms in Sinhala
Data Structures & Algorithms in Sinhala
 
Object Oriended Programming in Sinhala
Object Oriended Programming in Sinhala Object Oriended Programming in Sinhala
Object Oriended Programming in Sinhala
 
Tips For A Better Undergraduate Research
Tips For A Better Undergraduate ResearchTips For A Better Undergraduate Research
Tips For A Better Undergraduate Research
 
Basics of Block Chain
Basics of Block ChainBasics of Block Chain
Basics of Block Chain
 
Basics of IoT
Basics of IoTBasics of IoT
Basics of IoT
 
REST API Basics
REST API BasicsREST API Basics
REST API Basics
 
Cloud Conputing Basics and some Related Research Topics
Cloud Conputing Basics and some Related Research TopicsCloud Conputing Basics and some Related Research Topics
Cloud Conputing Basics and some Related Research Topics
 
Basic Concepts and Trends in Emerging Technologies
Basic Concepts and Trends in Emerging TechnologiesBasic Concepts and Trends in Emerging Technologies
Basic Concepts and Trends in Emerging Technologies
 
Introcution to EJB
Introcution to EJBIntrocution to EJB
Introcution to EJB
 
Introduction to Enterprise Applications and Tools
Introduction to Enterprise Applications and ToolsIntroduction to Enterprise Applications and Tools
Introduction to Enterprise Applications and Tools
 
Introduction to Agile Software Development & Python
Introduction to Agile Software Development & PythonIntroduction to Agile Software Development & Python
Introduction to Agile Software Development & Python
 
Agile Languages for Rapid Prototyping
Agile Languages for Rapid PrototypingAgile Languages for Rapid Prototyping
Agile Languages for Rapid Prototyping
 
Things to ponder before you start building [cooperate] software
Things to ponder before you start building [cooperate] softwareThings to ponder before you start building [cooperate] software
Things to ponder before you start building [cooperate] software
 
How to make screens and the internet safe for Children
How to make screens and the internet safe for Children How to make screens and the internet safe for Children
How to make screens and the internet safe for Children
 
Different Concepts on Databases
Different Concepts on DatabasesDifferent Concepts on Databases
Different Concepts on Databases
 
A Survey Study on Higher Education Trends among Sri Lankan IT Professionals
A Survey Study on Higher Education Trends among Sri Lankan IT ProfessionalsA Survey Study on Higher Education Trends among Sri Lankan IT Professionals
A Survey Study on Higher Education Trends among Sri Lankan IT Professionals
 
A Survey Study on Higher Education Trends among Information Technology Prof...
A Survey Study  on  Higher Education Trends among Information Technology Prof...A Survey Study  on  Higher Education Trends among Information Technology Prof...
A Survey Study on Higher Education Trends among Information Technology Prof...
 
Professionalism and Industry Expectations related to IT industry
Professionalism and Industry Expectations related to IT industry  Professionalism and Industry Expectations related to IT industry
Professionalism and Industry Expectations related to IT industry
 

Recently uploaded

The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 

Recently uploaded (20)

The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 

Cursors in MySQL