⬅ Previous Topic
SQL CursorsNext Topic ⮕
Dynamic SQL⬅ Previous Topic
SQL CursorsNext Topic ⮕
Dynamic SQLDatabases are like schools — full of rules. And when rules are broken, something must respond. In SQL, errors happen when data is missing, wrong, or violates constraints. To gracefully handle these issues without crashing your entire system, SQL offers structured error handling mechanisms.
Error handling allows you to catch and manage exceptions inside stored procedures or triggers using constructs like DECLARE HANDLER
, SIGNAL
, and RESIGNAL
. These tools help you respond smartly instead of failing silently or abruptly.
DECLARE CONTINUE HANDLER
– catches errors and continuesDECLARE EXIT HANDLER
– catches errors and exits the blockSIGNAL SQLSTATE
– manually raise a custom errorCREATE TABLE students (
roll_no INT PRIMARY KEY,
name VARCHAR(50),
marks INT
);
INSERT INTO students VALUES
(1, 'Aarav Sharma', 85),
(2, 'Diya Iyer', 92);
DELIMITER $$
CREATE PROCEDURE insert_student (
IN p_roll INT,
IN p_name VARCHAR(50),
IN p_marks INT
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
SELECT 'Error: Roll number already exists or invalid data.' AS message;
END;
INSERT INTO students VALUES (p_roll, p_name, p_marks);
END$$
DELIMITER ;
CALL insert_student(1, 'Sneha Patil', 88);
message
---------------------------------------
Error: Roll number already exists or invalid data.
DELIMITER $$
CREATE PROCEDURE insert_and_continue ()
BEGIN
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION
BEGIN
SELECT 'Attempted insert failed, moving on...' AS status;
END;
INSERT INTO students VALUES (1, 'Mehul', 75); -- Will fail
SELECT * FROM students;
END$$
DELIMITER ;
CALL insert_and_continue();
status
-------------------------------
Attempted insert failed, moving on...
roll_no | name | marks
--------+----------------+-------
1 | Aarav Sharma | 85
2 | Diya Iyer | 92
DELIMITER $$
CREATE PROCEDURE validate_marks (
IN p_marks INT
)
BEGIN
IF p_marks > 100 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Marks cannot exceed 100';
END IF;
SELECT CONCAT('Accepted: ', p_marks) AS status;
END$$
DELIMITER ;
CALL validate_marks(105);
ERROR 1644 (45000): Marks cannot exceed 100
Error handling ensures your SQL programs are not just powerful — but also resilient. Whether you’re inserting students, validating marks, or handling duplicates, proper use of HANDLER
and SIGNAL
helps your database respond thoughtfully, just like a good teacher correcting a mistake.
Next up: SQL Optimization Techniques — learn how to write faster, leaner, and smarter queries that scale.
⬅ Previous Topic
SQL CursorsNext Topic ⮕
Dynamic SQLYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.