Fact-checked by Grok 2 weeks ago

SQLSTATE

SQLSTATE is a standardized five-character alphanumeric used in the Structured Query Language (SQL) to indicate the outcome of SQL statement execution, encompassing successful completion, warnings, no data conditions, and error states. It forms part of the international SQL standard defined by ISO/IEC 9075, enabling portable error handling across compliant database management systems by replacing vendor-specific codes with a uniform reporting mechanism. The structure of an SQLSTATE code divides into a two-character class code, which categorizes the general type of condition (e.g., success or exception), and a three-character subclass code, which offers more detailed information about the specific issue. Each of the five characters must be a digit from 0 to 9 or an uppercase letter from A to Z, ensuring consistent encoding. Class codes follow predefined categories in the standard, with '00' denoting successful completion, '01' for warnings (such as data truncation), '02' for no data returned, and exception classes like '08' for connection issues, '22' for data exceptions (e.g., invalid data types), '23' for integrity constraint violations, '42' for syntax errors, and '38' for external routine exceptions. Subclasses within these classes provide granularity, such as '22003' for numeric value out of range under the data exception class. Introduced in the revision of the standard (ISO/IEC 9075:1992 and ANSI X3.135-1992), SQLSTATE enhanced SQL's diagnostic features by establishing a diagnostics area and supporting statements like GET DIAGNOSTICS for retrieving detailed error information, moving beyond earlier vendor-dependent error reporting. Subsequent SQL standards, including SQL:1999, SQL:2003, and up to SQL:2023, have expanded the defined SQLSTATE values while maintaining , with classes beginning with 0, 1, 2, 3, 4, or A through G reserved for standard-defined conditions and others available for implementation-specific use. In practice, SQLSTATE is integral to programs, stored procedures, and database APIs in systems like , , , , and , where it facilitates robust and cross-platform application development.

Introduction

Definition

SQLSTATE is a standardized five-character alphanumeric code used to report the outcome of SQL statement execution in management systems (RDBMS). It is defined in the SQL standards ISO/IEC 9075 and ANSI X3.135, where it serves as a status parameter indicating success, warnings, no data found, or exceptions. The code comprises a two-character class (the first two positions) that categorizes the condition broadly and a three-character subclass (the remaining positions) that specifies details, with each character limited to digits (0-9) or uppercase Latin letters (A-Z). In contrast to vendor-specific codes like SQLCODE, which are implementation-dependent and vary across DBMS, SQLSTATE promotes portability by adhering to a uniform scheme that works consistently in any standards-compliant RDBMS. SQLCODE, while included in early SQL standards, was deprecated in ISO/IEC 9075:1992 (SQL-92) and fully removed in later editions, making SQLSTATE the recommended approach for cross-platform compatibility. SQLSTATE facilitates , diagnostics, and signaling in SQL by populating the diagnostics area after execution, enabling applications to retrieve and act on status information. Through constructs like the GET DIAGNOSTICS , it provides access to details for analysis, while the SIGNAL allows explicit raising of conditions using SQLSTATE values. This mechanism supports robust application development by standardizing how SQL engines communicate execution results.

Purpose and Benefits

SQLSTATE serves as a standardized five-character code that indicates the outcome of an SQL statement's execution, signaling conditions such as success, warnings, no data found, or exceptions. This mechanism enables portable error handling by providing a consistent format across different database management systems (DBMS), allowing applications to detect and respond to specific error classes or subclasses without relying on vendor-specific codes. For instance, the class "00" denotes successful execution, while "01" indicates warnings, facilitating uniform diagnostics in diverse SQL environments. The primary benefits of SQLSTATE lie in its promotion of and reduced for developers. By adhering to ISO/IEC standards, it ensures that error conditions are reported in a predictable manner, enabling SQL code to be more easily ported between compliant DBMS implementations without extensive modifications. This standardization simplifies application-level diagnostics, as programmers can test for broad error categories (e.g., data exceptions under class "22") or precise subclasses, enhancing reliability and maintainability in multi-vendor setups. Additionally, it supports structured in and APIs, where applications can programmatically inspect and handle conditions, thereby improving overall system robustness. In SQL's exception model, SQLSTATE integrates seamlessly with the GET DIAGNOSTICS statement to retrieve detailed information about execution outcomes. This statement populates host variables with the SQLSTATE value alongside other diagnostics, such as message text or names, allowing for granular error analysis within handlers or procedures. For example, after an unsuccessful operation, an application can use GET DIAGNOSTICS to fetch the RETURNED_SQLSTATE, enabling targeted recovery actions based on the standardized code. This integration fosters efficient, standards-compliant exception management, minimizing downtime and supporting complex across SQL-compliant systems.

History and Development

Origins in SQL Standards

