Database Research & Development

  • Home
  • NoSQL
    • NoSQL
    • Cassandra
  • Databases
    • Database Theory
    • Database Designing
    • SQL Server Coding Standards
    • SQL Server
    • PostgreSQL
    • MySQL
    • Greenplum
    • Linux
  • Interviews
    • SQL Server Interviews
    • MySQL Interviews
    • SQL Puzzles
  • DBA Scripts
    • SQL Server DBA Scripts
    • PostgreSQL DBA Scripts
    • MySQL DBA Scripts
    • Greenplum DBA Scripts
  • Home
  • Blog Archives !
  • (: Laugh@dbrnd :)
  • Contact Me !
sqlserverinterviews
Home 2015 May MySQL Error Handling

MySQL Error Handling

This article is half-done without your Comment! *** Please share your thoughts via Comment ***

In this post, I am sharing the full demonstration on how to manage error/exception handling in the Stored Procedure of MySQL.

Whenever an exception is occurring in a stored procedure, it is very important to handle it by showing proper error messages.

If you do not handle the exception, there would be a chance to fail application with the certain exception in a stored procedure.

If you get an error in stored procedure, instead of an exit, you should continue without any error message. That means you can show any default or custom error code or message to the application/user.

MySQL provides Handler to handle the exception in the stored procedure.

Below is a full demonstration of a handler with examples:

1
2
3
4
5
6
7
8
9
10
/*Create Employee database for demo */
CREATE DATABASE Employee;
/*Create sample EmployeeDetails table.*/
CREATE TABLE Employee.tbl_EmployeeDetails
(
EmpID INTEGER
,EmpName VARCHAR(50)
,EmailAddress VARCHAR(50)
,CONSTRAINT pk_tbl_EmployeeDetails_EmpID PRIMARY KEY (EmpID)
)ENGINE = InnoDB;

How to declare handler in store procedure:

Syntax of Handler:

1
DECLARE handler_action HANDLER FOR condition_value ... statement

Three type of Handler_Action:

  • CONTINUE
  • EXIT
  • UNDO

Type of Condition Value:

  • mysql_error_code
  • sqlstate_value
  • SQLWarning
  • SQLException
  • NotFound

How to write handler in stored procedure?

E.g.

1
2
3
4
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SELECT 'Error occured';
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET IsError=1;
DECLARE EXIT HANDLER FOR SQLEXCEPTION SET IsError=1;
DECLARE EXIT HANDLER FOR SQLSTATE '23000' SET IsError = 1;

The Above are four different handler examples. Now, I am going to insert a duplicate value into EmpID column.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
DELIMITER //
CREATE PROCEDURE Employee.usp_InsertEmployeeDetails
(
InputEmpID INTEGER
,InputEmpName VARCHAR(50)
,InputEmailAddress VARCHAR(50)
)
/****************************************************************
Authors Name : Anvesh Patel
Created Date : 2015-05-20
Description : This is demo stored procedure to
insert record into table with proper
error handling.Basically for www.dbrnd.com readers.
*****************************************************************/
BEGIN
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SELECT 'Error occured';
INSERT INTO Employee.tbl_EmployeeDetails
(
EmpID
,EmpName
,EmailAddress
)
VALUES
(
InputEmpID
,InputEmpName
,InputEmailAddress
);
SELECT *FROM Employee.tbl_EmployeeDetails;
END
// DELIMITER ;

In the above SP, I defined a CONTINUE handler with my custom exception message.

Now, call the above SP two times with same EmpID.

The first time, it will execute successfully, but the second time it will throw a custom error message.

As we defined CONTINUE handler, so it will just show an error message and CONTINUE to next part of the SELECT statement.

Let’s See,

1
2
CALL Employee.usp_InsertEmployeeDetails (1,'Anvesh','anvesh@gmail.com');
CALL Employee.usp_InsertEmployeeDetails (1,'Roy','Roy@gmail.com');

Above are the two different calls with same EmpID value. The first call executes without any error message and the second call execute with an error message.

