// conversion reference

SQLite type affinity

A SQLite column has a preferred storage class, not an enforced type. INTEGER affinity converts numeric text on insert and stores anything else as it arrived.

Category
Conversion
Returns
depends on affinity
In this category
19 of 39

Syntax

CREATE TABLE t (col INTEGER);  -- affinity, not a constraint

Engine support

EngineSupportNotes
SQL Server Not built in columns enforce real types
PostgreSQL Not built in columns enforce real types
MySQL Not built in columns enforce real types (mode-dependent)
SQLite Yes Supported under this name.
Oracle Not built in columns enforce real types

Examples

SQLite

CREATE TABLE t (n INTEGER);
INSERT INTO t VALUES ('123'), ('abc');
SELECT n, typeof(n) FROM t;

SQLite

SELECT CAST('abc' AS INTEGER) AS n;

Good to know

  • Affinity is a preference, not a constraint: an INTEGER-affinity column stores the text 'abc' unchanged because it cannot be converted losslessly; only numeric text becomes a number.
  • typeof() tells you what actually got stored, which is how you debug affinity surprises; CAST inside a query changes the query's answer, never the stored rows.
  • A REAL-affinity column turns inserted integers into floats: 3 becomes 3.0. Use NUMERIC affinity when whole numbers should stay integers.
  • STRICT tables (SQLite 3.37+) do enforce types: inserting 'abc' into an INTEGER column of a STRICT table fails with 'cannot store TEXT value in INTEGER column'.

Questions about Type affinity

Is affinity a constraint?

No. In an ordinary table an INTEGER column stores blobs and text without complaint; affinity only decides whether an inserted value gets converted. Declare the table STRICT, or add a CHECK (typeof(col) = 'integer'), to reject wrong types.

Why did my integer become 123.0?

The column has REAL affinity: integers convert to floats on storage. NUMERIC affinity keeps integers whole, or CAST the value explicitly before inserting.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQLite.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.