Creating Tables and Constraints · Lesson 42 of 64

SQL Data Types

What you will learn

  • The five storage classes of SQLite
  • What type affinity does to the values you insert
  • How STRICT tables enforce types
  • How to choose a type for a column

This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). The tables you create exist only in your browser's copy of the data; Reset data removes them. Run the cells from top to bottom.

1. Five kinds of value

Every value stored in SQLite is one of five kinds, called storage classes: NULL, INTEGER (whole number), REAL (decimal), TEXT and BLOB (raw bytes). TYPEOF tells you which (lesson 1.6):

SELECT TYPEOF(NULL) AS a, TYPEOF(42) AS b, TYPEOF(4.2) AS c, TYPEOF('forty-two') AS d, TYPEOF(X'2A') AS e;
a     b        c     d     e
----  -------  ----  ----  ----
null  integer  real  text  blob
(1 row)
SELECT TYPEOF(NULL) AS a, TYPEOF(42) AS b, TYPEOF(4.2) AS c, TYPEOF('forty-two') AS d, TYPEOF(X'2A') AS e;
a     b        c     d     e
----  -------  ----  ----  ----
null  integer  real  text  blob
(1 row)
SELECT TYPEOF(NULL) AS a, TYPEOF(42) AS b, TYPEOF(4.2) AS c, TYPEOF('forty-two') AS d, TYPEOF(X'2A') AS e;
a     b        c     d     e
----  -------  ----  ----  ----
null  integer  real  text  blob
(1 row)

(X'2A' is a BLOB written in hexadecimal.) Dates have no storage class of their own: they are stored as TEXT (or numbers), lesson 1.7.

2. Type affinity

A column has a declared type, such as INTEGER or TEXT. SQLite turns the declared type into an affinity, a preference for how to store what you insert. According to the SQLite documentation the rules are applied in order: a declared type containing INT gives integer affinity; containing CHAR, CLOB or TEXT gives text affinity; BLOB or no type gives blob affinity; REAL, FLOA or DOUB gives real affinity; anything else gives numeric affinity. The affinity is a preference, not a rule:

CREATE TABLE lib_types (i INTEGER, t TEXT, r REAL, n NUMERIC);
INSERT INTO lib_types VALUES ('42', 42, 42, '42');
SELECT TYPEOF(i) AS i, TYPEOF(t) AS t, TYPEOF(r) AS r, TYPEOF(n) AS n FROM lib_types;
i        t     r     n
-------  ----  ----  -------
integer  text  real  integer
(1 row)
CREATE TABLE lib_types (i INTEGER, t TEXT, r REAL, n NUMERIC);
INSERT INTO lib_types VALUES ('42', 42, 42, '42');
SELECT TYPEOF(i) AS i, TYPEOF(t) AS t, TYPEOF(r) AS r, TYPEOF(n) AS n FROM lib_types;
i        t     r     n
-------  ----  ----  -------
integer  text  real  integer
(1 row)
CREATE TABLE lib_types (i INTEGER, t TEXT, r REAL, n NUMERIC);
INSERT INTO lib_types VALUES ('42', 42, 42, '42');
SELECT TYPEOF(i) AS i, TYPEOF(t) AS t, TYPEOF(r) AS r, TYPEOF(n) AS n FROM lib_types;
i        t     r     n
-------  ----  ----  -------
integer  text  real  integer
(1 row)

The text '42' in the integer column became the integer 42. The number 42 in the text column became the text '42'. The 42 in the real column became 42.0. The values were converted to match the affinity when that was possible without losing information.

3. When a value does not fit

A normal SQLite table does not refuse a value of the wrong kind. If conversion is impossible, it stores the value as it is:

INSERT INTO lib_types (i) VALUES ('not a number');
SELECT i, TYPEOF(i) AS type FROM lib_types WHERE rowid = 2;
i             type
------------  ----
not a number  text
(1 row)
INSERT INTO lib_types (i) VALUES ('not a number');
SELECT i, TYPEOF(i) AS type FROM lib_types WHERE rowid = 2;
i             type
------------  ----
not a number  text
(1 row)
INSERT INTO lib_types (i) VALUES ('not a number');
SELECT i, TYPEOF(i) AS type FROM lib_types WHERE rowid = 2;
i             type
------------  ----
not a number  text
(1 row)

The integer column now holds text. SQLite is flexible about types; most other databases are strict, and refuse the insert. Do not rely on the flexibility: choose the right type and check your values (a CHECK rule, lesson 6.4, can do it).

4. STRICT tables

Add STRICT after the closing bracket to make SQLite enforce the declared types (SQLite 3.37 and later):

CREATE TABLE lib_strict (id INTEGER PRIMARY KEY, qty INTEGER NOT NULL, label TEXT) STRICT;
INSERT INTO lib_strict (qty, label) VALUES ('7', 'ok');
SELECT qty, TYPEOF(qty) AS type FROM lib_strict;
qty  type
---  -------
  7  integer
(1 row)

A text that cannot become a number is refused:

