> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cockroachlabs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Data model (schema reference)

> This page is the complete reference schema.

This page is the complete reference schema. Other pages explain why each table is designed as it is; this page is the authoritative source for names, keys, and constraints, so that prose, SQL, APIs, events, and tests remain consistent. Every table uses `UUID` primary keys (`gen_random_uuid()`) to avoid insert hotspots, `DECIMAL` for money, and `TIMESTAMPTZ` for time.

> [!WARNING]
>
> **Do not use `INTERLEAVE IN PARENT`**
> It was removed from CockroachDB. Co-locate related data through key design and [hash-sharded indexes](https://docs.cockroachlabs.com/docs/stable/hash-sharded-indexes.md), not interleaving.

## Entity overview

| Table | Purpose | Detailed on |
| - | - | - |
| `orders` | One row per order; lifecycle state + total | [Lifecycle & idempotency](https://docs.cockroachlabs.com/docs/cookbook/order-management/order-lifecycle-and-idempotency.md) |
| `order_lines` | SKU + qty + **price snapshot** per order | [Representing money](https://docs.cockroachlabs.com/docs/cookbook/order-management/representing-money.md) |
| `order_events` | Append-only audit history | [Lifecycle & idempotency](https://docs.cockroachlabs.com/docs/cookbook/order-management/order-lifecycle-and-idempotency.md) |
| `idempotency_keys` | At-most-once request guard | [Lifecycle & idempotency](https://docs.cockroachlabs.com/docs/cookbook/order-management/order-lifecycle-and-idempotency.md) |
| `inventory` | Stock counter per SKU | [Inventory & reservations](https://docs.cockroachlabs.com/docs/cookbook/order-management/inventory-and-reservations.md) |
| `reservations` | Time-bounded stock holds | [Inventory & reservations](https://docs.cockroachlabs.com/docs/cookbook/order-management/inventory-and-reservations.md) |
| `payment_transactions` | Money-movement intent + outcome | [Payments & callbacks](https://docs.cockroachlabs.com/docs/cookbook/order-management/payments-and-callbacks.md) |
| `payment_events` | Inbox for provider callbacks | [Payments & callbacks](https://docs.cockroachlabs.com/docs/cookbook/order-management/payments-and-callbacks.md) |
| `shipments` / `shipment_lines` | Partial/split fulfillment | [Fulfillment & returns](https://docs.cockroachlabs.com/docs/cookbook/order-management/fulfillment-and-returns.md) |
| `returns` / `return_lines` | Returns / RMA | [Fulfillment & returns](https://docs.cockroachlabs.com/docs/cookbook/order-management/fulfillment-and-returns.md) |
| `outbox` | Transactional hand-off to external systems | [External integration](https://docs.cockroachlabs.com/docs/cookbook/order-management/external-integration.md) |

## Core DDL

```sql theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
CREATE TABLE orders (
  id          UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  customer_id UUID NOT NULL,
  status      STRING NOT NULL DEFAULT 'created',
  version     INT    NOT NULL DEFAULT 0,
  currency    CHAR(3) NOT NULL,
  total       DECIMAL(18,2) NOT NULL DEFAULT 0,
  created_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
  CONSTRAINT valid_status CHECK (status IN
    ('created','paid','fulfilling','shipped','delivered','cancelled','returned')),
  INDEX (customer_id, created_at DESC)
);

CREATE TABLE order_lines (
  order_id   UUID NOT NULL REFERENCES orders(id),
  line_no    INT  NOT NULL,
  sku        STRING NOT NULL,
  qty        INT  NOT NULL CHECK (qty > 0),
  unit_price DECIMAL(18,2) NOT NULL,     -- price snapshot
  discount   DECIMAL(18,2) NOT NULL DEFAULT 0,
  tax        DECIMAL(18,2) NOT NULL DEFAULT 0,
  PRIMARY KEY (order_id, line_no)
);

CREATE TABLE order_events (
  order_id    UUID NOT NULL REFERENCES orders(id),
  seq         INT  NOT NULL,
  from_state  STRING,
  to_state    STRING NOT NULL,
  actor       STRING NOT NULL,
  payload     JSONB,
  occurred_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (order_id, seq)
);

CREATE TABLE idempotency_keys (
  key                 STRING PRIMARY KEY,
  request_fingerprint STRING NOT NULL,
  state               STRING NOT NULL DEFAULT 'in_progress'
                      CHECK (state IN ('in_progress','done')),
  attempt_count       INT NOT NULL DEFAULT 0,
  response            JSONB,
  created_at          TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE inventory (
  sku       STRING PRIMARY KEY,
  on_hand   INT NOT NULL CHECK (on_hand  >= 0),
  reserved  INT NOT NULL DEFAULT 0 CHECK (reserved >= 0),
  available INT AS (on_hand - reserved) STORED CHECK (available >= 0)
);

CREATE TABLE reservations (
  id         UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  sku        STRING NOT NULL REFERENCES inventory(sku),
  order_id   UUID   NOT NULL REFERENCES orders(id),
  qty        INT    NOT NULL CHECK (qty > 0),
  state      STRING NOT NULL DEFAULT 'held'
             CHECK (state IN ('held','committed','released','expired')),
  expires_at TIMESTAMPTZ NOT NULL,
  INDEX (sku, state, expires_at)
);

CREATE TABLE payment_transactions (
  id              UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  order_id        UUID NOT NULL REFERENCES orders(id),
  idempotency_key STRING NOT NULL UNIQUE,
  state           STRING NOT NULL DEFAULT 'initiated'
                  CHECK (state IN ('initiated','authorized','captured','failed','refunded')),
  amount          DECIMAL(18,2) NOT NULL,
  currency        CHAR(3) NOT NULL,
  refunded_amount DECIMAL(18,2) NOT NULL DEFAULT 0
                  CHECK (refunded_amount >= 0 AND refunded_amount <= amount),
  provider_ref    STRING,
  created_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at      TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE payment_events (
  provider           STRING NOT NULL,
  provider_event_id  STRING NOT NULL,
  payment_id         UUID   NOT NULL REFERENCES payment_transactions(id),
  kind               STRING NOT NULL,
  provider_status_at TIMESTAMPTZ NOT NULL,
  received_at        TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (provider, provider_event_id)
);

CREATE TABLE outbox (
  id          UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  aggregate   STRING NOT NULL,           -- 'order','payment',...
  event_type  STRING NOT NULL,
  payload     JSONB NOT NULL,
  created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);
```

Fulfillment tables (`shipments`, `shipment_lines`, `returns`, `return_lines`) are defined on the [Fulfillment & returns](https://docs.cockroachlabs.com/docs/cookbook/order-management/fulfillment-and-returns.md) page.

## Conventions

* **Keys:** `UUID` default `gen_random_uuid()`; child tables use composite PKs (`order_id, line_no` / `order_id, seq`).
* **Separate by access pattern:** the order header (`orders`), the immutable line detail (`order_lines`), and the append-only history (`order_events`) are separate tables: their read/write patterns differ, and detail and history are write-once.
* **Index for demonstrated queries only:** choose primary keys around the dominant lookup path; add a secondary index only when a real query needs it (speculative indexes cost write throughput). Use keyset pagination rather than `OFFSET` for large scans, and avoid unindexed `JSONB` filters on hot paths.
* **Money:** `DECIMAL(18,2)` + `currency CHAR(3)`; never `FLOAT`.
* **Time:** `TIMESTAMPTZ` everywhere.
* **Invariants in the schema:** `CHECK` constraints (`available >= 0`, `refunded_amount <= amount`, `qty > 0`) are backstops that hold even if application code is wrong.
* **Expiry/cleanup:** [Row-Level TTL](https://docs.cockroachlabs.com/docs/stable/row-level-ttl.md) on `reservations`, `idempotency_keys`, and `outbox` to garbage-collect, never to enforce correctness.
