The SQLite dialect of SQL is a dynamically-typed language. Just like Python will let you create an array of mixed types like [None, 42, 3.14, 'Hello, world!', b'\x01\x23'], SQLite will let you store values of multiple types in the same column.
Storage classes
Conceptually, SQLite has five scalar data types, called “storage classes”:
- The
NULL type is used for the singleton value NULL, which is a sentinel value indicating an unknown or not-applicable value.
- The
INTEGER type is a 64-bit signed integer. The part about “stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value” is an implementation detail of the file format, and not something you as a programmer need to be concerned with. From the point of view of the C API and the SQL language, it's always 8 bytes.
- The
REAL type is a 64-bit floating-point number.
- The
TEXT type is a character string.
- The
BLOB type is a sequence of octets. SQL literals are X-prefixed strings of hex digits (e.g., X'0123456789ABCDEF').
If you're a Python 3.x programmer, you can think of:
NULL = None (of type NoneType)
INTEGER = int (but limited to 64 bits)
REAL = float
TEXT = str
BLOB = bytes
(This is actually the type mapping used by Python's standard sqlite3 module.)
If you're a C# programmer, you can think of:
NULL = null (but without the arbitrary distinction between value types and reference types)
INTEGER = long
REAL = double
TEXT = string
BLOB = byte[]
SQLite lets you store a value of any data type in any column. (Exception: If a column is declared as INTEGER PRIMARY KEY, and its table is not declared WITHOUT ROWID, then it actually is constrained to contain only integers, because it is an alias for the row ID.)
Column type affinity
Independent of the above list of “storage classes”, SQLite has the concept of type affinity which determines the preferred data type to store in a column. The affinitity of a column is determine by its declared datatype.
Only numeric (INTEGER and REAL) and TEXT values are affected by these automatic type conversions; there is never any implicit conversion to or from the NULL or BLOB storage classes.
So, if you declare a column with integer affinity (e.g., INT or INTEGER), but you insert a text string into it, then SQLite will automatically convert the value to an integer for you. But if it can't, it leaves it as a string. So, the string '42' becomes the integer 42, but the string 'xyz' stays as-is.
Real-affinity columns (REAL, FLOAT, DOUBLE) are similar, except that they attempt to convert strings into REAL values instead of INTEGER values. Numeric-affinity columns (NUMERIC, DECIMAL) convert strings to numbers, but will happily allow INTEGER and REAL values in the same column.
Text-affinity columns (CHAR, VARCHAR, TEXT, CLOB) will make the opposite conversion: All numbers (integer or real) are converted to strings.
Blob-affinity columns (BLOB or no declared data type) leave all values as-is.