The SQLSTATE mechanism was formally introduced in the standard, published as ANSI X3.135-1992 by the and as ISO/IEC 9075:1992 by the and the . This standard marked a significant advancement in the SQL language specification, particularly in the area of diagnostics and error handling, by defining SQLSTATE as a five-character alphanumeric string to report the outcome of SQL statements, including success, warnings, and exceptions. The structure consists of a two-character class code followed by a three-character subclass code, providing a standardized way to categorize conditions such as data exceptions or integrity constraint violations. Prior to , SQL implementations varied in error reporting, hindering portability across systems. SQLSTATE was designed to address this issue by establishing a uniform, internationally portable diagnostic system, enabling applications to handle errors consistently regardless of the underlying database management system. This unification effort complemented the of the earlier SQLCODE integer-based status parameter from the SQL-89 standard (ISO/IEC 9075:1989), promoting while favoring the more structured SQLSTATE for future development. The development of SQLSTATE was led by the ANSI X3H2 Database Committee, which coordinated the U.S. contributions to the international effort, and the ISO/IEC JTC1/SC32 working group on database languages, responsible for harmonizing the global specification. The first formal definition appears in Part 1 (Framework) of ISO/IEC 9075:1992, particularly in Clause 22 (Diagnostics management) and related subclauses, where it is specified as the preferred status parameter within the diagnostics area, which is cleared at the start of each SQL statement. This foundational work laid the groundwork for subsequent enhancements in later SQL standards, such as SQL:1999.

Evolution in Subsequent Standards

Following its initial definition in the SQL-92 standard, SQLSTATE underwent significant expansions in SQL:1999 (ISO/IEC 9075-2:1999) to accommodate the introduction of advanced database features, particularly through the SQL Persistent Stored Modules (SQL/PSM) extension. New subclasses were added within existing classes to handle exceptions related to triggers and stored procedures, enabling more granular error reporting in procedural SQL code. For instance, the class 2F was defined for SQL routine exceptions (e.g., 2F000 for general SQL routine errors, 2F002 for prohibited SQL statements), while class 09 addressed triggered action exceptions (e.g., 09000 for general trigger failures). Additionally, class 38 was introduced for external routine exceptions (e.g., 38000 for general cases), and diagnostics items such as TRIGGER_CATALOG, TRIGGER_SCHEMA, and TRIGGER_NAME were specified to provide context-specific information during trigger execution. These additions supported the new capabilities for defining triggers (with BEFORE/AFTER timing and statement/row granularity) and invoking stored procedures, including dynamic result sets and parameter handling, while integrating with the overall diagnostics area for exception propagation. Subsequent revisions further refined SQLSTATE to align with emerging SQL functionalities. In SQL:2003 (ISO/IEC 9075:2003), the new SQL/XML part introduced support for XML data types and operations, with errors for XML-specific issues such as invalid document structures handled under the existing data exception class 22. SQL:2006 (ISO/IEC 9075:2006) enhanced XML capabilities with integration, continuing to leverage class 22 for related data exceptions without major SQLSTATE structural changes. SQL:2008 (ISO/IEC 9075:2008) built on this by enhancing support for functions, introducing refinements to and invalid cursor state exceptions (classes 21 and 24) that could arise from window frame boundary violations or ordering issues in analytic queries. By SQL:2011 (ISO/IEC 9075:2011), temporal data features—such as system-versioned and application-time period tables—were added, with error handling for temporal operations utilizing existing integrity constraint (class 23) and (class 40) exception classes to manage issues like period definition violations and rollbacks in historical queries. SQL:2016 (ISO/IEC 9075:2016) introduced data type support and row , expanding data exception handling in class 22 for parsing and validation errors, alongside refinements to diagnostics for failures. Throughout these updates, the condition handling statements SIGNAL and RESIGNAL, originally specified in SQL/PSM, were more tightly integrated with SQLSTATE, allowing developers to raise user-defined conditions with custom SQLSTATE values (e.g., via SIGNAL SQLSTATE 'XXXXX') for precise exception propagation in compound statements and handlers. As of the latest revision in SQL:2023 (ISO/IEC 9075:2023), SQLSTATE saw minor clarifications to the diagnostics framework while preserving and the established for conditions. This approach ensured seamless migration and portability for applications across prior standards, with no major new classes introduced.

Code Structure

Format and Composition

SQLSTATE codes are defined as fixed-length strings consisting of exactly five characters. The first two characters form the class code, while the last three characters form the subclass code. Each character in an SQLSTATE code must be either a from '0' to '9' or an uppercase letter from 'A' to 'Z', drawn from the ISO 646 (ASCII) character set. The class code identifies a broad category of the SQL statement's outcome, such as indicating successful completion, while the subclass code specifies a particular condition within that category, such as '000' denoting no specific subclass information. SQLSTATE codes that do not conform to these encoding rules, including those using lowercase letters, other symbols, or invalid combinations, are considered undefined by the standard, and their behavior in database systems is unspecified. In programming interfaces, SQLSTATE values are returned as character strings rather than numeric values, with no standard specification for numeric conversion. For instance, in ODBC and JDBC APIs, the diagnostic functions retrieve the SQLSTATE as a five-character string.

