---
title: "Timestamps"
description: "created_at, updated_at, and auto-updating triggers for Postgres and SQLite."
---

> Documentation Index
> Fetch the complete documentation index at: https://codex.mirio.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Timestamps

`created_at` records when a row was inserted; `updated_at` records when it last
changed. Both belong on almost every table. `updated_at` requires a trigger to
stay current; without one it reflects insert time only and never changes.

## Postgres

```sql
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
```

Always use `TIMESTAMPTZ`, never `TIMESTAMP`. `TIMESTAMP` silently drops the timezone
offset; `TIMESTAMPTZ` stores UTC and converts on read. Mixing the two causes subtle
bugs when clients are in different timezones.

`DEFAULT now()` fires at insert time. Mark both columns `NOT NULL`; a row without a
creation time is always a bug.

### `updated_at` trigger

Define the trigger function once per database and wire it to every table that needs it:

```sql
CREATE FUNCTION set_updated_at()
RETURNS TRIGGER
LANGUAGE plpgsql AS $$
BEGIN
  NEW.updated_at = now();
  RETURN NEW;
END;
$$;

CREATE TRIGGER posts_set_updated_at
  BEFORE UPDATE ON posts
  FOR EACH ROW
  EXECUTE FUNCTION set_updated_at();
```

:::tip
`BEFORE UPDATE` is intentional. The trigger rewrites `NEW` before the row is written, so the
updated timestamp is stored atomically with the rest of the change.
:::

:::caution
`now()` returns the transaction start time, not wall-clock time. Two updates in the same
transaction get the same `updated_at`. This is usually correct (the logical change happened at one
point), but worth knowing.
:::

## SQLite

SQLite has no native date type. The two idiomatic choices:

- **`TEXT`**: ISO-8601 strings (`'2024-01-15T09:30:00Z'`). Human-readable in a DB
  browser; sorts correctly as text.
- **`INTEGER`**: Unix epoch seconds. Easier arithmetic; smaller storage.

`TEXT` is the better default unless you need to do a lot of date math in SQL.

```sql
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
```

### `updated_at` trigger

SQLite triggers use a different syntax from Postgres; they `UPDATE` the row rather
than rewriting `NEW`:

```sql
CREATE TRIGGER posts_set_updated_at
  AFTER UPDATE ON posts
  BEGIN
    UPDATE posts SET updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now')
    WHERE id = NEW.id;
  END;
```

The trigger's own `UPDATE` does not re-fire it while `PRAGMA recursive_triggers`
is off, which is the default.

Source: https://codex.mirio.dev/databases/table-design/timestamps/index.mdx