The resule of Second Call:

Continue1

Continue2

As we defined CONTINUE, so you can find two results in above image. One is our custom error message and second is the result of the defined SELECT statement.
The execution didn’t stop by error, and it continued for another part.

Now, check the EXIT handler:

Please modify your handler and replace CONTINUE by EXIT:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
DELIMITER //
CREATE PROCEDURE Employee.usp_InsertEmployeeDetails
(
InputEmpID INTEGER
,InputEmpName VARCHAR(50)
,InputEmailAddress VARCHAR(50)
)
/*****************************************************************
Authors Name : Anvesh Patel
Created Date : 2015-05-20
Description : This is demo stored procedure to
insert record into table with proper
error handling.Basically for www.dbrnd.com readers.
******************************************************************/
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'Error occured';
INSERT INTO Employee.tbl_EmployeeDetails
(
EmpID
,EmpName
,EmailAddress
)
VALUES
(
InputEmpID
,InputEmpName
,InputEmailAddress
);
SELECT *FROM Employee.tbl_EmployeeDetails;
END
// DELIMITER ;

Call with the same parameter:

1
CALL Employee.usp_InsertEmployeeDetails (1,'Roy','Roy@gmail.com');

The Result is an only error message, and you cannot find two results as we defined EXIT to exit the code when an error occurred.

Exit1

The best practice is to create a output parameter and store 1 if any error occurred.

Application code has to check this output parameter is NULL or 1.

1 = Error.

NULL = No Error.

Below is a stored procedure for this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
DELIMITER //
CREATE PROCEDURE Employee.usp_InsertEmployeeDetails
 
(
InputEmpID INTEGER
,InputEmpName VARCHAR(50)
,InputEmailAddress VARCHAR(50)
,out IsError INTEGER
)
/***********************************************************
Authors Name : Anvesh Patel
Created Date : 2015-05-20
Description : This is demo stored procedure to insert
record into table with proper error handling.
Basically for www.dbrnd.com readers.
************************************************************/
BEGIN
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET IsError=1;
 
INSERT INTO Employee.tbl_EmployeeDetails
(
EmpID
,EmpName
,EmailAddress
)
VALUES
(
InputEmpID
,InputEmpName
,InputEmailAddress
);
SELECT *FROM Employee.tbl_EmployeeDetails;
END
// DELIMITER ;

Now call the above SP and select output parameter:

1
2
CALL Employee.usp_InsertEmployeeDetails (1,'Roy','Roy@gmail.com',@IsError);
SELECT @IsError;

Now Results are:

IsError1

IsError2

Above is a simple demonstration of Error Handling in MySQL. You can also use SQLSTATE which shows default error messages of MySQL.

