SQLite Triggers, Views, and Generated Columns Cheatsheet

CREATE VIEW, CREATE TRIGGER, audit logging, derived values, generated columns, and automation patterns in SQLite.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all

Create reusable views

Package common joins and projections into named queries.

Create a view

Define a reusable read-only query projection.

sqlANYsqliteview
sql
CREATE VIEW recent_posts AS
SELECT p.id, p.title, u.email AS author_email, p.created_at
FROM posts p
JOIN users u ON u.id = p.user_id
WHERE p.created_at >= date('now', '-30 day');

Views are great for simplifying repeated report queries or exposing app-friendly shapes.

Query a view

Read from the named projection like a table.

sqlANYsqliteviewselect
sql
SELECT * FROM recent_posts ORDER BY created_at DESC LIMIT 20;

Useful for dashboards and administrative pages.

Triggers and generated values

Automate timestamps, audit rows, and derived fields.

Create an AFTER INSERT trigger

Write to an audit log when a row is created.

sqlANYsqlitetriggeraudit
sql
CREATE TRIGGER users_ai
AFTER INSERT ON users
BEGIN
  INSERT INTO audit_log(entity, entity_id, action)
  VALUES ('users', NEW.id, 'insert');
END;

A classic pattern for audit trails and event capture.

Touch updated_at from a trigger

Maintain a timestamp on row changes.

sqlANYsqlitetriggerupdated_at
sql
CREATE TRIGGER posts_au
AFTER UPDATE ON posts
BEGIN
  UPDATE posts
  SET updated_at = CURRENT_TIMESTAMP
  WHERE id = NEW.id;
END;

Be careful to avoid unintended recursive behavior depending on trigger design and settings.

Normalize data with a generated column

Compute a lowercased email for indexing or search.

sqlANYsqlitegenerated columnnormalization
sql
CREATE TABLE contacts (
  id INTEGER PRIMARY KEY,
  email TEXT NOT NULL,
  email_normalized TEXT GENERATED ALWAYS AS (lower(email)) STORED
);

Generated columns can simplify lookups and enforce repeatable derivations close to the data.

Index a generated column

Speed up queries over a derived value.

sqlANYsqliteindexgenerated column
sql
CREATE INDEX idx_contacts_email_normalized ON contacts(email_normalized);

High-value when the generated value is used frequently in filters or joins.

Recommended next

No recommendations yet.