Database Programming Features · Lesson 84 of 112

Database Generated Columns and Sequences

What you will learn

  • What a generated column is, and the virtual and stored kinds
  • How to index a generated column and use it to enforce a rule
  • What a sequence is
  • How SQLite numbers rows: INTEGER PRIMARY KEY and AUTOINCREMENT
  • How to build gap-free numbers yourself

1. Generated columns

A generated column is a column whose value the database calculates from other columns in the same row. You never write to it. The PostgreSQL documentation describes it as always computed from other columns, "for columns what a view is for tables", and names two kinds: stored (computed when the row is written and kept on disk) and virtual (computed when read, taking no storage). SQLite supports both.

This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). It adds columns and small tables of its own to your browser's copy; run the examples from top to bottom, and Reset data starts again.

CREATE TABLE lines (
    id INTEGER PRIMARY KEY,
    price INTEGER NOT NULL,
    qty INTEGER NOT NULL,
    total INTEGER GENERATED ALWAYS AS (price * qty) VIRTUAL,
    total_stored INTEGER GENERATED ALWAYS AS (price * qty) STORED
);
INSERT INTO lines (price, qty) VALUES (120, 3), (80, 5);
SELECT id, price, qty, total, total_stored FROM lines ORDER BY id;
id  price  qty  total  total_stored
--  -----  ---  -----  ------------
 1    120    3    360           360
 2     80    5    400           400
(2 rows)
UPDATE lines SET qty = 10 WHERE id = 1;
SELECT id, total, total_stored FROM lines ORDER BY id;
id  total  total_stored
--  -----  ------------
 1   1200          1200
 2    400           400
(2 rows)
CREATE TABLE lines (
    id INTEGER PRIMARY KEY,
    price INTEGER NOT NULL,
    qty INTEGER NOT NULL,
    total INTEGER GENERATED ALWAYS AS (price * qty) VIRTUAL,
    total_stored INTEGER GENERATED ALWAYS AS (price * qty) STORED
);
INSERT INTO lines (price, qty) VALUES (120, 3), (80, 5);
SELECT id, price, qty, total, total_stored FROM lines ORDER BY id;
id  price  qty  total  total_stored
--  -----  ---  -----  ------------
 1    120    3    360           360
 2     80    5    400           400
(2 rows)
UPDATE lines SET qty = 10 WHERE id = 1;
SELECT id, total, total_stored FROM lines ORDER BY id;
id  total  total_stored
--  -----  ------------
 1   1200          1200
 2    400           400
(2 rows)
CREATE TABLE lines (
    id INTEGER PRIMARY KEY,
    price INTEGER NOT NULL,
    qty INTEGER NOT NULL,
    total INTEGER GENERATED ALWAYS AS (price * qty) VIRTUAL,
    total_stored INTEGER GENERATED ALWAYS AS (price * qty) STORED
);
INSERT INTO lines (price, qty) VALUES (120, 3), (80, 5);
SELECT id, price, qty, total, total_stored FROM lines ORDER BY id;
id  price  qty  total  total_stored
--  -----  ---  -----  ------------
 1    120    3    360           360
 2     80    5    400           400
(2 rows)
UPDATE lines SET qty = 10 WHERE id = 1;
SELECT id, total, total_stored FROM lines ORDER BY id;
id  total  total_stored
--  -----  ------------
 1   1200          1200
 2    400           400
(2 rows)

Both columns equal price * qty, and both followed the change when qty became 10. You cannot write to them:

UPDATE lines SET total = 5 WHERE id = 1;
OperationalError: cannot UPDATE generated column "total"
UPDATE lines SET total = 5 WHERE id = 1;
OperationalError: cannot UPDATE generated column "total"
UPDATE lines SET total = 5 WHERE id = 1;
OperationalError: cannot UPDATE generated column "total"

A generated column can also be added to a real table (only a VIRTUAL one can be added to a table that already exists):

ALTER TABLE order_items ADD COLUMN line_total REAL GENERATED ALWAYS AS (ROUND(quantity * unit_price, 2)) VIRTUAL;
SELECT order_id, line_no, quantity, unit_price, line_total FROM order_items ORDER BY order_id, line_no LIMIT 3;
order_id  line_no  quantity  unit_price  line_total
--------  -------  --------  ----------  ----------
       1        1         1        29.5        29.5
       1        2         1        21.6        21.6
       1        3         1        24.0        24.0
