← Back to SQL, page 25

sql-0489 · Medium mid

Design the tables for a multi-step approval workflow, such as leave requests that need manager and then HR approval.

Keep one row per request with its current status, a table of steps defined per request type, and an append-only history of decisions with who, when and the comment. Valid transitions are enforced by a CHECK on status values and by application or trigger logic, and the current step is derived from the history. The history table answers audits without reconstructing past states.

Full answer

Illustrative design (example SQL, not run here):

sql
CREATE TABLE request_types (id int PRIMARY KEY, name text UNIQUE);
CREATE TABLE approval_steps (
  request_type_id int REFERENCES request_types(id),
  step_no         int,
  approver_role   text NOT NULL,
  PRIMARY KEY (request_type_id, step_no)
);
CREATE TABLE requests (
  id              bigserial PRIMARY KEY,
  request_type_id int NOT NULL REFERENCES request_types(id),
  requester_id    bigint NOT NULL,
  status          text NOT NULL CHECK (status IN ('pending', 'approved', 'rejected', 'withdrawn')),
  current_step    int,
  created_at      timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE request_decisions (
  id          bigserial PRIMARY KEY,
  request_id  bigint NOT NULL REFERENCES requests(id),
  step_no     int NOT NULL,
  decided_by  bigint NOT NULL,
  decision    text NOT NULL CHECK (decision IN ('approve', 'reject')),
  comment     text,
  decided_at  timestamptz NOT NULL DEFAULT now(),
  UNIQUE (request_id, step_no)
);

How it behaves: a request starts as pending at step 1. An approval inserts a decision row and moves current_step to the next step, or sets status = 'approved' after the last one. A rejection sets rejected immediately. The unique key on (request_id, step_no) stops two approvers from deciding the same step twice, even in concurrent requests, and the update and decision insert happen in one transaction.

Alternatives and trade-offs: a table of allowed transitions (from_status, to_status) makes the state machine data instead of code; workflow engines are worth considering when routing becomes conditional (amount thresholds, parallel approvals, delegation). Delegation and out-of-office rules are best modelled as extra rows that map one approver role to another person for a period, not as special cases in code.

Key points

  • Request row with current status and step
  • Step definitions per request type
  • Append-only decision history
  • Unique key prevents double decisions
  • Transitions in one transaction

Common mistakes

  • Overwriting status without keeping history
  • Hard-coding the approval chain in application code only

Follow-ups

  • How would you support parallel approvals by two roles?
  • How would you report average time spent at each step?

Tips

  • Separate current state from history