← Back to SQL, page 9

sql-0164 · Medium mid

In SQLite, what does typeof() return after inserting '42', '4.5' and 'abc' into a column declared INTEGER?

SQLite uses type affinity: a declared INTEGER column converts text that looks like a number, so '42' is stored as integer 42 and '4.5' as real 4.5. Text that is not numeric, such as 'abc', is stored as text. PostgreSQL rejects 'abc' for an integer column.

Full answer
sql
CREATE TABLE t (n INTEGER);
INSERT INTO t VALUES ('42'), ('4.5'), ('abc');
SELECT n, typeof(n) AS stored_as FROM t ORDER BY rowid;
nstored_as
42integer
4.5real
abctext

The declared type is a preference, not a rule. SQLite tries to convert to the column's affinity and keeps the original value when conversion would lose information.

PostgreSQL enforces the type:

sql
CREATE TABLE t (n INTEGER);
INSERT INTO t VALUES ('abc');
-- error on purpose
text
Error: invalid input syntax for type integer: "abc"

This flexibility makes SQLite forgiving in prototypes and surprising in production data. Bad values slip in silently and show up later as odd sorting or failed joins. STRICT tables, a CHECK on typeof(col), or validation in the application close the gap.

sql
CREATE TABLE t (n INTEGER);
INSERT INTO t VALUES ('42'), ('4.5'), ('abc');
SELECT n, typeof(n) AS stored_as FROM t ORDER BY rowid;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • Declared types in SQLite set an affinity, not a hard type
  • Numeric-looking text is converted to numbers
  • Non-numeric text is stored as text
  • PostgreSQL rejects values that do not fit the type

Common mistakes

  • Assuming an INTEGER column in SQLite only contains integers
  • Discovering mixed types only when sorting or joining

Follow-ups

  • What are STRICT tables?
  • How would you find rows with the wrong storage type?

Tips

  • Use typeof() to show the evidence