(3 rows)
ALTER TABLE transactions ADD COLUMN signed_cents INTEGER GENERATED ALWAYS AS
  (CASE WHEN kind IN ('deposit', 'transfer_in', 'interest') THEN amount_cents ELSE -amount_cents END) VIRTUAL;
SELECT txn_id, kind, amount_cents, signed_cents FROM transactions ORDER BY txn_id LIMIT 4;
txn_id  kind        amount_cents  signed_cents
------  ----------  ------------  ------------
     1  deposit            54800         54800
     2  deposit            53200         53200
     3  deposit            76000         76000
     4  withdrawal         23900        -23900
(4 rows)
ALTER TABLE students ADD COLUMN full_name TEXT GENERATED ALWAYS AS (first_name || ' ' || last_name) VIRTUAL;
SELECT student_id, full_name FROM students ORDER BY student_id LIMIT 3;
student_id  full_name
----------  ------------
         1  Vera Khan
         2  Elena Haque
         3  Chloe Garcia
(3 rows)
Kind Stored on disk? Cost
Virtual no calculated every time it is read
Stored yes uses space, calculated once when the row is written

The big benefit is that the total can never disagree with price and quantity. If you stored total as a normal column, a buggy program could save a wrong total (lesson 5.1 on repeated data).

2. Index a generated column

A generated column can be indexed like any other (lesson 7.3), which turns an expensive calculation into a fast lookup:

CREATE INDEX idx_total ON lines (total);
EXPLAIN QUERY PLAN SELECT id FROM lines WHERE total > 500;
plan
--------------------------------------------
SEARCH lines USING INDEX idx_total (total>?)
(1 row)
CREATE INDEX idx_total ON lines (total);
EXPLAIN QUERY PLAN SELECT id FROM lines WHERE total > 500;
plan
--------------------------------------------
SEARCH lines USING INDEX idx_total (total>?)
(1 row)
CREATE INDEX idx_total ON lines (total);
EXPLAIN QUERY PLAN SELECT id FROM lines WHERE total > 500;
plan
--------------------------------------------
SEARCH lines USING INDEX idx_total (total>?)
(1 row)

It is also a neat way to enforce a rule such as "emails are unique, ignoring capitals":

CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT, email_lc TEXT GENERATED ALWAYS AS (lower(email)) STORED);
CREATE UNIQUE INDEX idx_email_lc ON users (email_lc);
INSERT INTO users (email) VALUES ('Rina@Example.com');
(1 row changed)
INSERT INTO users (email) VALUES ('RINA@example.com');
IntegrityError: UNIQUE constraint failed: users.email_lc
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT, email_lc TEXT GENERATED ALWAYS AS (lower(email)) STORED);
CREATE UNIQUE INDEX idx_email_lc ON users (email_lc);
INSERT INTO users (email) VALUES ('Rina@Example.com');
(1 row changed)
INSERT INTO users (email) VALUES ('RINA@example.com');
IntegrityError: UNIQUE constraint failed: users.email_lc
CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT, email_lc TEXT GENERATED ALWAYS AS (lower(email)) STORED);
CREATE UNIQUE INDEX idx_email_lc ON users (email_lc);
INSERT INTO users (email) VALUES ('Rina@Example.com');
(1 row changed)
INSERT INTO users (email) VALUES ('RINA@example.com');
IntegrityError: UNIQUE constraint failed: users.email_lc

The two spellings differ in capitals, yet the unique index on the lower-case copy refused the second one (a cure for the Dhaka / dhaka problem from lesson 1.1).

Quick check: why can't you UPDATE a generated column?

Its value is defined by the formula. Allowing a direct write would let it disagree with the columns it comes from.

3. Sequences

A sequence is a source of numbers that only goes up, used to give rows unique ids. The PostgreSQL documentation describes CREATE SEQUENCE as creating a new sequence number generator. SQLite does not have separate sequence objects. It numbers rows in two ways:

