SQL: Structured Query LanguageSQL FundamentalsType Validation and Insertion Errors
What happens when a value is inserted into a column with an incompatible data type?
Question 16 of 30 · Updated
On this page
- 1. What the database checks
- 2. A practical PostgreSQL insertion example
- 3. Successful conversion does not mean preservation
- 4. Invalid syntax, range errors and incompatible expressions
- 5. Distinguish type errors from constraints
- 6. What happens to the statement and transaction?
- 7. SQLite: flexible typing versus STRICT tables
- 8. Safe bulk import and data validation
- 9. Production guidance and common mistakes
- 10. Interview-ready answer
- Validation and references
When an INSERT supplies a value that is incompatible with the target column's data type, the database first determines whether an allowed conversion can produce a valid value of that type. If conversion succeeds and all applicable constraints are satisfied, the converted value can be stored. If the conversion is unsupported, the value has invalid syntax, or the result exceeds the type's limits, a strongly typed database such as PostgreSQL normally rejects the statement with an error.
An important distinction is that an input of a different type is not necessarily incompatible. The text literal '42' can be interpreted as an integer in appropriate PostgreSQL contexts, but 'abc' cannot. Some successful conversions lose information or round the value. Other database engines may apply more permissive conversion rules, so the result is not universal across SQL dialects.
1. What the database checks#
An INSERT must resolve the target columns, determine the input expression types, perform any allowed conversion to the target types, and enforce applicable column and table constraints. This conceptual flow emphasizes type validation; actual implementation details, constraint timing and triggers vary by database engine.
Type compatibility is necessary but not sufficient. For example, -5 is a valid integer but may violate a nonnegative inventory constraint. A successful statement also does not necessarily mean the data has been committed: the transaction may still be open or may fail later, including on a deferred constraint.
2. A practical PostgreSQL insertion example#
Consider this illustrative schema for a disposable database:
SQLCREATE TABLE inventory_items ( item_id INTEGER PRIMARY KEY, quantity INTEGER NOT NULL CHECK (quantity >= 0), unit_price NUMERIC(5,2) NOT NULL CHECK (unit_price >= 0 AND unit_price <> 'NaN'::numeric) );
The following statements illustrate different outcomes in PostgreSQL. Execute deliberately failing statements separately, or use savepoint recovery inside an explicit transaction. These INSERT statements and their DDL are illustrative; the live PostgreSQL tests below use only read-only expressions and synthetic inline rows.
SQLINSERT INTO inventory_items VALUES (1, 42, 12.50); INSERT INTO inventory_items VALUES (2, '42', 12.345); -- Expected: quantity 42 and price 12.35. INSERT INTO inventory_items VALUES (3, 'abc', 10.00); -- Expected: invalid integer input syntax. INSERT INTO inventory_items VALUES (4, 2147483648, 10.00); -- Expected: integer out of range. INSERT INTO inventory_items VALUES (5, -5, 10.00); -- Expected: CHECK constraint violation. INSERT INTO inventory_items VALUES (6, NULL, 10.00); -- Expected: NOT NULL constraint violation.
The second statement illustrates an initially untyped string literal resolved in the integer target context, plus a decimal value rounded to the column's declared scale. An explicitly typed TEXT expression is different: PostgreSQL does not automatically permit every conversion available through an explicit CAST. Drivers can also send typed parameters, which changes the resolution context. Do not assume a value accepted as an untyped SQL literal is accepted in every parameterized statement.
3. Successful conversion does not mean preservation#
The following read-only PostgreSQL query demonstrates representable conversions directly:
SQLSELECT CAST('42' AS integer) AS parsed_integer, CAST(12 AS bigint) AS widened_integer, CAST(12.345 AS numeric(5,2)) AS rounded_decimal;
| parsed_integer | widened_integer | rounded_decimal |
|---|---|---|
| 42 | 12 | 12.35 |
The input 42 fits the target integer type. Widening a small integer value to BIGINT also succeeds. Converting 12.345 to NUMERIC(5,2) rounds its fractional digits. Successful conversion therefore does not guarantee that the original representation or every digit is preserved. Validate the original input when the business requires exact preservation rather than rounding or truncation.
4. Invalid syntax, range errors and incompatible expressions#
PostgreSQL supports pg_input_is_valid and pg_input_error_info in supported versions to test the textual input accepted by many types. They let us inspect errors for the integer type without intentionally aborting a transaction. They do not test the full INSERT pipeline, permissions or constraints.
SQLSELECT v.raw_value, pg_input_is_valid(v.raw_value,'integer') AS valid_integer, e.sql_error_code FROM (VALUES ('42'), ('abc'), ('2147483648')) AS v(raw_value) CROSS JOIN LATERAL pg_input_error_info(v.raw_value,'integer') AS e ORDER BY v.raw_value;
| raw_value | valid_integer | sql_error_code |
|---|---|---|
| 2147483648 | FALSE | 22003 |
| 42 | TRUE | NULL |
| abc | FALSE | 22P02 |
The integer range in PostgreSQL is -2147483648 to 2147483647. The value 2147483648 is a syntactically valid whole number, but cannot be represented as INTEGER. By contrast, abc is not valid integer input syntax. The valid input 42 has no error code.
Other target types have their own validity rules:
SQLSELECT pg_input_is_valid('2026-02-30','date') AS valid_date, pg_input_is_valid('maybe','boolean') AS valid_boolean, pg_input_is_valid('1000','numeric(5,2)') AS valid_amount;
| valid_date | valid_boolean | valid_amount |
|---|---|---|
| FALSE | FALSE | FALSE |
An impossible calendar date, an unsupported Boolean spelling and a decimal magnitude outside its allowed precision all fail these input checks.
5. Distinguish type errors from constraints#
| PostgreSQL SQLSTATE | Typical meaning | Example |
|---|---|---|
| 42804 | Datatype mismatch | Expression type cannot be assigned to the target column |
| 22P02 | Invalid text representation | abc supplied to an integer input parser |
| 22003 | Numeric value out of range | Integer overflow |
| 22001 | String data right truncation | Ordinary assignment of an overlength non-space string to a bounded character column |
| 23502 | Not-null violation | NULL supplied to a NOT NULL column |
| 23514 | Check violation | Negative quantity rejected by CHECK |
| 23505 | Unique violation | Duplicate primary key |
SQLSTATE codes are useful for application error handling because human-readable error messages can change or be localized. The two integer conversion SQLSTATE values above were independently observed through pg_input_error_info. The other codes are explanatory PostgreSQL examples, not individually tested error paths in this session.
A type specifies representable values; constraints express additional rules about those values and their relationships. Do not change an INTEGER column to TEXT just to make invalid quantities insert successfully. Determine why the source is invalid and fix the mapping or validation instead.
6. What happens to the statement and transaction?#
In ordinary PostgreSQL execution, if any row in a multi-row INSERT causes an unhandled type conversion error, the statement fails as a unit; the earlier rows from that failed statement are not retained as successful inserts. This differs from running several separate statements with autocommit, where earlier successful statements may already be committed.
Inside an explicit PostgreSQL transaction, an unhandled SQL error generally leaves the transaction in an aborted state until ROLLBACK, or until recovery to a savepoint established before the failing statement. Continuing to send ordinary queries without recovery may produce SQLSTATE 25P02 (in_failed_sql_transaction). An application should manage rollback at the appropriate transaction boundary and avoid blindly retrying invalid data.
For example, after creating the illustrative inventory table in an isolated environment:
SQLBEGIN; SAVEPOINT before_import; INSERT INTO inventory_items VALUES (10, 8, 1.00), (11, 'abc', 1.00); -- Expected: this entire INSERT fails. ROLLBACK TO SAVEPOINT before_import; INSERT INTO inventory_items VALUES (10, 8, 1.00); COMMIT;
Run this example with a client that permits sending the recovery command after an error. It is an illustrative PostgreSQL transaction sequence; it was not executed on the publishing database. This recovery pattern does not imply that every type error should be ignored: retain information about rejected input and make the import policy explicit. Special conflict-handling features such as PostgreSQL ON CONFLICT handle specified uniqueness or exclusion conflicts, not arbitrary datatype errors.
7. SQLite: flexible typing versus STRICT tables#
SQLite ordinarily uses type affinity rather than PostgreSQL-style fixed column typing. An ordinary INTEGER-affinity column can retain text that cannot be converted to an integer. SQLite STRICT tables, available from version 3.37.0, enforce compatible storage types and allow lossless conversions where supported.
The following DDL and successful inserts were executed in an isolated in-memory SQLite 3.46.1 database:
SQLCREATE TABLE loose_items(qty INTEGER); CREATE TABLE strict_items( qty INTEGER NOT NULL CHECK(qty >= 0) ) STRICT; INSERT INTO loose_items VALUES ('abc'); SELECT qty, typeof(qty) FROM loose_items; INSERT INTO strict_items VALUES ('42'); SELECT qty, typeof(qty) FROM strict_items;
| Table | qty | typeof(qty) |
|---|---|---|
| loose_items | abc | text |
| strict_items | 42 | integer |
Each of the following statements was then executed separately against the same isolated strict table and rejected:
SQLINSERT INTO strict_items VALUES ('abc'); INSERT INTO strict_items VALUES (-5); INSERT INTO strict_items VALUES (NULL); INSERT INTO strict_items VALUES (7), ('abc');
After each failure, the strict table still contained only the original integer 42. The final multi-row INSERT did not retain 7. This verifies the ordinary statement-abort behavior in the tested SQLite configuration, not every possible conflict policy or PostgreSQL transaction rule. SQLite and PostgreSQL can differ in how failures affect an enclosing transaction. MySQL behavior can depend on SQL mode, the statement form and the storage engine; permissive configurations may coerce some inputs and issue warnings. Test the target database rather than relying on generalizations.
8. Safe bulk import and data validation#
When importing external CSV or API data, one invalid row should not silently corrupt the other records. A useful approach is to stage raw text, validate type and range, apply business rules, and separate accepted records from rejected records before writing to the destination. Preserve a safe record identifier and rejection reason for correction.
Here is a tested PostgreSQL read-only example using synthetic incoming quantities:
SQLWITH incoming(id, raw_quantity) AS ( VALUES (1,'12'), (2,'abc'), (3,'2147483648'), (4,'-5'), (5,NULL::text) ), parsed AS ( SELECT id, raw_quantity, CASE WHEN pg_input_is_valid(raw_quantity,'integer') THEN raw_quantity::integer END AS quantity FROM incoming ) SELECT id, raw_quantity, quantity, CASE WHEN raw_quantity IS NULL THEN 'missing' WHEN quantity IS NULL THEN 'invalid_type_or_range' WHEN quantity < 0 THEN 'invalid_business_rule' ELSE 'accepted' END AS validation_status FROM parsed ORDER BY id;
| id | raw_quantity | quantity | validation_status |
|---|---|---|---|
| 1 | 12 | 12 | accepted |
| 2 | abc | NULL | invalid_type_or_range |
| 3 | 2147483648 | NULL | invalid_type_or_range |
| 4 | -5 | -5 | invalid_business_rule |
| 5 | NULL | NULL | missing |
CASE guards the conversion in this example, so only values that pass the integer input check are cast. The query distinguishes missing input from invalid input and from a valid integer that violates a business rule. A real import must also enforce the destination constraints at write time and handle concurrency, duplicates, security and any transaction failures. Do not log sensitive raw input unnecessarily.
9. Production guidance and common mistakes#
Use parameterized SQL with values supplied through the driver. Validate incoming data according to the application contract and retain database constraints as a final integrity boundary. Match numeric ranges, string lengths, temporal types and nullability to domain requirements. Do not treat every conversion warning as harmless, do not silently replace invalid values with zero, and do not use unbounded TEXT merely to avoid error handling. For batch operations, define whether all rows must succeed together or invalid rows should be quarantined; design transaction and savepoint handling accordingly.
10. Interview-ready answer#
When a value is inserted into a column with an incompatible data type, the database may convert the input if an allowed conversion exists and the resulting value fits the target type. Otherwise it rejects the statement with an error, such as invalid input syntax, datatype mismatch or numeric overflow. For example, PostgreSQL can interpret the literal '42' as an integer but rejects 'abc' for an integer column. Successful conversion may still round a decimal, and a correctly typed value can fail NOT NULL or CHECK constraints. In PostgreSQL, a failed multi-row INSERT normally fails atomically and an explicit transaction requires appropriate rollback or savepoint recovery. Other engines, including SQLite's ordinary affinity-based tables, may behave differently. Validate input, use appropriate types and handle errors explicitly.
Validation and references#
Four read-only PostgreSQL queries passed: successful casts, integer validity and observed SQLSTATE values, invalid date/Boolean/numeric inputs, and staged-input classification. Six scenarios passed in an isolated in-memory SQLite 3.46.1 database: ordinary affinity acceptance, lossless STRICT conversion, invalid text rejection, CHECK rejection, NOT NULL rejection and multi-row statement failure with unchanged existing rows. PostgreSQL INSERT, DDL and savepoint sequences were illustrative rather than executed; other-engine behavior was not tested except for SQLite. No educational DDL or application data writes were performed on production tables.
The Mermaid flowchart was checked structurally for node and edge syntax and reviewed against the described logic. It is stored in the required triple-backtick mermaid code block with real line breaks. Full Mermaid parser validation and live public rendering remain unverified.
Documentation consulted through the Supabase documentation connector:
- Supabase — Tables and data: typed columns, supported data types and conversion incompatibilities.
Additional authoritative reading (not live-verified in this session):
- PostgreSQL — Type Conversion.
- PostgreSQL — Error Codes.
- PostgreSQL — System Information Functions.
- PostgreSQL — Transactions.
- SQLite — Datatypes.
- SQLite — STRICT Tables.
Live web browsing was unavailable. Additional references are suggested reading, rather than independently consulted sources.
References
- 1.Supabase — Tables and datasupabase.com
- 2.PostgreSQL — Type Conversion (not live-verified)postgresql.org
- 3.PostgreSQL — Error Codes (not live-verified)postgresql.org
- 4.
- 5.PostgreSQL — Transactions (not live-verified)postgresql.org
- 6.SQLite — Datatypes (not live-verified)sqlite.org
- 7.
Related questions
Explore other topics:Forward Deployed EngineeringPythonAI System DesignMachine Learning