Database Tables and Keys · Lesson 10 of 112

Database Data Types

What you will learn

  • Why columns have data types
  • The common types: integer, decimal, text, date and time, true/false
  • How SQLite handles types (it is more relaxed than most systems)
  • How to store money and dates safely
  • How a STRICT table enforces types

This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). Some examples create small tables of their own in your browser's copy; run them from top to bottom, and press Reset data to start again.

1. Why types?

A type tells the database what kind of value a column holds. That lets it check values, compare them correctly (the number 9 is less than 10, but the text "9" comes after "10") and use the right amount of space.

Kind of value Typical type name Example
whole number INTEGER 25
number with a fraction REAL / FLOAT / DECIMAL 12.5
text TEXT / VARCHAR "Rina"
date and time DATE, TIMESTAMP 2026-03-05
true or false BOOLEAN true

Type names differ between systems. The ideas are the same everywhere. Check your own system's documentation for the exact list.

2. How SQLite stores types

SQLite is unusual: the type is attached to each value, not strictly to the column. The function typeof() tells you what SQLite stored. First on real columns of the sample database:

SELECT name, typeof(name), price, typeof(price), stock, typeof(stock) FROM products ORDER BY product_id LIMIT 3;
name              typeof(name)  price  typeof(price)  stock  typeof(stock)
----------------  ------------  -----  -------------  -----  -------------
Steel pan         text            6.6  real               0  integer
Ceramic mug       text           44.1  real             150  integer
Wooden spoon set  text           29.5  real               0  integer
(3 rows)
SELECT account_id, typeof(account_id), account_type, typeof(account_type), balance_cents, typeof(balance_cents) FROM accounts ORDER BY account_id LIMIT 3;
account_id  typeof(account_id)  account_type  typeof(account_type)  balance_cents  typeof(balance_cents)
----------  ------------------  ------------  --------------------  -------------  ---------------------
         1  integer             checking      text                         192400  integer
         2  integer             savings       text                          52078  integer
         3  integer             savings       text                          62780  integer
(3 rows)
SELECT title, typeof(title), credits, typeof(credits), course_id, typeof(course_id) FROM courses ORDER BY course_id LIMIT 3;
title                   typeof(title)  credits  typeof(credits)  course_id  typeof(course_id)
----------------------  -------------  -------  ---------------  ---------  -----------------
Foundations of Algebra  text                 4  integer                  1  integer
Geometry                text                 3  integer                  2  integer
Statistics              text                 4  integer                  3  integer
(3 rows)

Now a table where we put the "wrong" kind of value into each column on purpose:

CREATE TABLE stock_counts (product_id INTEGER, label TEXT);
INSERT INTO stock_counts VALUES (42, 'bin A');
INSERT INTO stock_counts VALUES ('42', 99);
INSERT INTO stock_counts VALUES ('forty-two', 3.5);
SELECT product_id, typeof(product_id), label, typeof(label) FROM stock_counts;
product_id  typeof(product_id)  label  typeof(label)
----------  ------------------  -----  -------------
42          integer             bin A  text
42          integer             99     text
forty-two   text                3.5    text
(3 rows)
CREATE TABLE limit_requests (account_id INTEGER, note TEXT);
INSERT INTO limit_requests VALUES (42, 'urgent');
INSERT INTO limit_requests VALUES ('42', 99);
INSERT INTO limit_requests VALUES ('forty-two', 3.5);
SELECT account_id, typeof(account_id), note, typeof(note) FROM limit_requests;
account_id  typeof(account_id)  note    typeof(note)
----------  ------------------  ------  ------------
42          integer             urgent  text
42          integer             99      text
forty-two   text                3.5     text
(3 rows)
CREATE TABLE exam_notes (student_id INTEGER, comment TEXT);
INSERT INTO exam_notes VALUES (42, 'late');
INSERT INTO exam_notes VALUES ('42', 99);
INSERT INTO exam_notes VALUES ('forty-two', 3.5);
SELECT student_id, typeof(student_id), comment, typeof(comment) FROM exam_notes;
student_id  typeof(student_id)  comment  typeof(comment)
----------  ------------------  -------  ---------------
42          integer             late     text
42          integer             99       text
forty-two   text                3.5      text
(3 rows)

