Gapless Counter Table Invoice Numbers
A counter table hands out invoice numbers under a row lock: UPDATE ... RETURNING increments atomically and a ROLLBACK gives the number back for reuse.
Code
-- 发票号 (invoice numbers) 不能有空洞 (gapless):SEQUENCE 回滚即作废,改用 counter table 加行锁发号
CREATE TABLE invoice_counters (
scope text PRIMARY KEY,
next_number int NOT NULL
);
CREATE TABLE invoices (
invoice_no int PRIMARY KEY,
customer_id int NOT NULL
);
INSERT INTO invoice_counters VALUES ('eu', 1001);
-- UPDATE 行级锁把并发发号串行化;RETURNING 原子取号并自增
CREATE FUNCTION issue_invoice(p_customer int) RETURNS int
LANGUAGE sql AS $$
UPDATE invoice_counters
SET next_number = next_number + 1
WHERE scope = 'eu'
RETURNING next_number - 1;
$$;
BEGIN;
SELECT issue_invoice(7) AS issued_no; -- 发出 1001
INSERT INTO invoices VALUES (1001, 7);
COMMIT;
BEGIN;
SELECT issue_invoice(8) AS issued_no;
ROLLBACK; -- 回滚:计数器也回到 1001,下一个号仍是 1001
SELECT next_number FROM invoice_counters WHERE scope = 'eu';
SELECT * FROM invoices ORDER BY invoice_no;
DROP TABLE invoices;
DROP TABLE invoice_counters;What the code does
What runs here is SELECT / INSERT / UPDATE / CREATE — invoice_counters and invoices are the objects involved.
In terms of clauses, the statements use: a WHERE clause constraining which rows the statement operates on; an ORDER BY that fixes the output order; a RETURNING clause that hands the affected rows back to the caller; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Applying it
The invoice_counters table is the working surface here.
Statements that matter
CREATE FUNCTION issue_invoice(p_customer int) RETURNS int
LANGUAGE sql AS $$
UPDATE invoice_counters
SET next_number = next_number + 1
WHERE scope = 'eu'
RETURNING next_number - 1;
$$;
SELECT next_number FROM invoice_counters WHERE scope = 'eu';
CREATE TABLE invoice_counters (
scope text PRIMARY KEY,
next_number int NOT NULL
);
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Number Base ConverterConvert arbitrary-size integers between binary, octal, decimal, hexadecimal, and base 36 with digit validation and signed input support.
FAQ
- What are the relations in play here?
- `invoice_counters`, `invoices` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.