Class and Subclass Organization

The SQLSTATE codes are organized into 1,296 possible classes, identified by two alphanumeric characters ranging from '00' to 'ZZ', which categorize the outcome of SQL statement execution. These classes are semantically grouped into success (class 00), warnings (class 01), no data (class 02), feature-specific conditions (classes 0A to 3Z), and exceptions (classes 40 to 99, along with other predefined ranges like 07 to 3Z for specific error types). The first character of the class code often indicates the broad category: digits 0-4 or letters A-H are reserved by the SQL standard for predefined conditions, while other characters (5-9 or I-Z) allow for implementation-defined extensions by database vendors. Within each class, there is a hierarchy of up to 46,656 subclasses, identified by three alphanumeric characters ranging from '000' to 'ZZZ', providing finer-grained details about the condition. The subclass '000' typically serves as a generic indicator for the class without specifying a particular subcondition, while other values like '001' denote specific scenarios, such as cursor operations. The first character of the subclass further distinguishes between standard and non-standard definitions: digits 0-4 or letters A-H are reserved for conditions defined in the ISO/IEC 9075 SQL standard, whereas other characters (5-9 or I-Z) are available for implementation-defined subclasses, enabling vendors to extend functionality without conflicting with standard codes. For instance, Oracle uses 'U' for certain non-updatable column assignments (e.g., 0U000) and 'V' for ordering column issues (e.g., 0V000). To aid documentation and interpretation, classes are often annotated with category indicators: 'S' for success classes (00), 'W' for warnings (01), 'N' for no data (02), and 'X' for exception classes (all others). These indicators are not part of the SQLSTATE code itself but are used in and guides to classify conditions quickly. The reserves specific subclasses within classes for portability, while allowing to define additional ones to handle product-specific errors, ensuring broad compatibility across SQL implementations.

Standard Classes

Success and Warning Classes

The SQLSTATE success class, designated as "00", signifies the successful completion of an SQL statement without any detected issues or warnings. The primary subclass, 00000, indicates normal execution where the statement has fully succeeded, such as a standard SELECT query retrieving expected data or an INSERT operation adding rows without anomalies. According to ISO/IEC 9075-2:1999, database management systems (DBMS) are required to return this class for all successful outcomes to ensure consistent status reporting across compliant implementations. Additional subclasses within class 00, such as 00001 for cases involving extra result sets returned, are implementation-defined and provide optional details on non-standard but successful behaviors. In contrast, the warning class "01" denotes that an SQL has completed successfully overall, but with non-fatal conditions that may warrant attention, such as data truncation or handling. These warnings do not interrupt execution or transactions, allowing the application to proceed while accessing diagnostic information for or user notification. The standard recommends implementing class 01 codes to enhance portability, as they standardize the reporting of minor issues across different DBMS vendors. Key subclasses in class 01 include the following representative examples, as defined in the ISO/IEC 9075 standards:
SubclassMeaningContext
01000General warningCatch-all for unspecified cautionary conditions during statement execution.
01001Cursor operation conflictArises when a cursor encounters modifications by another operation, such as in positioned DELETE statements.
01003Null value eliminated in set functionOccurs during aggregation functions like or where nulls are excluded from calculations.
01004String data, right truncationTriggered by data assignment exceeding column , such as in operations.
01006Privilege not revokedIssued when attempting to revoke a non-existent or already-revoked .
These subclasses are accessible via the SQL diagnostics area, enabling applications to query and handle programmatically without assuming . In practice, class 01 ensures that potential concerns, like , are flagged early while maintaining operational continuity.

No Data and Feature Classes

Class 02, known as the No Data class, signals that an SQL operation has completed successfully but returned no rows. The primary subclass, 02000 (no data), is returned when a SELECT yields no matching rows or when a FETCH operation attempts to retrieve beyond the end of a cursor's result set. According to the SQL standard, this class is treated as both a no-data and a warning, allowing applications to handle the absence of without interpreting it as a . Applications must explicitly check for class 02 to differentiate this from true exceptions, preventing erroneous recovery logic that could disrupt normal query flows. For instance, failing to account for 02000 might lead to unnecessary rollbacks in scenarios where empty results are expected. The SQL standard recommends this verification to ensure robust handling of operations. Class 0A, the Feature Not Supported class, indicates that an SQL statement attempts to invoke a feature not implemented by the database system. The general subclass 0A000 (feature not supported) applies to unsupported elements, such as certain procedural extensions or advanced data types. This class provides diagnostic information when required SQL capabilities, like specific aggregation functions or module features, are unavailable. Additional feature-related classes include 0B (Invalid Transaction Initiation) and 0F (Locator Exception). Class 0B, with subclass 0B000 (invalid transaction initiation), arises when a cannot be properly started, such as in read-only contexts or nested transaction prohibitions. Class 0F addresses issues with locators—references to database objects like arrays or large objects—with 0F000 (locator exception) as the general code and 0F001 (invalid locator specification) for malformed locators; these highlight gaps in support for locator-based features. Unlike warning classes that accompany successful executions, these provide informative signals on capability limitations without implying .