INSERT INTO lib_strict (qty, label) VALUES ('seven', 'bad');
IntegrityError: cannot store TEXT value in INTEGER column lib_strict.qty
CREATE TABLE lib_strict (id INTEGER PRIMARY KEY, qty INTEGER NOT NULL, label TEXT) STRICT;
INSERT INTO lib_strict (qty, label) VALUES ('7', 'ok');
SELECT qty, TYPEOF(qty) AS type FROM lib_strict;
qty  type
---  -------
  7  integer
(1 row)

A text that cannot become a number is refused:

INSERT INTO lib_strict (qty, label) VALUES ('seven', 'bad');
IntegrityError: cannot store TEXT value in INTEGER column lib_strict.qty
CREATE TABLE lib_strict (id INTEGER PRIMARY KEY, qty INTEGER NOT NULL, label TEXT) STRICT;
INSERT INTO lib_strict (qty, label) VALUES ('7', 'ok');
SELECT qty, TYPEOF(qty) AS type FROM lib_strict;
qty  type
---  -------
  7  integer
(1 row)

A text that cannot become a number is refused:

INSERT INTO lib_strict (qty, label) VALUES ('seven', 'bad');
IntegrityError: cannot store TEXT value in INTEGER column lib_strict.qty

The text '7' was converted to the integer 7, but 'seven' was refused. A strict table behaves more like other databases. Allowed types in a strict table are INT, INTEGER, REAL, TEXT, BLOB and ANY.

5. Choosing a type

Data Suggested type Why
a count, a year, an id INTEGER exact whole numbers
money INTEGER in the smallest unit (cents) exact; no rounding errors (lesson 1.6)
a measurement REAL decimals; tiny errors are normal
names, descriptions, codes TEXT words
a date or time TEXT in YYYY-MM-DD form sorts and compares correctly (lesson 1.7)
a yes/no flag INTEGER with a CHECK (x IN (0, 1)) SQLite has no boolean type
a phone number, a postcode TEXT leading zeros and plus signs matter; you never add them
a file or image BLOB raw bytes

The Shop stores money as a decimal number (REAL) to keep early lessons simple, and flags as INTEGER with a check:

SELECT name, type FROM pragma_table_info('products') WHERE name IN ('price', 'stock', 'is_active', 'name');
name       type
---------  -------
name       TEXT
price      REAL
stock      INTEGER
is_active  INTEGER
(4 rows)

The Bank stores money in whole cents (INTEGER), as recommended here:

SELECT name, type FROM pragma_table_info('accounts') WHERE name IN ('balance_cents', 'status', 'opened_on');
name           type
-------------  -------
opened_on      TEXT
status         TEXT
balance_cents  INTEGER
(3 rows)

The School stores a grade as a decimal number and dates as text:

SELECT name, type FROM pragma_table_info('enrollments');
name         type
-----------  -------
student_id   INTEGER
section_id   INTEGER
enrolled_on  TEXT
grade        REAL
(4 rows)

In other databases. Many databases have richer types (a real date type, DECIMAL/NUMERIC with exact digits, booleans) and enforce them. The ideas of this lesson (choose the narrowest suitable type, store money exactly, keep dates in one form) apply everywhere; the type names differ. Check the documentation of the one you use.

Worked example: choose the types

A table of customer orders needs: an order number, the customer's name, the order date, the amount with cents, whether it was paid.

Column Type Note
order_no INTEGER PRIMARY KEY numbers itself
customer TEXT NOT NULL
ordered_on TEXT NOT NULL YYYY-MM-DD
amount_cents INTEGER NOT NULL 1250 means 12.50
paid INTEGER NOT NULL DEFAULT 0 CHECK (paid IN (0, 1)) a flag

The table is made up.

Common mistakes

  • Trusting the declared type to refuse bad values in a normal SQLite table.
  • Storing money as REAL when exactness matters.
  • Storing phone numbers or codes as numbers, losing leading zeros.
  • Storing dates in another text form.
  • Assuming other databases are as relaxed as SQLite.

Key takeaways

  • SQLite has five storage classes: NULL, INTEGER, REAL, TEXT, BLOB.
  • A column's declared type sets an affinity: values are converted when possible but not refused.
  • STRICT tables enforce the declared types.
  • Choose INTEGER cents for money, TEXT YYYY-MM-DD for dates, TEXT for codes and phone numbers.

Practice

1. What does TYPEOF(3.0) return?

Show answer

real.

2. What happens when you insert '42' into an INTEGER column of a normal table?

Show answer

It is converted to the integer 42.

3. What happens when you insert 'abc' into an INTEGER column of a normal table?

Show answer

It is stored as text, with no error.

4. How do you make SQLite refuse the wrong type?

Show answer

Create the table with STRICT (SQLite 3.37 and later).

5. Which type do you use for money?

Show answer

INTEGER holding the smallest unit (cents), so the amounts are exact.

6. Why is a phone number TEXT?

Show answer

Leading zeros and plus signs matter and you never calculate with it.