Skip to content
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
167 changes: 137 additions & 30 deletions content/sql/concepts/errors/errors.md
Original file line number Diff line number Diff line change
@@ -1,60 +1,167 @@
---
Title: 'Errors'
Description: 'An error refers to a problem that prevents the successful execution of a query or generates incorrect results.'
Title: 'SQL Errors'
Description: 'Returns diagnostic messages when issues occur during SQL query execution and database operations.'
Subjects:
- 'Computer Science'
- 'Data Science'
Tags:
- 'Aggregate Functions'
- 'Alias'
- 'Arithmetic'
- 'CRUD'
- 'Database'
- 'Debugging'
- 'Error Handling'
- 'Errors'
- 'SQL'
CatalogContent:
- 'learn-sql'
- 'paths/analyze-data-with-sql'
---

**Errors** in SQL occur when a query or operation fails to execute properly or generates incorrect results.
**SQL errors** are diagnostic messages returned by database management systems when issues occur during query execution or database operations. These errors provide information about what went wrong and help developers identify and resolve problems in their SQL statements or database configurations. SQL errors typically include an error code, a short description, and sometimes a detailed explanation.

There are mainly three types of SQL errors. Each of them are discussed below.
## Types of SQL errors

## Syntax Errors
SQL errors can be categorized into several main types based on their nature and when they occur during query processing:

A syntax error occurs when a SQL query does not follow the correct syntax or violate any linguistic rules, like the use of wrong keywords or wrong clauses.
- **Syntax errors** occur when SQL statements violate the rules of SQL grammar, including misspelled keywords, missing clauses, incorrect punctuation, or improper use of operators. These errors prevent the query from being parsed and executed by the database engine.

## Runtime Errors
- **Runtime errors** happen during query execution and are often caused by issues like data type mismatches, division by zero operations, or attempts to perform invalid operations on the data. These errors occur after the query has been successfully parsed but fail during the actual execution phase.

A runtime error occurs when the execution of a query takes place. This is why it is named as runtime error. These errors can occur due to performing inapplicable operations, like division by zero.
- **Logical errors** arise when queries execute without raising an error message but produce incorrect results due to flaws in the query logic itself. These errors are often the most challenging to identify because the database system doesn't flag them as problems.

## Logical Errors
- **Constraint violations** occur when database operations violate established database constraints, such as unique constraints, foreign key constraints, or check constraints. These errors help maintain data integrity by preventing invalid data modifications.

Logical errors arise when a query executes successfully, but produces an incorrect or unintended result due to the existence of logical flaws in it.
- **Data type mismatch errors** happen when attempting to insert, update, or compare incompatible data types. For example, trying to insert a text string into a numeric column or comparing a date with an integer value.

## Syntax
- **System errors** are related to the database system infrastructure and can range from connection issues and authentication failures to more severe problems like database corruption, insufficient memory, or network connectivity problems.

The below syntax demonstrates how a syntactical error occurs in SQL. Here the word `FORM` causes a syntactical error:
## SQL Error Codes