Exception Classes

Connection and Transaction Exceptions

Connection and transaction exceptions in SQLSTATE pertain to issues arising during the establishment, maintenance, or termination of database sessions and transactions, as defined in the ISO/IEC 9075 SQL standard. These exceptions ensure that applications can detect and handle disruptions in connectivity or invalid transactional operations promptly, preventing inconsistent states or lost work. Class 08 specifically addresses connection-related failures, while classes and 40 focus on transaction lifecycle errors, such as improper termination or forced rollbacks due to conflicts. Class 08: Connection Exception signals problems with SQL connections, often stemming from network issues, unavailability, or configuration errors that prevent or interrupt session establishment. This class is raised when the SQL client cannot initiate or sustain a valid to the SQL , encompassing scenarios like failed handshakes or abrupt disconnections during execution. According to the SQL standard, implementations must raise a class 08 exception immediately upon detecting such conditions to halt further operations on the invalid . Representative subclasses include:
  • 08001 (SQL client unable to establish SQL ): Occurs when the client fails to connect due to reasons such as incorrect address, failure, or timeouts.
  • 08003 (Connection does not exist): Triggered when an operation references a non-existent name or identifier.
  • 08004 (SQL rejected establishment of SQL ): Raised if the denies the connection request, for instance, due to resource limits or security policies.
These subclasses highlight common network or session problems, ensuring diagnostic precision without delving into data-specific errors. Class 2D: Invalid Transaction Termination indicates attempts to end a in an improper or unsupported manner, such as issuing a COMMIT or outside an active context or in environments where dynamic termination is disallowed. This class enforces the of boundaries by signaling violations of the SQL standard's rules for management statements. The general subclass 2D000 (Invalid transaction termination) covers broad cases, including invalid use of COMMIT or in certain execution environments, like or when no is active. For example, executing COMMIT without an ongoing raises this exception to prevent erroneous changes. Implementations adhering to ISO/IEC 9075 must detect and report these immediately to avoid ambiguous outcomes. Specific extensions, such as 2D521 for environment-specific COMMIT invalidity, build on this foundation but align with the standard's core requirement. Class 40: Transaction Rollback denotes situations where the current is automatically or explicitly rolled back to maintain consistency, often due to deadlocks, conflicts, or violations detected during execution. Unlike exceptions, these are raised post-statement to indicate that prior changes within the transaction have been undone, requiring the application to restart the transaction if needed. The SQL standard mandates raising a class 40 exception in such cases to inform the client of the rollback without completing the statement. Key subclasses include:
  • 40000 (Transaction rollback): General rollback condition, applicable to various rollback triggers.
  • 40001 (Serialization failure): Indicates a rollback due to inability to serialize concurrent , common in high-isolation levels like SERIALIZABLE.
  • 40003 (Statement completion unknown): Used when a statement's outcome is indeterminate following a rollback, such as in distributed .
This class ensures transactional atomicity by forcing rollbacks on conflicts, with the standard emphasizing immediate exception propagation. Resolution for these exceptions typically involves reconnection for class 08 issues or transaction restart for classes 2D and 40, as the standard requires applications to handle them by re-establishing sessions or initiating new s to resume operations safely. Failure to address these can lead to persistent unavailability or data inconsistency, underscoring the need for robust error-handling in SQL clients.

Data and Integrity Exceptions

Data and integrity exceptions in SQLSTATE encompass errors arising from invalid data values, constraint breaches, and syntactic or access rule violations during SQL statement execution. These classes—22, 23, and 42—signal issues that typically prevent the successful completion of data manipulation or query operations, ensuring and adherence in compliant database systems. Class 22, designated for data exceptions, captures anomalies in data handling, such as type mismatches, out-of-range values, or invalid literals that occur during assignment, , or operations. For instance, subclass 22002 (null_value_no_indicator_parameter) is raised when a value is assigned in without an indicator parameter for the host variable. Subclass 22003 denotes a numeric value out of range, occurring when an result or cast exceeds the allowed precision or scale of the . Additionally, subclass 22007 signifies an invalid datetime format, raised when date, time, or timestamp literals fail to conform to the expected syntax or range, such as malformed strings in INSERT or UPDATE statements. These subclasses are defined in the SQL:1999 standard to standardize error reporting for during runtime evaluation. Class 23 addresses violations, which occur when data modifications contravene predefined rules like , foreign keys, or check conditions. The general subclass 23000 covers broad failures, while 23502 specifically flags violations, activated during INSERT or operations that attempt to assign to a non-nullable column. Subclass 23505 identifies breaches, such as duplicate values inserted into a column governed by a or . These errors are integral to maintaining and are invoked at statement commit or during validation in transactions. Class 42 pertains to syntax errors or access rule violations, encompassing malformed SQL statements or insufficient privileges that hinder execution. Subclass 42000 represents general syntax issues, such as unbalanced clauses or unrecognized tokens in the query parser. Subclass 42S02 (invalid_schema_name) highlights invalid schema names, often due to references to non-existent or misspelled schema qualifiers in object identifiers. This class ensures precise of structural or problems before statement processing advances. Class 44 (WITH CHECK OPTION violation), with subclass 44000, relates to violations of the WITH CHECK OPTION on s, where an UPDATE or INSERT through a view fails because the resulting row does not satisfy the view's defining . In the ISO SQL standard, these exception classes uniformly abort the offending statement, rolling back any partial effects to preserve database consistency, while populating diagnostic areas with the specific SQLSTATE code for application-level error handling and logging. This mechanism, outlined in Clause 22 of SQL:1999, facilitates portable error recovery across conforming implementations.

