1 Introduction to SQL Errors
TopErrors in SQL happen when a statement can't be executed — a constraint is violated, a table doesn't exist, a data type is wrong, or a deadlock occurs. Without proper error handling, your stored procedures will crash silently, leaving data in an inconsistent state.
Common Error Categories
| Category | Example | Error Code (MySQL) |
|---|---|---|
| Syntax errors | SELCT * FROM users (typo) | 1064 |
| Constraint violations | Duplicate primary key, NOT NULL violation | 1062, 1048 |
| Missing objects | Table or column doesn't exist | 1146, 1054 |
| Data type mismatch | Inserting 'abc' into an INT column | 1366 |
| Division by zero | SELECT 100 / 0 | 1365 |
| Deadlocks | Two transactions waiting for each other | 1213 |
| Permission denied | User lacks INSERT privilege | 1142 |
What Happens Without Error Handling
-- This procedure has NO error handling
DELIMITER //
CREATE PROCEDURE transfer_money(
IN from_id INT, IN to_id INT, IN amount DECIMAL(10,2)
)
BEGIN
UPDATE accounts SET balance = balance - amount WHERE id = from_id;
-- If this fails, the money is already deducted! 💥
UPDATE accounts SET balance = balance + amount WHERE id = to_id;
END //
DELIMITER ;If the second UPDATE fails (wrong to_id, constraint violation, etc.), the money is subtracted from the sender but never added to the receiver. This is why you need error handling combined with transactions.
Key Takeaways
- SQL errors stop statement execution — they don't fix themselves
- Without error handling, failures can leave data in an inconsistent state
- Common errors: constraint violations, missing objects, type mismatches, deadlocks
- Always combine error handling with transactions for critical operations