May 21, 2015Anvesh Patel
How to create job in PostgreSQLPostgreSQL XML Type
Comments: 20
  1. Sunil
    January 4, 2017 at 9:29 am

    hi Avnesh i am struggling with DEFINER in stored procedure can you suggest some better idea
    like DEFINER is =root@% then i am unable to execute this stored procedure from my local mysql db.

    , advance thanks!

    • Anvesh Patel
      Anvesh Patel
      January 4, 2017 at 7:16 pm

      Remove it. Its default added in your stored procedure.

  2. Shubhada Mulay
    January 30, 2017 at 10:43 am

    Hi Anvesh,
    I am beginner to MYSQL. Could you please throw more light in details on this exception Handling Part? If you have any detailed version of this Please reply with the URL of that article as well.
    Many Thanks in Advance.
    Regards
    Shubhada

    • Anvesh Patel
      Anvesh Patel
      January 30, 2017 at 6:10 pm

      Sure, I will update this article and will share few other links.

  3. Victor R Udeshi
    July 14, 2017 at 7:03 pm

    HI Anvesh,

    I am using error handling in my stored proc and it works fine. the results show me only 1 field, the error.

    What i am trying to do is call the proc into a reporting software (pentaho). when i call the proc in pentaho it only shows me the error field.

    is there i way i can have all the fields i want show up blank and the error message if there is an error?

    • Anvesh Patel
      Anvesh Patel
      July 17, 2017 at 8:14 pm

      You can replace that 1 by NULL.

  4. Ravi Kumar Chandran
    September 25, 2017 at 11:16 pm

    Anvesh,

    It is a well written article and you have managed to explain a fairly complex feature in simple terms! thanks. it was useful to me.

    • Anvesh Patel
      Anvesh Patel
      September 26, 2017 at 5:02 pm

      Thank you, Ravi…

  5. kaliyappan
    November 9, 2017 at 5:53 am

    HI, Below query shows me “No data: 1329 No data – zero rows fetched, selected, or processed”. Cant fix it can u help me.
    BEGIN
    DECLARE from_date DATETIME;
    DECLARE to_date DATETIME;
    DECLARE hostname VARCHAR(50);
    DECLARE servicename VARCHAR(50);
    DECLARE running_no INT;
    DECLARE loop_no INT;
    DECLARE value1 FLOAT;
    DECLARE value2 FLOAT;
    DECLARE value3 FLOAT;
    DECLARE state INT;
    DECLARE logdate DATETIME;
    DECLARE prev_status INT;
    DECLARE c1len INT;
    DECLARE c2len INT;
    DECLARE c2flag INT;
    DECLARE IsError INT;
    DECLARE c1 CURSOR FOR SELECT host_name as host,service_name as service FROM cmp_warehouse.tbl_health_events_csv GROUP BY host_name,service_name ORDER BY host_name, service_name;

    SET running_no = 1;
    OPEN c1;
    set c1len = (SELECT FOUND_ROWS());
    l_c1:LOOP

    FETCH c1 INTO hostname,servicename;

    INSERT INTO cmp_warehouse.temp_event_data_4 (host, service,conelen) VALUES (hostname, servicename,c1len);
    SET loop_no=1;

    BLOCK2: BEGIN
    DECLARE c2 CURSOR FOR SELECT val1,val2,val3,status_check as status, event_time as logtime FROM cmp_warehouse.tbl_health_events_csv WHERE host_name = hostname AND service_name = servicename ORDER BY event_time ASC;
    OPEN c2;
    set c2len = (SELECT FOUND_ROWS());
    SET c2flag = 1;
    l_c2:LOOP
    FETCH c2 INTO value1,value2,value3,state,logdate;
    INSERT INTO cmp_warehouse.temp_event_data_3 (val1, val2, val3, status, logtime,prev_sta,ctwolen,c2flg) VALUES (value1,value2,value3,state,logdate,prev_status,c2len,c2flag);
    IF loop_no=1 THEN
    INSERT INTO cmp_warehouse.temp_event_data_2 (row_no, host, service, val1, val2, val3, status, start_time, end_time,createdon) VALUES (running_no, hostname, servicename, value1, value2, value3, state, logdate, NULL,NOW());
    SET loop_no = loop_no +1;
    SET prev_status = state;
    END IF;
    IF state prev_status THEN
    UPDATE cmp_warehouse.temp_event_data_2 SET end_time = logdate WHERE row_no = running_no;
    SET running_no = running_no +1;
    INSERT INTO cmp_warehouse.temp_event_data_2 (row_no, host, service, val1, val2, val3, status, start_time, end_time,createdon) VALUES (running_no, hostname, servicename, value1, value2, value3, state, logdate, NULL,NOW());
    END IF;
    SET prev_status = state;
    IF c2len = c2flag THEN
    UPDATE temp_event_data_2 SET end_time = logdate WHERE row_no = running_no;
    SET running_no = running_no + 1;
    LEAVE l_c2;
    END IF;
    SET c2flag = c2flag + 1;
    END LOOP l_c2;
    CLOSE c2;
    END BLOCK2;
    END LOOP l_c1;
    CLOSE c1;
    END

    • Anvesh Patel
      Anvesh Patel
      November 9, 2017 at 9:57 am

      I think this is your logic and not related to this post, if you need any other help, contact me from via CONTACT ME page. I will try to help you.

  6. Sanket Kale
    January 2, 2018 at 7:46 am

    How to know the run time errors in a mysql store procedure?
    Is there a way where I can print the errors that occurred while executing the SP?
    Kindly explain with a example.

    Thanks in advance.

    • Anvesh Patel
      Anvesh Patel
      January 4, 2018 at 9:20 am

      Ok i will send

      • rajesh
        June 12, 2018 at 12:25 pm

        Hi Anvesh,

        this is rajesh, please clarify my doubt. i have no idea about Oracle and Mysql. so my i join Mysql directly.

  7. Arti
    July 28, 2018 at 10:38 am

    shared great example for mysql error handling.

  8. Ben Oakes
    August 16, 2018 at 7:01 am

    When it comes to handling SQL querying problems, these are often easier to fix than pure PHP problems because you can narrow down the position of the error 0xc0000185.

  9. Himanshu
    August 17, 2018 at 6:40 am

    Hi Avinash,

    could you please let me know, how we can print the Run time exception.

  10. shivani survase
    November 22, 2018 at 10:23 am

    while call above SP with empID i’m gettting an error. Saying,

    Error 4052 (42S22): Unknown column ‘InputEmpID’ in ‘field list’

  11. Edward_abino
    December 13, 2018 at 8:41 am

    MySQL provides an easy way to define handlers that handle from general conditions such as warnings or exceptions to specific conditions e.g., specific error codes.

  12. Puneet Papneja
    June 15, 2019 at 8:00 am

    Is there any way to use error handling inside transaction but not use store procedure?

  13. Labonya Das
    November 26, 2019 at 4:22 am

    I want to capture the actual DB error not a user defined error messages as it is written here. In the manner we have in Oracle and SQL server the exact DB error is captured when an exception occurs. Any idea on this please share and thank you for your suggestion in advance.

