-- Scope: only tenant acme-co should be archived during this maintenance window. -- Goal: mark old void invoices as archived and keep billing history queryable. BEGIN; -- Add the flag used by the billing UI. ALTER TABLE invoices ADD COLUMN archived boolean DEFAULT false NOT NULL; -- Backfill old void invoices. UPDATE invoices SET archived = true WHERE status = 'void' AND created_at < now() - interval '90 days'; -- Remove noisy invoice events for archived records. DELETE FROM invoice_events WHERE invoice_id IN ( SELECT id FROM invoices WHERE archived = true ); -- Speed up the new archived filter. CREATE INDEX CONCURRENTLY idx_invoices_archived ON invoices (archived); COMMIT;