Measured on SQLite 3.49.1: an INTEGER column kept the text two, an order number lost its leading zero, and sum skipped text. What STRICT tables stop.
A declared type is a preference, not a rule
Most SQL databases treat a column's declared type as a constraint. Insert the word two into an INTEGER column in PostgreSQL and the statement fails. SQLite works differently, and the SQLite documentation is direct about it: the datatype of a value is associated with the value itself, not with its container. A column's declared type only gives it a type affinity, a preference that SQLite applies when it can convert a value without losing information. When it cannot, it stores the value as it arrived.
That design is deliberate and well documented, and it rarely causes trouble when every write comes from one carefully typed application. It causes trouble when data arrives as text: CSV imports, form fields, JSON payloads, or values copied between systems by scripts. Then an INTEGER column can hold integers, reals and text side by side, comparisons depend on which side of the operator has a column, and an identifier can lose its leading zero without any error.
The running example is a small reporting database at Belgavi's Book Store, built by importing a CSV export of order lines into SQLite. Geetha noticed that a quantity total did not match the export. The companion example sqlite_affinity_strict reproduces every result below with Python's built-in sqlite3 module on CPython 3.13.5, which bundles SQLite 3.49.1.
Measured: four imported rows
The table is declared orders (order_no INTEGER, qty INTEGER, sku TEXT, price NUMERIC, note BLOB). Four rows go in with the mixture of values a CSV import and a one-off script produce.
| Value inserted | Column and affinity | Value stored | Stored type |
|---|---|---|---|
| '1001' | order_no, INTEGER | 1001 | integer |
| '01003' | order_no, INTEGER | 1003 | integer |
| '1004.0' | order_no, INTEGER | 1004 | integer |
| 'two' | qty, INTEGER | two | text |
| ' 3' (leading space) | qty, INTEGER | 3 | integer |
| '4.5' | qty, INTEGER | 4.5 | real |
| 1001 (an integer) | sku, TEXT | 1001 | text |
| 7.0 (a real) | sku, TEXT | 7.0 | text |
| '1e2' | price, NUMERIC | 100 | integer |
| 'abc' | price, NUMERIC | abc | text |
Every insert succeeded. Order number 01003 became the integer 1003, so the leading zero that some upstream system meant as part of an identifier is gone. The quantity column now holds an integer, a real and the text two. Then the queries:
SELECT sum(qty)returned 9.5. The texttwocounted as zero, without a warning.ORDER BY qtyreturned 2, 3, 4.5 and thentwo, because SQLite sorts all numbers before all text.WHERE qty = '2'matched one row andWHERE sku = 1001matched one row, because when one operand is a column, SQLite applies that column's affinity to the other operand before comparing.SELECT 2 = '2'returned 0, and'10' < '9'returned 1. With no column involved, no affinity is applied, so an integer never equals text and text compares as text.
The last two bullets are why the same comparison can give different answers in a view, a subquery and a parameterized query, depending on whether a column sits on one side.
Why it happens
SQLite has five storage classes: NULL, INTEGER, REAL, TEXT and BLOB. A column declared INTEGER gets INTEGER affinity, which behaves like NUMERIC affinity: text that is a well-formed integer or real literal is converted, and anything else is kept as text. A real value with no fractional part, such as 4.0 or the string 1004.0, is converted to an integer. In the probe, text with a leading space, ' 3', was also converted, to 3; the datatype page does not spell out whitespace handling, so treat that as measured behaviour of 3.49.1 rather than a documented rule. A column declared TEXT converts numbers to their text form. The declared type name only matters through a set of substring rules: anything containing INT gets INTEGER affinity, CHAR, CLOB or TEXT gives TEXT, and so on. A column declared DATETIME gets NUMERIC affinity.
STRICT tables
Since SQLite 3.37.0 (November 2021), a table can opt into strict typing by adding the STRICT keyword after the column list. In a STRICT table, the declared type must be one of INT, INTEGER, REAL, TEXT, BLOB or ANY. SQLite still converts a value when the conversion is lossless, and raises an error when it is not.
CREATE TABLE orders_strict (
order_no INTEGER,
qty INTEGER,
sku TEXT,
price REAL,
note ANY
) STRICT;The same probe against this table:
| Value inserted | Column | Result |
|---|---|---|
| '1001' | order_no INTEGER | stored as integer 1001 |
| 'two' | qty INTEGER | error: cannot store TEXT value in INTEGER column |
| 4.5 | qty INTEGER | error: cannot store REAL value in INTEGER column |
| 4.0 | qty INTEGER | stored as integer 4 |
| 1001 | sku TEXT | stored as text 1001 |
| '1e2' | price REAL | stored as real 100.0 |
| (column declared DATETIME) | table definition | error: unknown datatype |
STRICT tables stop the silent text-in-a-number-column case, which is the one that corrupts aggregates. They do not stop lossless conversions, so '01003' would still become 1003 in an INTEGER column. Identifiers that are not numbers should be declared TEXT, in strict and non-strict tables alike.
Adapting an existing database
A table cannot be switched to STRICT in place. The usual path is to create a new STRICT table, copy rows through a query that exposes bad values, and swap names inside a transaction.
- Find the damage first:
SELECT typeof(qty), count(*) FROM orders GROUP BY 1. Any row whose type differs from the column's intent is a finding. - Decide per finding: fix the source, convert explicitly, or quarantine the row. Do not let a migration discard rows silently.
- Declare identifiers that may carry leading zeros or letters as
TEXT, and check them against the source system, because some zeros may already be gone. - Create the STRICT table, copy with
INSERT INTO ... SELECT, and let the copy fail on rows you have not handled. - Recreate and verify dependent indexes, triggers, views and foreign-key relationships using SQLite's documented table-rebuild procedure. Complete the rename inside the migration transaction, then run the type audit and foreign-key check again.
For tables you cannot rebuild, a CHECK (typeof(qty) = 'integer') constraint gives similar protection on new writes. The probe shows the subtlety: the check runs after affinity conversion, so '3' and 3.0 pass because they were already converted to integers, while 'three' and 3.5 fail.
Failure modes to look for
Imports through text. CSV readers return strings. Python's sqlite3 binds a str as TEXT, so every value relies on affinity conversion. A value the converter rejects is kept as text and nothing errors.
Comparisons without a column. A query that compares a parameter with a computed expression, such as coalesce(qty, 0) = ?, gets no affinity help. Bind values with the type you mean.
Lost identifiers. Leading zeros, long numeric strings that do not fit a 64-bit integer and codes like 007A behave differently. The first two convert or overflow, the last is kept as text. Store identifiers as text.
Reports that sum text as zero. sum and total skip values they cannot read as numbers, so totals drift quietly. Audit typeof before trusting a total.
When you do not need any of this
If a single application owns every write and binds typed parameters, affinity is invisible. If the data is append-only logs where a stray type is harmless, a periodic typeof audit may be enough. The rebuild is worth it for tables that feed money, stock or identifiers.
How to verify it
Run a type audit over every column: SELECT typeof(col), count(*) FROM t GROUP BY 1. Add a test that inserts a deliberately bad value through each import path and expects an error, which is the test STRICT tables make pass. Then re-run the aggregates your reports depend on and compare them with the source system's totals. The companion example runs the whole probe above and checks each stored value and error message.