Read the three rows:

  • Row 1: as expected.
  • Row 2: the text '42' in an INTEGER column was converted to the integer 42, and the number 99 in a TEXT column became the text '99'. SQLite tries to convert values into the column's type (its "affinity").
  • Row 3: 'forty-two' cannot be converted, so SQLite simply stored it as text in an INTEGER column, without complaint.

This flexibility is a SQLite feature; other systems may be stricter, so read your system's documentation. When you design for any database, pick the right type and keep to it, even where SQLite would let you slip.

3. A STRICT table

SQLite (version 3.37 and later; the browser's SQLite is 3.39) lets you ask for strict checking with STRICT. The refused inserts are meant to fail:

CREATE TABLE stock_counts_strict (product_id INTEGER, label TEXT) STRICT;
INSERT INTO stock_counts_strict VALUES (42, 'bin A');
(1 row changed)
INSERT INTO stock_counts_strict VALUES ('forty-two', 'x');
IntegrityError: cannot store TEXT value in INTEGER column stock_counts_strict.product_id
INSERT INTO stock_counts_strict VALUES (7, 99);
SELECT product_id, label, typeof(label) FROM stock_counts_strict ORDER BY product_id;
product_id  label  typeof(label)
----------  -----  -------------
         7  99     text
        42  bin A  text
(2 rows)
CREATE TABLE limit_requests_strict (account_id INTEGER, note TEXT) STRICT;
INSERT INTO limit_requests_strict VALUES (42, 'urgent');
(1 row changed)
INSERT INTO limit_requests_strict VALUES ('forty-two', 'x');
IntegrityError: cannot store TEXT value in INTEGER column limit_requests_strict.account_id
INSERT INTO limit_requests_strict VALUES (7, 99);
SELECT account_id, note, typeof(note) FROM limit_requests_strict ORDER BY account_id;
account_id  note    typeof(note)
----------  ------  ------------
         7  99      text
        42  urgent  text
(2 rows)
CREATE TABLE exam_notes_strict (student_id INTEGER, comment TEXT) STRICT;
INSERT INTO exam_notes_strict VALUES (42, 'late');
(1 row changed)
INSERT INTO exam_notes_strict VALUES ('forty-two', 'x');
IntegrityError: cannot store TEXT value in INTEGER column exam_notes_strict.student_id
INSERT INTO exam_notes_strict VALUES (7, 99);
SELECT student_id, comment, typeof(comment) FROM exam_notes_strict ORDER BY student_id;
student_id  comment  typeof(comment)
----------  -------  ---------------
         7  99       text
        42  late     text
(2 rows)

The text 'forty-two' is refused for the INTEGER column. The number 99 in the TEXT column was accepted and stored as text (the conversion is allowed because it loses nothing). Use STRICT for new SQLite tables when you can.

4. Numbers: whole, fractional and money

Computers store fractions in binary, which cannot represent some decimal fractions exactly:

SELECT 0.1 + 0.2 AS sum;
SELECT 0.1 + 0.2 = 0.3 AS equal;
                sum
-------------------
0.30000000000000004
(1 row)

equal
-----
    0
(1 row)
SELECT 0.1 + 0.2 AS sum;
SELECT 0.1 + 0.2 = 0.3 AS equal;
                sum
-------------------
0.30000000000000004
(1 row)

equal
-----
    0
(1 row)
SELECT 0.1 + 0.2 AS sum;
SELECT 0.1 + 0.2 = 0.3 AS equal;
                sum
-------------------
0.30000000000000004
(1 row)

equal
-----
    0
(1 row)

The result is not exactly 0.3, and the comparison gives 0 (false). This is the same float problem you may know from Python. For money, the safe habit is to store whole units of the smallest coin: cents as an INTEGER.

CREATE TABLE price_list (item TEXT, cents INTEGER);
INSERT INTO price_list VALUES ('pen', 1050), ('book', 12075), ('bag', 25000);
SELECT SUM(cents) AS total_cents, SUM(cents) / 100 AS whole_units, SUM(cents) % 100 AS cents_left FROM price_list;
total_cents  whole_units  cents_left
-----------  -----------  ----------
      38125          381          25
(1 row)

The bank's own table stores every balance in cents:

SELECT SUM(balance_cents) AS total_cents, SUM(balance_cents) / 100 AS whole_units, SUM(balance_cents) % 100 AS cents_left FROM accounts;
total_cents  whole_units  cents_left
-----------  -----------  ----------
   62199130       621991          30
(1 row)
CREATE TABLE fee_list (item TEXT, cents INTEGER);
INSERT INTO fee_list VALUES ('trip', 1050), ('uniform', 12075), ('books', 25000);
SELECT SUM(cents) AS total_cents, SUM(cents) / 100 AS whole_units, SUM(cents) % 100 AS cents_left FROM fee_list;
total_cents  whole_units  cents_left
-----------  -----------  ----------
      38125          381          25
(1 row)

Dividing whole numbers gives a whole number, so / 100 gives the whole units and % 100 the cents left over. Some systems offer an exact DECIMAL/NUMERIC type for money; SQLite does not store decimals exactly, so integers of the smallest unit are the habit to learn. (The Shop table keeps prices as decimal numbers such as 12.5 to keep early lessons readable; a real shop should store cents.)

5. Dates and times

SQLite has no separate date type. The common habit is to store a date as text in the form YYYY-MM-DD (year first). Then alphabetical order is also date order, and SQLite's date functions understand it:

SELECT order_id, order_date FROM orders ORDER BY order_date, order_id LIMIT 3;
SELECT date('2026-03-05', '+30 days') AS thirty_days_later;
SELECT COUNT(*) AS orders_in_february FROM orders WHERE order_date BETWEEN '2026-02-01' AND '2026-02-28';
order_id  order_date
--------  ----------
    2021  2024-01-01
     786  2024-01-03
    1672  2024-01-03
(3 rows)

thirty_days_later
-----------------
2026-04-04
(1 row)

orders_in_february
------------------
               123
(1 row)
SELECT txn_id, txn_date FROM transactions ORDER BY txn_date, txn_id LIMIT 3;
SELECT date('2026-03-05', '+30 days') AS thirty_days_later;
SELECT COUNT(*) AS entries_in_february FROM transactions WHERE txn_date BETWEEN '2026-02-01' AND '2026-02-28';
txn_id  txn_date
------  ----------
     1  2018-02-23
     2  2018-02-23
     3  2018-03-07
(3 rows)

thirty_days_later
-----------------
2026-04-04
(1 row)

entries_in_february
-------------------
                153
(1 row)
SELECT assignment_id, due_date FROM assignments ORDER BY due_date, assignment_id LIMIT 3;
SELECT date('2026-03-05', '+30 days') AS thirty_days_later;
SELECT COUNT(*) AS due_in_march FROM assignments WHERE due_date BETWEEN '2026-03-01' AND '2026-03-31';
assignment_id  due_date
-------------  ----------
           20  2025-02-17
           59  2025-02-20
           28  2025-02-24
(3 rows)

thirty_days_later
-----------------
2026-04-04
(1 row)

due_in_march
------------
          18
(1 row)

Never store dates as 05/03/2026: is it 5 March or 3 May? And it sorts wrongly. YYYY-MM-DD is unambiguous.

6. True or false

SQLite has no boolean type: true is stored as 1 and false as 0.

The is_active column of products is such a flag:

SELECT product_id, name, is_active FROM products WHERE is_active = 0 ORDER BY product_id;
product_id  name            is_active
----------  --------------  ---------
        17  Desk organiser          0
        34  Skipping rope           0
(2 rows)
CREATE TABLE alerts (message TEXT, resolved INTEGER);
INSERT INTO alerts VALUES ('card used abroad', 1), ('large transfer', 0), ('new device', 0);
SELECT message FROM alerts WHERE resolved = 0;
message
--------------
large transfer
new device
(2 rows)
CREATE TABLE chores (title TEXT, done INTEGER);
INSERT INTO chores VALUES ('wash boards', 1), ('count chairs', 0), ('water plants', 0);
SELECT title FROM chores WHERE done = 0;
title
------------
count chairs
water plants
(2 rows)

Worked example: choose the types for a table of members

Members of the shop's loyalty club:

Column Value Type Why
member_id 17 INTEGER whole number
name "Rina" TEXT words
phone "01712345678" TEXT not arithmetic, and a leading 0 must be kept
joined "2026-03-05" TEXT (YYYY-MM-DD) sortable date
credit_cents 50000 INTEGER money in the smallest unit
active 1 INTEGER (0 or 1) true or false
CREATE TABLE loyalty_members (member_id INTEGER, name TEXT, phone TEXT, joined TEXT, credit_cents INTEGER, active INTEGER);
INSERT INTO loyalty_members VALUES (17, 'Rina', '01712345678', '2026-03-05', 50000, 1);
SELECT phone, typeof(phone), credit_cents, typeof(credit_cents) FROM loyalty_members;
phone        typeof(phone)  credit_cents  typeof(credit_cents)
-----------  -------------  ------------  --------------------
01712345678  text                  50000  integer
(1 row)

Payees a customer can send money to:

Column Value Type Why
payee_id 17 INTEGER whole number
name "Rina" TEXT words
phone "01712345678" TEXT not arithmetic, and a leading 0 must be kept
added_on "2026-03-05" TEXT (YYYY-MM-DD) sortable date
limit_cents 50000 INTEGER money in the smallest unit
verified 1 INTEGER (0 or 1) true or false
CREATE TABLE payees (payee_id INTEGER, name TEXT, phone TEXT, added_on TEXT, limit_cents INTEGER, verified INTEGER);
INSERT INTO payees VALUES (17, 'Rina', '01712345678', '2026-03-05', 50000, 1);
SELECT phone, typeof(phone), limit_cents, typeof(limit_cents) FROM payees;
phone        typeof(phone)  limit_cents  typeof(limit_cents)
-----------  -------------  -----------  -------------------
01712345678  text                 50000  integer
(1 row)

Members of the school clubs:

Column Value Type Why
member_id 17 INTEGER whole number
name "Rina" TEXT words
phone "01712345678" TEXT not arithmetic, and a leading 0 must be kept
joined "2026-03-05" TEXT (YYYY-MM-DD) sortable date
fee_cents 50000 INTEGER money in the smallest unit
active 1 INTEGER (0 or 1) true or false
CREATE TABLE club_members (member_id INTEGER, name TEXT, phone TEXT, joined TEXT, fee_cents INTEGER, active INTEGER);
INSERT INTO club_members VALUES (17, 'Rina', '01712345678', '2026-03-05', 50000, 1);
SELECT phone, typeof(phone), fee_cents, typeof(fee_cents) FROM club_members;
phone        typeof(phone)  fee_cents  typeof(fee_cents)
-----------  -------------  ---------  -----------------
01712345678  text               50000  integer
(1 row)

A phone number looks like a number but is not one: you never add two phone numbers, and an INTEGER would drop the leading zero. Rule: if you would not do arithmetic on it, it is probably text. The member is made up.

Common mistakes

  • Phone numbers or postcodes as integers (leading zeros are lost).
  • Money as a fraction type. Use whole smallest units, or an exact decimal type where available.
  • Dates in local formats (05/03/2026). Use YYYY-MM-DD.
  • Trusting SQLite to reject wrong types. It converts or accepts them unless the table is STRICT.

Key takeaways

  • A data type tells the database how to check, compare and store a column's values.
  • Common kinds: integer, decimal, text, date/time, true/false; names differ by system.
  • SQLite is flexible about types; STRICT tables make it check them.
  • Store money as integers of the smallest unit; store dates as YYYY-MM-DD.
  • Identifiers like phone numbers are text, not numbers.

Practice

1. Which type would you use for a student's roll number such as 0045?

Show answer

Text, because the leading zeros are part of the value and you never do arithmetic on it.

2. Why store a price as 12075 cents instead of 120.75?

Show answer

Whole numbers are exact, while binary fractions can give results like 0.1 + 0.2 not equal to 0.3.

3. What does typeof(x) do in SQLite?

Show answer

It reports the storage type of the value actually stored (for example integer, text or real).

4. Write the date 5 March 2026 in the form recommended for storing dates.

Show answer

2026-03-05

5. What does STRICT change about a SQLite table?

Show answer

SQLite refuses values that cannot be stored as the column's declared type (such as 'forty-two' in an INTEGER column), instead of storing them anyway.

6. How does SQLite store true and false?

Show answer

As the integers 1 and 0.