← Back to SQL, page 21

sql-0410 · Easy fresher

Predict typeof() for 1, 1.0, '1', NULL and x'01' in SQLite.

The results are integer, real, text, null and blob. SQLite has five storage classes, and typeof() reports the class of each value, not of a column.

Full answer
sql
SELECT typeof(1) AS a, typeof(1.0) AS b, typeof('1') AS c, typeof(NULL) AS d, typeof(x'01') AS e;
abcde
integerrealtextnullblob

Literals keep their own storage class: a number without a decimal point is an integer, with a decimal point it is a real, quoted values are text, x'..' is a blob literal and NULL is null. In a table, the column's affinity may convert values on insert; for example inserting '1' into an INTEGER column stores the integer 1. Checking typeof(col) across rows is a quick way to find mixed types in a column that was loaded from CSV. PostgreSQL has pg_typeof(), which reports declared types instead.

sql
SELECT typeof(1) AS a, typeof(1.0) AS b, typeof('1') AS c, typeof(NULL) AS d, typeof(x'01') AS e;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Five storage classes: integer, real, text, blob, null
  • typeof reports the value's class
  • Column affinity can convert on insert

Common mistakes

  • Assuming a column's declared type guarantees each value's type in SQLite

Follow-ups

  • What does typeof return after inserting '1' into an INTEGER column?
  • How would you find mixed types in a column?

Tips

  • Name the five storage classes