Usage in Database Systems

Implementation in ANSI/ISO SQL

The ISO/IEC 9075 standard, which defines the SQL language, mandates that all conforming database management systems (DBMS) populate the diagnostics area with an SQLSTATE value following the execution of each SQL statement. This requirement ensures standardized error and status reporting, enabling consistent handling of outcomes across implementations. The diagnostics area serves as a structured repository for diagnostic information, where SQLSTATE provides a five-character code indicating the completion status, warnings, or exceptions resulting from the statement. SQLSTATE integrates directly with key SQL mechanisms for retrieval and conditional handling. The GET DIAGNOSTICS statement retrieves the SQLSTATE value (along with other diagnostic details like SQLCODE and message text) from the diagnostics area into host variables or session parameters, allowing applications to inspect statement outcomes programmatically. In procedural extensions defined in ISO/IEC 9075-4 (SQL/PSM), SQLSTATE is used in DECLARE HANDLER statements to define handlers, such as HANDLER FOR SQLSTATE '23505' to address unique constraint violations, enabling CONTINUE or actions to manage exceptions within compound statements. For portability, the standard recommends that applications query SQLSTATE values rather than vendor-specific codes, as it promotes cross-DBMS by abstracting semantics into a universal format. ISO/IEC 9075 defines over 100 predefined SQLSTATE values, organized into classes (e.g., '23' for violations) and subclasses, with implementations required to use these for standard conditions while reserving user-defined codes in specific ranges. Compliance levels vary: Core SQL conformance (per Parts 1, 2, and 11 of ISO/IEC 9075) mandates basic SQLSTATE support in the diagnostics area and essential classes for reporting; full SQL conformance extends this to advanced features like comprehensive in procedural modules.

Vendor-Specific Adaptations

provides full support for the SQL standard's SQLSTATE codes, assigning five-character codes to all server-emitted messages while extending the scheme with vendor-specific subclasses for conditions not covered by the standard. These extensions include codes starting with 'XX', such as 'XX000' for internal errors that do not fit standard categories, and 'P0001' for exceptions raised via the statement in . maps these SQLSTATE values to its internal error codes, ensuring compatibility with standard SQL diagnostics while allowing for database-specific error handling in applications. MySQL and MariaDB implement SQLSTATE codes alongside their proprietary ER_ error numbers, mapping most server errors to standard SQLSTATE values but using 'HY000' (general error) as a fallback for unmapped conditions. In , this approach extends to replication errors, where many such issues—such as corrupted events or thread initialization failures—are assigned 'HY000' rather than a specific subclass, though syntax-related replication problems may fall under '42' (syntax error or access rule violation). MariaDB follows a similar pattern, providing SQLSTATE values in its error code reference for all built-in errors, with '45000' recommended for custom signals and 'HY000' for vendor-specific cases not aligned with the standard. Oracle offers partial support for SQLSTATE, primarily relying on its native SQLCODE and SQLERRM mechanisms for error reporting, but making SQLSTATE available in environments like and Pro*C/C++ when ANSI mode is enabled. In , errors in the range ORA-06500 to ORA-06599 map to SQLSTATE class '65000' for procedural language issues, representing a vendor extension beyond standard classes. This hybrid approach allows applications to access standardized codes via the SQLCA structure, though full SQLSTATE compliance requires explicit configuration. Microsoft SQL Server supports SQLSTATE codes primarily through its ODBC driver and in error messages returned by the server, aligning with the SQL standard for diagnostic reporting in client applications. While native T-SQL uses @@ERROR for error handling, SQLSTATE values are provided in the extended error information for ODBC, JDBC, and connections, enabling portable . Vendor-specific errors may use implementation-defined classes, but standard conditions map to predefined SQLSTATEs like '23000' for constraint violations. IBM Db2 maintains comprehensive SQLSTATE support with over 500 defined values, adhering closely to ISO/IEC 9075 and ANSI X3.135 standards while introducing vendor-specific subclasses in classes starting with '5' for Db2-unique conditions. These include class '51' for invalid application states (e.g., '51002' for package not found), class '53' for inconsistent specifications, and class '58' for system errors like duplicate DBID detection ('58001'). No subclasses starting with 'D' are defined, but the extensive list ensures detailed diagnostics for and other platforms. Vendor-specific extensions to SQLSTATE, such as custom classes and fallback codes, can reduce application portability by introducing non-standard values that may not map consistently across database management systems. To address this, interfaces like ODBC standardize error mapping through SQLSTATE definitions, enabling applications to handle diagnostics uniformly regardless of the underlying DBMS.