```pseudo
SELECT * FORM users;
SQL error codes are standardized numeric identifiers that specify the type of issue encountered during database operations. Different database systems use various error code ranges to categorize problems, from syntax errors to connection failures.

### Success and Warning Codes

| Error Code | Description |
| ---------- | ---------------------------------------------------------------------------------------- |
| 0 | Successful execution of the SQL statement. No errors occurred. |
| 100 | No data found; used by some SQL databases to indicate that a query has returned no rows. |

### General Error Codes (-1 to -99)

This range includes various general SQL issues such as **syntax errors**, **data type mismatches**, and permission problems.

| Error Code | Description |
| ---------- | ------------------------------------------------------------------------------------ |
| -1 | General SQL error; the specific issue is not defined. |
| -2 | Invalid SQL statement or syntax error in the SQL query. |
| -3 | Out of memory; the system could not allocate the required memory. |
| -4 | Database connection error; unable to establish or maintain a connection. |
| -5 | Data type mismatch; trying to insert or process incompatible data types. |
| -6 | Numeric overflow; value exceeds the storage capacity. |
| -8 | Constraint violation; such as a unique constraint or foreign key constraint failure. |
| -9 | Invalid operation; performing an operation that is not allowed. |
| -10 | Deadlock; two or more transactions are waiting for each other to release locks. |
| -11 | Timeout; the operation took longer than the permitted time limit. |
| -12 | Data integrity issue; corruption or mismatch in data. |
| -13 | Invalid index; referring to a non-existent or incorrect index. |
| -14 | Unspecified SQL error; general error with no specific cause. |
| -15 | Authentication error; issues with user credentials or login. |
| -16 | Database not found; the specified database does not exist. |
| -17 | Query execution error; issues encountered during SQL query execution. |

### Specific Feature Error Codes (-101 to -500)

This range includes more specific SQL error messages related to feature support, query execution, and data integrity.

| Error Code | Description |
| ---------- | ------------------------------------------------------------------------------------- |
| -101 | Syntax error; the SQL statement contains incorrect syntax. |
| -102 | Incorrect or missing keyword in the SQL statement. |
| -103 | Unexpected token; encountered an unrecognized or invalid character. |
| -104 | Column not found; attempting to access a non-existent column. |
| -105 | Table not found; specified table does not exist. |
| -106 | Function or stored procedure not found; non-existent function or procedure. |
| -107 | Invalid operation on an open cursor; operation not permitted. |
| -108 | Incorrect data length; data does not fit in the specified length. |
| -109 | Invalid constraint definition; issues with constraints in the database schema. |
| -110 | Unsupported SQL feature; the SQL feature is not available in the current environment. |

## Example 1: Basic Syntax SQL Error Example

This example demonstrates a common syntax error that occurs when SQL keywords are misspelled or used incorrectly.

```sql
-- Incorrect syntax with misspelled SELECT keyword
SELCT name, age FROM users WHERE age > 25;
```

The output of this code will be:

```shell
ERROR: syntax error at or near "SELCT"
LINE 1: SELCT name, age FROM users WHERE age > 25;
^
```

The error occurs because `SELCT` is not a valid SQL keyword. The correct statement should use `SELECT` instead. This type of **syntax error** is one of the most common SQL errors encountered by developers.

## Example 2: Table Not Found Error in SQL

This example shows what happens when referencing a table that doesn't exist in the database:

```sql
-- Attempting to query a non-existent table
SELECT product_name, price
FROM inventory
WHERE category = 'electronics';
```

## Example
The output of this code will be:

The following example shows how different errors arise in SQL:
```shell
ERROR: relation "inventory" does not exist
LINE 2: FROM inventory
^
```

This **table not found error** occurs when the specified table name doesn't exist in the current database schema. Common causes include misspelled table names, incorrect database context, or attempting to access tables that haven't been created yet.

## Example 3: Data Type Mismatch Error in SQL

This example demonstrates an error that occurs when trying to insert incompatible data types into a column.

```sql
-- Create a table with a UNIQUE constraint
CREATE TABLE users (
id INT PRIMARY KEY,
email VARCHAR(100) UNIQUE
-- Creating a table with specific data types
CREATE TABLE employees (
id INTEGER,
name VARCHAR(50),
hire_date DATE,
salary DECIMAL(10,2)
);

-- Insert data with syntax error
INSERT INTO users (id, email VALUES (1, '[email protected]'); -- Error: Missing closing parenthesis
-- Attempting to insert incorrect data types
INSERT INTO employees (id, name, hire_date, salary)
VALUES ('invalid_id', 'John Doe', '2024-13-45', 'high_salary');
```

-- Insert data with unique constraint violation
INSERT INTO users (id, email) VALUES (2, '[email protected]'); -- Error: Duplicate email
The output of this code will be:

-- Data type mismatch
INSERT INTO users (id, email) VALUES ('three', '[email protected]'); -- Error: 'id' should be an integer
```shell
ERROR: invalid input syntax for type integer: "invalid_id"
ERROR: date/time field value out of range: "2024-13-45"
ERROR: invalid input syntax for type numeric: "high_salary"
```

This **data type mismatch error** occurs when the values being inserted don't match the expected data types for the columns. The `id` column expects an integer, `hire_date` expects a valid date format, and `salary` expects a numeric value.

## Frequently Asked Questions
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add FAQs that are relevant to PAA questions.


### 1. What are the most common SQL error types?

The most common SQL errors include syntax errors, table or column not found errors, data type mismatches, constraint violations, and connection timeouts. Syntax errors typically occur due to misspelled keywords or incorrect query structure.

### 2. What's the difference between SQL error codes and SQLSTATE codes?

SQL error codes are database-specific numeric identifiers, while SQLSTATE codes are standardized five-character codes defined by the SQL standard. SQLSTATE codes provide consistent error identification across different database systems.

### 3. Why do I get connection errors when running SQL queries?

Connection errors can occur due to network issues, incorrect connection parameters, authentication failures, database server downtime, or exceeding connection limits. Verify your connection string, credentials, and network connectivity to resolve these issues.