Anvesh Patel
Anvesh Patel

Database Engineer

May 21, 2015 MySQLAnvesh Patel, continue, database, database research and development, error handling, exception stored procedure, exit, handler, MySQL, MySQL Command, MySQL Database Programming, MySQL Query, sqlstate
About Me!

I'm Anvesh Patel, a Database Engineer certified by Oracle and IBM. I'm working as a Database Architect, Database Optimizer, Database Administrator, Database Developer. Providing the best articles and solutions for different problems in the best manner through my blogs is my passion. I have more than six years of experience with various RDBMS products like MSSQL Server, PostgreSQL, MySQL, Greenplum and currently learning and doing research on BIGData and NoSQL technology. -- Hyderabad, India.

About DBRND !

dbrnd

This is a personal blog (www.dbrnd.com).

Any views or opinions represented in this blog are personal and belong solely to the blog owner and do not represent those of people, institutions or organizations that the owner may or may not be associated with in professional or personal capacity, unless explicitly stated.

Feel free to challenge me, disagree with me, or tell me I’m completely nuts in the comments section of each blog entry, but I reserve the right to delete any comment for any reason whatsoever (abusive, profane, rude, or anonymous comments) - so keep it polite.

The content of this website is protected by copyright. No portion of this website may be copied or replicated in any form without the written consent of the website owner.

Recent Comments !
  • Anvesh Patel { Sure will do... } – May 27, 12:43 PM
  • Anvesh Patel { Great... } – May 27, 12:41 PM
  • Anvesh Patel { Great... } – May 27, 12:39 PM
  • Anvesh Patel { Great... } – May 27, 12:36 PM
  • Anvesh Patel { Great... } – May 27, 12:28 PM
  • Anvesh Patel { Great... } – May 27, 12:27 PM
  • Anvesh Patel { Great... } – May 27, 12:16 PM
  • Older »
Follow Me !
  • facebook
  • linkedin
  • twitter
  • youtube
  • google
  • flickr
© 2015 – 2019 All rights reserved. Database Research & Development (dbrnd.com)
Posting....