Examples and Interpretation

Common SQLSTATE Codes

SQLSTATE codes, with classes defined in the ANSI/ISO SQL standard (ISO/IEC 9075) and including both standard and common implementation-defined subclasses, serve as a portable mechanism for indicating the or failure of SQL operations, with the most common ones falling into classes for , warnings, no , and various exceptions. These enable consistent error handling across compliant database systems such as and Db2. Below is a table of 12 frequently encountered SQLSTATE codes, grouped by class, including their meanings and typical triggers.
ClassCodeDescriptionTypical Triggers
0000000Successful completionSQL statement executes without errors or warnings.
0101000General warningMinor issues like data truncation or conversion warnings during execution.
0101003Null value eliminated in aggregateAggregate functions (e.g., SUM, AVG) ignore null values in computations.
0202000No data foundQuery returns an empty result set, such as in a SELECT INTO or FETCH operation.
0808006Connection failureFailure to establish or maintain a connection to the database server.
2222001String data, right truncationInserted or updated string exceeds the target column's length limit.
2323502Not null violationAttempt to insert or update a NULL value in a column defined as NOT NULL.
2323503Foreign key violationInsert or update violates a foreign key constraint by referencing non-existent data.
2323505Unique violationInsert or update attempts to create a duplicate key in a unique index or constraint.
4040001Serialization failureTransaction rollback due to deadlock or serialization anomaly in concurrent operations.
4242601Syntax error or access rule violationInvalid SQL syntax, such as missing tokens, clauses, or improper structure.
4242S02Base table or view not foundReference to a non-existent table, view, or object in the statement.

Diagnostic Usage in Applications

In environments, applications retrieve SQLSTATE values following the execution of to diagnose or warnings. The SQL Communications Area (SQLCA) structure, included via a directive such as EXEC SQL INCLUDE SQLCA;, automatically populates the sqlstate field—a five-character —after each executable SQL . Alternatively, the standardized GET DIAGNOSTICS can explicitly fetch SQLSTATE along with other diagnostic details like messages and row counts from the diagnostics area, enabling more granular inspection in languages like (Pro*C) or . For instance, after a failed INSERT, a program might check SQLSTATE to determine if the issue stems from a violation. In database APIs such as ODBC and JDBC, SQLSTATE is accessed through exception or diagnostic mechanisms to facilitate cross-vendor error handling. For ODBC applications, after an SQL function like SQLExecDirect returns an error, developers call SQLGetDiagRec or SQLGetDiagField on the statement handle to retrieve the SQLSTATE value from the diagnostic record, which provides a standardized independent of vendor-specific error numbers. In JDBC, the SQLException.getSQLState() method returns the five-character SQLSTATE string from the thrown exception object, allowing applications to identify the error category without relying on implementation-specific codes. A common pattern involves conditional logic based on SQLSTATE, such as:
try {
    // Execute SQL statement
} catch (SQLException e) {
    String sqlState = e.getSQLState();
    if ("23505".equals(sqlState)) {
        handleDuplicateKeyException();  // Unique constraint violation
    } else if (sqlState.startsWith("23")) {
        notifyUserOfIntegrityError();   // Class 23: Data integrity issues
    }
}
This approach enables targeted recovery, like retrying transactions for transient errors. Best practices for handling SQLSTATE emphasize proactive logging and structured exception management to enhance application reliability and debugging. Applications should log the full SQLSTATE alongside the executed statement text, timestamp, and contextual details (e.g., input parameters) to a centralized error repository, facilitating root-cause analysis without exposing sensitive data to end users. For error classes like '23' (integrity constraint violations), implement dedicated handlers that attempt retries for non-fatal issues or escalate to user notifications, while broader classes like '08' (connection exceptions) trigger reconnection logic. Avoiding generic catch-all handlers prevents masking specific issues, and testing against representative SQLSTATE values from common scenarios ensures robust coverage. Object-relational mapping () frameworks integrate SQLSTATE by translating database errors into higher-level exceptions, streamlining diagnostics in modern applications. In Hibernate, for example, underlying JDBC SQLExceptions are wrapped in JDBCException subclasses, with the framework mapping SQLSTATE values to specific types like ConstraintViolationException for class '23' codes or DataAccessException for connectivity failures, allowing developers to catch and respond at the level without direct SQLSTATE inspection. This abstraction aids debugging, as traces in tools like Hibernate's logging or integrated profilers include resolved SQLSTATE details for tracing back to the originating SQL statement.