CREATE TABLE t1 (id INTEGER PRIMARY KEY, v TEXT);
CREATE TABLE t2 (id INTEGER PRIMARY KEY AUTOINCREMENT, v TEXT);
INSERT INTO t1 (v) VALUES ('a'), ('b'), ('c');
INSERT INTO t2 (v) VALUES ('a'), ('b'), ('c');
DELETE FROM t1 WHERE id = 3;
DELETE FROM t2 WHERE id = 3;
INSERT INTO t1 (v) VALUES ('d');
INSERT INTO t2 (v) VALUES ('d');
SELECT id, v FROM t1 ORDER BY id;
SELECT id, v FROM t2 ORDER BY id;
SELECT * FROM sqlite_sequence;
id  v
--  -
 1  a
 2  b
 3  d
(3 rows)

id  v
--  -
 1  a
 2  b
 4  d
(3 rows)

name  seq
----  ---
t2      4
(1 row)
CREATE TABLE t1 (id INTEGER PRIMARY KEY, v TEXT);
CREATE TABLE t2 (id INTEGER PRIMARY KEY AUTOINCREMENT, v TEXT);
INSERT INTO t1 (v) VALUES ('a'), ('b'), ('c');
INSERT INTO t2 (v) VALUES ('a'), ('b'), ('c');
DELETE FROM t1 WHERE id = 3;
DELETE FROM t2 WHERE id = 3;
INSERT INTO t1 (v) VALUES ('d');
INSERT INTO t2 (v) VALUES ('d');
SELECT id, v FROM t1 ORDER BY id;
SELECT id, v FROM t2 ORDER BY id;
SELECT * FROM sqlite_sequence;
id  v
--  -
 1  a
 2  b
 3  d
(3 rows)

id  v
--  -
 1  a
 2  b
 4  d
(3 rows)

name  seq
----  ---
t2      4
(1 row)
CREATE TABLE t1 (id INTEGER PRIMARY KEY, v TEXT);
CREATE TABLE t2 (id INTEGER PRIMARY KEY AUTOINCREMENT, v TEXT);
INSERT INTO t1 (v) VALUES ('a'), ('b'), ('c');
INSERT INTO t2 (v) VALUES ('a'), ('b'), ('c');
DELETE FROM t1 WHERE id = 3;
DELETE FROM t2 WHERE id = 3;
INSERT INTO t1 (v) VALUES ('d');
INSERT INTO t2 (v) VALUES ('d');
SELECT id, v FROM t1 ORDER BY id;
SELECT id, v FROM t2 ORDER BY id;
SELECT * FROM sqlite_sequence;
id  v
--  -
 1  a
 2  b
 3  d
(3 rows)

id  v
--  -
 1  a
 2  b
 4  d
(3 rows)

name  seq
----  ---
t2      4
(1 row)
  • INTEGER PRIMARY KEY (table t1) picks the largest existing id plus one. After deleting the last row, the next row reused id 3.
  • AUTOINCREMENT (table t2) keeps a counter in a system table, sqlite_sequence, so an id is never reused. The new row got 4.

Notice also that t2 now has a gap: id 3 is missing. All sequences in all products behave like this in some situations. A sequence promises unique, increasing numbers, not numbers without holes (a rolled-back transaction can still use up a number). If you need unique ids, a gap does not matter. If the law says invoice numbers must have no gaps, a plain sequence is not enough.

4. Gap-free numbers with a counter table

A simple pattern for gap-free numbers is a counter table updated in the same transaction as the thing being numbered. Each of the three blocks below takes one number:

CREATE TABLE counters (name TEXT PRIMARY KEY, next_value INTEGER NOT NULL);
INSERT INTO counters VALUES ('invoice', 1001);
BEGIN;
UPDATE counters SET next_value = next_value + 1 WHERE name = 'invoice';
SELECT next_value - 1 AS number_issued FROM counters WHERE name = 'invoice';
COMMIT;
BEGIN;
UPDATE counters SET next_value = next_value + 1 WHERE name = 'invoice';
SELECT next_value - 1 AS number_issued FROM counters WHERE name = 'invoice';
COMMIT;
BEGIN;
UPDATE counters SET next_value = next_value + 1 WHERE name = 'invoice';
SELECT next_value - 1 AS number_issued FROM counters WHERE name = 'invoice';
COMMIT;
number_issued
-------------
         1001
(1 row)

number_issued
-------------
         1002
(1 row)

number_issued
-------------
         1003
