Troubleshooting
SQLCode -302 with SQLState 22001 stopped my Db2 migration cold last week. ⚡ The error means your data exceeds a column's defined size, and the database refuses to accept it—no warnings, just a hard rejection.
This isn't just a syntax issue; it's a data integrity problem that can derail entire transactions if you're not careful.
The root cause is almost always a mismatch between what you're trying to store and what the schema allows. Maybe you're importing CSV data with extra decimal places into a DECIMAL(10,2) field, or a VARCHAR(50) gets hit with a 60-character string.
Db2, SQL Server, and even MySQL throw this same error when data truncation occurs during INSERT or UPDATE operations. The fix isn't about the query—it's about the data itself.
You'll resolve this in three targeted steps: first validate your data against the schema using a simple SELECT query with LENGTH() or CAST checks, then clean or truncate the problematic fields, and finally retry your operation.
I've seen this error waste hours when teams treat it as a query problem instead of a data problem. The solution is straightforward once you know where to look.
Works across Db2, SQL Server, and PostgreSQL—just adjust the data type functions for your specific database. Let's walk through the exact queries that saved my migration from becoming a fire drill.
Why it happens
When you encounter SQLCODE=-302 with SQLSTATE=22001, you're dealing with a data truncation error—a common but frustrating issue in database operations. This error occurs when a value you're trying to insert, update, or retrieve exceeds the maximum storage capacity of the target column.
Let’s break down the root causes in detail.
###
🔍 1. Mismatched Data Types
One of the most frequent culprits is a mismatch between the data type of your input and the column’s defined type. For example:
- String vs. VARCHAR: If you’re inserting a 500-character string into a
VARCHAR(100)column, the database will reject it with this error. - Integer vs. SMALLINT: A value like
32768(which fits in anINT) exceeds the range of aSMALLINT(which only supports values up to32,767). - Floating-Point Precision: A decimal like
123.456789may truncate if stored in a column with lower precision, such asDECIMAL(5,2).
Why it happens: The database enforces strict type constraints to maintain data integrity. If your input doesn’t conform, SQL rejects it outright.
###
📏 2. Exceeding Column Length Limits
This is the classic "too much data" scenario. Columns have predefined storage limits, and if your input surpasses them, truncation occurs:
- VARCHAR/CHAR Limits: A
VARCHAR(50)column can’t hold a 60-character string, even if the extra characters are spaces or special symbols. - LOB (Large Object) Constraints: While LOB types like
CLOBorBLOBhandle large data, they still have implicit or explicit size limits (e.g.,CLOB(1000)vs.CLOB(2000)). - Unicode vs. Non-Unicode: A single Unicode character (e.g.,
é) occupies 2 bytes, while ASCII uses 1. AVARCHAR(100)column in a non-Unicode environment might fail if it contains 50+ Unicode characters.
Why it happens: Databases allocate memory based on column definitions. If your data outgrows its allocated space, SQL truncates it to fit—or throws an error if strict mode is enabled.
###
🔄 3. Automatic Data Conversion Failures
Sometimes, SQL tries to convert your input to fit the target column, but the conversion fails or produces unexpected results:
- String to Numeric: Inserting
'123ABC'into a numeric column (e.g.,INT) will truncate the non-numeric part, but if the column isDECIMAL(5,2), the entire value may be rejected. - Timestamp Truncation: A
TIMESTAMPcolumn with precision(6)can’t store microsecond-level data if your input has nanosecond precision. - Hex/Binary Mismatches: Trying to store a 32-byte binary string in a 16-byte
BLOBcolumn will trigger truncation.
Why it happens: SQL performs implicit conversions, but some transformations (like string-to-numeric or high-precision truncation) can’t be resolved without data loss or errors.
###
🔧 4. Application Logic Gaps
Not all truncation errors stem from database design. Application code or user input can also cause issues:
- Dynamic SQL with Unsanitized Input: If your app builds SQL queries dynamically (e.g., using
EXECUTE IMMEDIATEin PL/SQL), user-provided data might exceed column limits without validation. - Batch Inserts with Varying Lengths: A batch operation inserting rows with inconsistent data lengths (e.g., some strings are 200 chars, others 50) can fail if the schema isn’t flexible.
- Missing NULL Checks: A
NOT NULLconstraint on a column with a length limit (e.g.,VARCHAR(10) NOT NULL) will reject any input longer than 10 characters, even if the column allows NULLs elsewhere.
Why it happens: Applications often assume data will fit, but real-world inputs (user typos, API responses, or legacy data) rarely conform to expectations.
Pro Tip: 💡 Use LENGTH() or DATA_LENGTH() functions in your queries to pre-check input sizes before insertion. For dynamic SQL, implement TRY-CATCH blocks (or equivalent error handling) to gracefully manage truncation errors.
Fixing Data Truncation Errors in SQL
Encountering SQLCODE=-302 with SQLSTATE=22001 can feel like hitting a roadblock—your database is rejecting data because it’s too long for the target column. But don’t panic! With the right approach, you can resolve this issue quickly and prevent future headaches.
Below are step-by-step solutions tailored to the most common causes, along with practical prevention tips to keep your database running smoothly.
🔥 When Data Exceeds Column Limits: Adjusting Table Structures
If your error stems from inserting or updating data that’s longer than the column’s defined size, you’ll need to modify the table structure to accommodate the new data. Here’s how:
-
🔧 Identify the problematic column:
Run a query to inspect the column’s current data type and length. For example:
Or, for a more detailed view:DESCRIBE yourtablename;SELECT COLUMNNAME, DATATYPE, CHARACTER_MAXIMUM_LENGTH FROM INFORMATIONSCHEMA.COLUMNS WHERE TABLENAME = 'yourtablename'; -
📏 Expand the column size:
Use
ALTER TABLEto increase the column’s length. For a VARCHAR column:
For a CHAR column:ALTER TABLE yourtablename ALTER COLUMN yourcolumnname VARCHAR(255);ALTER TABLE yourtablename ALTER COLUMN yourcolumnname CHAR(100); - ✅ Test the fix: Retry your INSERT or UPDATE statement to ensure the error is resolved. If the column is part of a constraint (like a PRIMARY KEY or UNIQUE), you may need to drop and recreate it after altering the column.
💡 Pro Tip: If you’re unsure about the optimal length, check the maximum data size in your current dataset. For example:
SELECT MAX(LENGTH(yourcolumnname)) FROM yourtablename;
Round up to the nearest practical size (e.g., 255 for VARCHAR is a safe default for most text fields).
🍳 Truncating Data on Import: Cleaning or Trimming Input
Sometimes, the issue isn’t the table—it’s the data you’re trying to import. If you’re working with external files (CSV, Excel, etc.), the data might exceed limits even if the table could theoretically hold it. Here’s how to handle it:
-
📊 Check the source data:
Open your input file (e.g., CSV or Excel) and verify the length of the problematic field. Use a tool like
LENGTH()in your query or a spreadsheet function like=LEN(A1)to spot inconsistencies. -
🔪 Trim or truncate the data:
If the data is too long but contains unnecessary characters (e.g., trailing spaces, newlines), clean it before importing:
If you need to hard-cut the data, use-- Example: Trim whitespace from a VARCHAR column UPDATE yourtablename SET yourcolumnname = RTRIM(LTRIM(yourcolumnname));SUBSTRING():-- Example: Limit to 100 characters UPDATE yourtablename SET yourcolumnname = SUBSTRING(yourcolumnname, 1, 100); -
🔄 Re-import with validation:
Before loading data into the table, validate its length against the column’s constraints. For example, in a script or ETL process, add a check like:
IF LENGTH(yourcolumn) > 255 THEN -- Log the error or truncate yourcolumn = SUBSTRING(yourcolumn, 1, 255); END IF;
🌡️ Prevention Tip: Automate data validation in your pipelines. Tools like Apache NiFi, Talend, or even simple Python scripts with pandas can pre-check data lengths before database insertion.
⏰ Temporary Workarounds: Using Larger Data Types
If altering the table isn’t an option (e.g., due to schema constraints or permissions), you can use a larger data type temporarily to bypass the error. Here’s how:
-
📝 Create a staging table:
Design a temporary table with a larger column size to hold the truncated data:
(AdjustCREATE TABLE temptablename AS SELECT *, SUBSTRING(yourcolumnname, 1, 4000) AS extendedcolumn FROM yourtablename;4000based on your database’s maximum limit, e.g.,32767for some SQL dialects.) -
🔄 Migrate data gradually:
Use a script to move data from the original table to the temporary one, then truncate or clean the original data:
INSERT INTO temptablename (column1, extendedcolumn) SELECT column1, yourcolumnname FROM yourtablename; - 🔄 Resolve the root issue: Once the data is safely stored, address the original problem (e.g., by expanding the column or cleaning the source data). Then, migrate back to the original table if needed.
✨ Pro Tip: For databases like DB2 or SQL Server, consider using CLOB (Character Large Object) or TEXT data types for columns that frequently exceed standard lengths. Example:
ALTER TABLE yourtablename
ALTER COLUMN yourcolumnname CLOB(1M); -- Supports 1MB of text
🎯 Long-Term Prevention: Best Practices for Database Design
To avoid SQLCODE=-302 errors in the future, adopt these habits:
-
✅ Plan column sizes wisely:
Use realistic defaults based on your data’s typical length. For example:
VARCHAR(255)for most text fields (emails, names, descriptions).CHAR(10)for fixed-length identifiers (e.g., ZIP codes).CLOBorTEXTfor large, variable-length content (e.g., JSON, XML, or logs).
-
📊 Document data constraints:
Maintain a
DATADICTIONARYtable or comments in your schema to track expected lengths and formats. Example:-- Example: Add a comment in DB2 or SQL Server COMMENT ON COLUMN yourtablename.yourcolumnname IS 'Expected length: 1-255 chars. Avoid special characters.'; -
🔄 Implement validation layers:
Add checks in your application code or stored procedures. For example, in PL/SQL:
BEGIN IF LENGTH(:yourcolumn) > 255 THEN RAISEAPPLICATIONERROR(-20001, 'Data exceeds column limit!'); END IF; -- Proceed with INSERT/UPDATE END; -
🔄 Schedule regular audits:
Run queries to identify columns approaching their limits. Example:
SELECT TABLENAME, COLUMNNAME, CHARACTER_MAXIMUM_LENGTH, AVG(LENGTH(C
Frequently asked questions
Why does SQLCODE=-302 with SQLSTATE=22001 appear during data imports?
This error occurs when your import data exceeds the column's defined storage limits in the database. For example, inserting a 60-character string into a VARCHAR(50) column triggers this error. It's not a syntax issue but a data integrity violation that prevents truncation in strict database modes.
Can I fix this error without altering the table structure?
Yes! You can pre-process your data using SUBSTRING() or RTRIM() functions to trim excess characters before insertion. For example: UPDATE table SET column = SUBSTRING(column, 1, 100). This avoids schema changes while resolving the truncation issue.
Does this error affect only string columns?
No, it impacts all data types. For numeric columns, values exceeding the defined range (like 32768 in a SMALLINT) trigger this error. For timestamps, precision mismatches (e.g., nanosecond data in a TIMESTAMP(6) column) can also cause it. The root cause is always data exceeding storage capacity.
How can I prevent this error in future database operations?
Implement validation layers in your application code using LENGTH() checks before database operations. For example, in PL/SQL: IF LENGTH(:input) > 255 THEN RAISE_APPLICATION_ERROR(-20001, 'Data too long'); END IF;. Also document column constraints in your data dictionary.
Will this error appear in all database systems?
While the error codes may vary slightly, the concept is universal. IBM Db2, SQL Server, and PostgreSQL all throw truncation errors with similar SQLSTATE values (22001). The fix approach remains consistent across systems: validate data against schema constraints before operations.