References

  1. [1]
    SQLSTATE values and common error codes - Db2 - IBM
    SQLSTATE values are five-character return codes indicating the outcome of SQL statements. They have a two-character class code and a three-character subclass ...
  2. [2]
    SQLSTATE Codes - Spark 3.5.7 Documentation
    A SQLSTATE consists of two portions: A two character class, and a three character subclass. Each character must be a digit '0' to '9' or 'A' to 'Z' .
  3. [3]
    SQLSTATE error codes | Databricks on AWS
    Sep 9, 2025 · SQLSTATE is a 5-character SQL standard encoding for error conditions, consisting of a two-character class and a three-character subclass. ...
  4. [4]
    Documentation: 18: Appendix A. PostgreSQL Error Codes
    All messages emitted by the PostgreSQL server are assigned five-character error codes that follow the SQL standard's conventions for “SQLSTATE” codes.<|control11|><|separator|>
  5. [5]
  6. [6]
    International Standard ISO/IEC 9075:1992
    ... statement> .....481 22 SQL-statement character codes for use in the diagnostics area........................................................482 23 SQLSTATE ...<|control11|><|separator|>
  7. [7]
    8 Error Handling and Diagnostics - Oracle Help Center
    SQLSTATE must be declared as a five-character alphanumeric string as in the following example: * Declare the SQLSTATE status variable. EXEC SQL BEGIN ...
  8. [8]
    Error information in the SQLCODE, SQLSTATE, and SQLWARN fields
    Practically speaking, you should use SQLSTATE values when you are concerned about portability since SQLSTATE values are common across many database managers.
  9. [9]
    D.7.3 SQLSTATE vs. SQLCODE
    Both are derived from the SQL standard, but SQLCODE has been marked deprecated in the SQL-92 edition of the standard and has been dropped in later editions.
  10. [10]
    SQLSTATE - Teradata Vantage - Analytics Database
    Oct 30, 2023 · SQLSTATE is a status variable to which SQL exception and completion conditions are posted. SQLSTATE is used both by embedded SQL applications and by stored ...Missing: signaling | Show results with:signaling
  11. [11]
    15.6.7.3 GET DIAGNOSTICS Statement - MySQL :: Developer Zone
    SQL statements produce diagnostic information that populates the diagnostics area. The GET DIAGNOSTICS statement enables applications to inspect this ...
  12. [12]
    MySQL 8.4 Reference Manual :: 15.6.7.5 SIGNAL Statement
    An SQLSTATE value can indicate errors, warnings, or “not found.” The first two characters of the value indicate its error class, as discussed in Signal ...
  13. [13]
    [PDF] ANSI/ISO/IEC International Standard (IS) Database Language SQL
    4. Concepts................................................................ 11. 4.1. Data types .
  14. [14]
    SQLSTATE values and common error codes - Db2 - IBM
    SQLSTATE values are designed so that application programs can test for specific errors or classes of errors. The first character of an SQLSTATE value indicates ...
  15. [15]
    Exception handling with SQLSTATE - HCL Product Documentation
    This section describes how to use the SQLSTATE variable and the GET DIAGNOSTICS statement to perform exception handling.
  16. [16]
    8 Error Handling and Diagnostics - Oracle Help Center
    You learn how to handle warnings and errors using the status variables SQLCODE, SQLSTATE, SQLCA (SQL Communications Area), and the WHENEVER statement. You also ...Missing: signaling | Show results with:signaling
  17. [17]
    SQL-92
    SQL-92 was developed by the INCITS Technical Committee H2 on Database. This committee develops standards for the syntax and semantics of database languages.
  18. [18]
    The SQL Standard - ISO/IEC 9075:2023 (ANSI X3.135)
    Oct 5, 2018 · SQL (Structured Query Language) standard for relational database management systems is ISO/IEC 9075:2023, with origins in ANSI X3.135.
  19. [19]
    SC 32 - JTC 1
    ISO/IEC JTC 1/SC 32, titled “Data Management and Interchange”, is responsible for a number of projects related to data management and data interchange.
  20. [20]
    [PDF] SQL 2003 Standard Support in Oracle Database 10g
    XML DB also includes a number of additional SQL extensions to support querying, updating, and transformation of XML data. Oracle is working closely with the SQL ...Missing: SQLSTATE expansions
  21. [21]
    [PDF] What's new in SQL:2011 - SIGMOD Record
    MERGE is a data manipulation command introduced in SQL:2003 and enhanced in SQL:2008. Here is an example that is permitted by SQL:2008. Suppose that. Inventory ...Missing: SQLSTATE | Show results with:SQLSTATE
  22. [22]
    Temporal features in SQL:2011 | ACM SIGMOD Record
    This paper covers the most important new functionality that is part of SQL:2011: the ability to create and manipulate temporal tables. Formats available. You ...Missing: exceptions | Show results with:exceptions
  23. [23]
    [PDF] SQL99, SQL/MM, and SQLJ: An Overview of the SQL Standards
    SIGNAL SQLSTATE - New SQL statement that halts processing and returns the requested SQLSTATE and message to the application. Format: SIGNAL SQLSTATE ...
  24. [24]
    Database languages SQL - ISO/IEC 9075-1:2023
    In stockThis document describes the conceptual framework used in other parts of the ISO/IEC 9075 series to specify the grammar of SQL and the result of processing ...
  25. [25]
    Announcing the General Availability of the SQL:2023 Standard
    Jun 2, 2023 · We are pleased to announce the publication of the new SQL:2023 Standard of which many features are supported in Oracle Database 23c Free ...Missing: SQLSTATE | Show results with:SQLSTATE
  26. [26]
    [PDF] Structured Query Language (SQL) Version 2 - The Open Group
    Database Language SQL (endorsement of. ANSI standard X3.135-1992) ...
  27. [27]
    Appendix B. Exception Codes and Messages - Firebird
    The structure of an SQLSTATE error code is five characters comprising the SQL error class (2 characters) and the SQL subclass (3 characters). i. Note.
  28. [28]
    Appendix A: ODBC Error Codes - ODBC API Reference
    Jun 25, 2024 · SQLSTATE values are strings that contain five characters. The following table lists SQLSTATE values that a driver can return for SQLGetDiagRec.
  29. [29]
    [PDF] [MS-TSQLISO02]: SQL Server Transact-SQL ISO/IEC 9075-2 ...
    May 10, 2016 · The character string value returned in an SQLSTATE parameter comprises a 2-character class ... However, Transact-SQL does support five-character.
  30. [30]
    Error Handling and Diagnostics - Oracle Help Center
    All other subclass codes are reserved for implementation-defined sub-conditions. Figure 8-1 shows the coding scheme: Figure 8-1 SQLSTATE Coding Scheme.
  31. [31]
    Compliance to SQL Standard | Exasol DB Documentation
    This article lists the mandatory and optional features of the SQL standard that are supported by Exasol.<|separator|>
  32. [32]
    [PDF] Condition Handling in SQL Persistent Stored Modules
    Below is the bnf for this SQL statement. DECLARE <handler type> HANDLER. FOR { < SQLSTATE value> I <exception name> } chandler action>. Handler declarations ...
  33. [33]
    Industry compliance - IBM
    Db2® conforms with the following industry standards for SQL: ISO/IEC 9075-1:2023, Information technology - Database languages - SQL - Part 1: Framework ...
  34. [34]
    MySQL :: Page Not Found
    Insufficient relevant content. The provided URL (https://dev.mysql.com/doc/refman/8.0/en/error-messages-server.html) results in a "Page Not Found" error, indicating the page or file is unavailable. No information on MySQL's use of SQLSTATE with ER_ codes, extensions for replication errors in class 42, or HY000 as a fallback can be extracted.
  35. [35]
  36. [36]
    MariaDB Error Code Reference | Server
    An SQLSTATE value, consisting of five characters, in this case 3D000 . These codes are standard to ODBC and ANSI SQL.
  37. [37]
    D SQLSTATE Codes
    This appendix contains a table of the SQLSTATE codes and the conditions and errors associated with them. SQLSTATE Codes. Code, Condition, Oracle Error. 00000.
  38. [38]
    Db2 SQL - GET DIAGNOSTICS statement - IBM
    The GET DIAGNOSTICS statement provides diagnostic information about the last SQL statement (other than a GET DIAGNOSTICS statement) that was executed.
  39. [39]
    SQLSTATEs - ODBC API Reference | Microsoft Learn
    Jun 25, 2024 · SQLSTATEs provide detailed information about the cause of a warning or error. The SQLSTATEs in this manual are based on those found in the ISO/IEF CLI ...
  40. [40]
    Handling SQLExceptions - JDBC Basics - Oracle Help Center
    SQLException is thrown when JDBC encounters an error with a data source. It contains a description, SQLState code, and error code. SQLWarning objects are a ...
  41. [41]
    Error and Transaction Handling in SQL Server - Erland Sommarskog
    May 3, 2015 · The aim of this first article is to give you a jumpstart with error handling by showing you a basic pattern which is good for the main bulk of your code.
  42. [42]
    Logging and Error Handling for SQL Stored Procedures
    Jan 20, 2014 · Learn how to develop and test a template for logging and error handling in a multi-step SQL stored procedure.
  43. [43]
    5.2.3. Exception handling | Hibernate Entity Manager Reference Guide
    Hibernate wraps SQLException s thrown while interacting with the database in a JDBCException . In fact, Hibernate will attempt to convert the exception into ...Missing: mapping | Show results with:mapping