Table of Contents
- Introduction
- Why Error Handling Matters in SQL
- Types of Errors in SQL
- Syntax Errors vs Runtime Errors
- Understanding Transaction Errors
- Rollbacks for Safe Error Recovery
- Error Handling in SQL Scripts
- Handling Errors in Stored Procedures
- Using
DECLARE HANDLER
in MySQL - Handling Errors in PostgreSQL (
EXCEPTION
) - SQL Server’s
TRY...CATCH
Syntax - Identifying Errors with
SQLSTATE
and Error Codes - Logging Errors for Auditing and Debugging
- Real-World Use Case: Bank Transfer with Error Handling
- Preventing Errors Through Constraints
- Retrying, Skipping, or Continuing After Errors
- Common Error Patterns and Troubleshooting
- Best Practices for Error Handling
- Database-Specific Features for Error Management
- Summary and What’s Next
1. Introduction
Error handling is a critical aspect of SQL programming. Whether you’re writing a script, stored procedure, or a high-throughput application backend, managing exceptions and transaction failures properly can protect your data and improve system reliability.
2. Why Error Handling Matters in SQL
- Maintains data consistency and integrity
- Prevents partial updates or corrupt states
- Helps diagnose and log application-level issues
- Enables clean recovery or user-friendly messages
- Supports robust and maintainable code
3. Types of Errors in SQL
Error Type | Examples |
---|---|
Syntax errors | Misspelled SQL keywords, missing commas |
Constraint errors | Violations of NOT NULL , UNIQUE , or FK |
Runtime errors | Division by zero, invalid data type operations |
Deadlocks | Competing transactions causing locks |
Connection errors | Timeouts, disconnections, missing privileges |
4. Syntax Errors vs Runtime Errors
- Syntax errors are caught during query parsing.
- Runtime errors occur during execution and can be caught or handled in stored routines.
Example:
sqlCopyEditSELECT 1 / 0; -- Runtime error: division by zero
5. Understanding Transaction Errors
Many SQL statements are executed inside transactions. If one fails, the entire transaction must be rolled back to maintain data integrity.
6. Rollbacks for Safe Error Recovery
sqlCopyEditSTART TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
-- Error occurs here
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
ROLLBACK; -- Ensures nothing is committed
7. Error Handling in SQL Scripts
Basic SQL scripts usually stop execution when an error is encountered. To control this, use database-specific constructs like:
DECLARE HANDLER
in MySQLBEGIN ... EXCEPTION
in PostgreSQLTRY...CATCH
in SQL Server
8. Handling Errors in Stored Procedures
MySQL:
sqlCopyEditDECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
INSERT INTO error_log (message) VALUES ('Something failed');
END;
PostgreSQL:
sqlCopyEditBEGIN
-- statements
EXCEPTION
WHEN OTHERS THEN
RAISE WARNING 'Error: %', SQLERRM;
END;
9. Using DECLARE HANDLER
in MySQL
sqlCopyEditDECLARE CONTINUE HANDLER FOR SQLEXCEPTION
BEGIN
SET @has_error = TRUE;
END;
Handler types:
CONTINUE
: continue execution after errorEXIT
: exit the blockUNDO
: rarely supported
10. Handling Errors in PostgreSQL (EXCEPTION
)
sqlCopyEditDO $$
BEGIN
-- Attempt risky logic
EXCEPTION
WHEN division_by_zero THEN
RAISE NOTICE 'Divide by zero error';
WHEN OTHERS THEN
RAISE WARNING 'Unhandled error: %', SQLERRM;
END $$;
PostgreSQL provides GET STACKED DIAGNOSTICS
for deeper debugging.
11. SQL Server’s TRY...CATCH
Syntax
sqlCopyEditBEGIN TRY
-- risky SQL
END TRY
BEGIN CATCH
PRINT ERROR_MESSAGE();
ROLLBACK TRANSACTION;
END CATCH;
Also access: ERROR_NUMBER()
, ERROR_LINE()
, ERROR_SEVERITY()
12. Identifying Errors with SQLSTATE
and Error Codes
Code | Meaning |
---|---|
22012 | Division by zero |
23000 | Constraint violation |
40001 | Serialization failure (deadlock) |
42000 | Syntax error or access violation |
Useful for creating custom error logic based on type.
13. Logging Errors for Auditing and Debugging
sqlCopyEditCREATE TABLE error_log (
id INT AUTO_INCREMENT PRIMARY KEY,
error_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
message TEXT
);
-- Log error
INSERT INTO error_log (message) VALUES ('Update failed at step 3');
14. Real-World Use Case: Bank Transfer with Error Handling
sqlCopyEditBEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
INSERT INTO error_log (message) VALUES ('Transfer failed');
END;
START TRANSACTION;
UPDATE accounts SET balance = balance - 1000 WHERE id = 101;
UPDATE accounts SET balance = balance + 1000 WHERE id = 202;
COMMIT;
END;
15. Preventing Errors Through Constraints
Define constraints in schema:
CHECK (quantity >= 0)
NOT NULL
to enforce required fieldsUNIQUE
to prevent duplicatesFOREIGN KEY
to enforce relational integrity
16. Retrying, Skipping, or Continuing After Errors
Use CONTINUE HANDLER
or write loop logic to skip faulty records during ETL.
sqlCopyEditDECLARE CONTINUE HANDLER FOR SQLEXCEPTION
SET @skipped_rows = @skipped_rows + 1;
17. Common Error Patterns and Troubleshooting
Issue | Solution |
---|---|
Uncaught exceptions | Use TRY...CATCH or HANDLER |
Silent failures | Always log or raise feedback |
Rollback missed | Always rollback in failure handlers |
Ambiguous error cause | Use SQLSTATE , ERROR_MESSAGE() etc. |
18. Best Practices for Error Handling
- Always wrap complex DML in transactions
- Log meaningful context with every failure
- Use specific error handling when possible
- Test edge cases (nulls, duplicates, failures)
- Avoid silent failure paths unless explicitly desired
19. Database-Specific Features for Error Management
DBMS | Mechanism |
---|---|
MySQL | DECLARE HANDLER , error codes |
PostgreSQL | EXCEPTION , SQLERRM , diagnostics |
SQL Server | TRY...CATCH , XACT_ABORT , severity levels |
Oracle | EXCEPTION WHEN , SQLCODE , SQLERRM |
20. Summary and What’s Next
Error handling in SQL empowers you to build robust, resilient, and fault-tolerant systems. Whether using handlers, exception blocks, or structured logs, it’s essential for modern database operations.