(1 row)
CREATE TABLE counters (name TEXT PRIMARY KEY, next_value INTEGER NOT NULL);
INSERT INTO counters VALUES ('invoice', 1001);
BEGIN;
UPDATE counters SET next_value = next_value + 1 WHERE name = 'invoice';
SELECT next_value - 1 AS number_issued FROM counters WHERE name = 'invoice';
COMMIT;
BEGIN;
UPDATE counters SET next_value = next_value + 1 WHERE name = 'invoice';
SELECT next_value - 1 AS number_issued FROM counters WHERE name = 'invoice';
COMMIT;
BEGIN;
UPDATE counters SET next_value = next_value + 1 WHERE name = 'invoice';
SELECT next_value - 1 AS number_issued FROM counters WHERE name = 'invoice';
COMMIT;
number_issued
-------------
         1001
(1 row)

number_issued
-------------
         1002
(1 row)

number_issued
-------------
         1003
(1 row)
CREATE TABLE counters (name TEXT PRIMARY KEY, next_value INTEGER NOT NULL);
INSERT INTO counters VALUES ('invoice', 1001);
BEGIN;
UPDATE counters SET next_value = next_value + 1 WHERE name = 'invoice';
SELECT next_value - 1 AS number_issued FROM counters WHERE name = 'invoice';
COMMIT;
BEGIN;
UPDATE counters SET next_value = next_value + 1 WHERE name = 'invoice';
SELECT next_value - 1 AS number_issued FROM counters WHERE name = 'invoice';
COMMIT;
BEGIN;
UPDATE counters SET next_value = next_value + 1 WHERE name = 'invoice';
SELECT next_value - 1 AS number_issued FROM counters WHERE name = 'invoice';
COMMIT;
number_issued
-------------
         1001
(1 row)

number_issued
-------------
         1002
(1 row)

number_issued
-------------
         1003
(1 row)

If the transaction that uses the number rolls back, the counter rolls back too, so no number is lost. The price is that the counter row becomes a bottleneck: only one transaction at a time can update it (chapter 6), so gap-free numbering is slower than a plain sequence under heavy load.

Worked example: invoice numbers

A small business must issue invoices numbered 1, 2, 3 with no gaps. Options:

Option Unique? Gap-free? Fast under load?
AUTOINCREMENT id yes no (rollbacks and deletes can leave holes) yes
counter table in the same transaction yes yes no (one at a time)

Use AUTOINCREMENT (or a similar sequence) for the internal row id, and a counter table for the printed invoice number, since only that one has to be gap-free. The business is made up; always check the actual rule that applies to you.

Common mistakes

  • Writing a calculated value into a normal column that can drift from its parts.
  • Relying on a sequence for gap-free numbers.
  • Assuming deleted ids are never reused. In SQLite that is true only with AUTOINCREMENT.
  • Forgetting that a stored generated column uses disk space and a virtual one costs time on every read.

Key takeaways

  • A generated column is computed by the database from other columns and cannot be written directly.
  • Virtual is computed on read; stored is computed on write and takes space.
  • Generated columns can be indexed and used with unique indexes to enforce rules.
  • A sequence gives unique, increasing numbers, not gap-free ones.
  • In SQLite, INTEGER PRIMARY KEY may reuse ids; AUTOINCREMENT never does. A counter table gives gap-free numbers at the cost of speed.

Practice

1. What is the difference between a virtual and a stored generated column?

Show answer

Virtual: calculated each time it is read, no storage. Stored: calculated when the row is written and kept on disk.

2. Why is a generated total safer than a normal total column?

Show answer

It is always calculated from price and qty, so it cannot disagree with them.

3. Why did inserting 'RINA@example.com' fail after 'Rina@Example.com' was stored?

Show answer

The unique index on the generated lower-case column saw the same value rina@example.com twice.

4. After deleting the last row, t1 gave the next row id 3 and t2 gave 4. Why?

Show answer

INTEGER PRIMARY KEY uses the largest existing id plus one, so 3 was reused. AUTOINCREMENT remembers the highest id ever used in sqlite_sequence, so it never reuses one.

5. Does a sequence guarantee no gaps? Explain.

Show answer

No. It guarantees unique, increasing numbers. A rolled-back transaction or a deleted row can leave a hole.

6. Why is a counter table slower than a sequence when many users insert at once?

Show answer

Every transaction must update the same counter row, so they have to take turns.