Note that there are some explanatory texts on larger screens.

plurals
  1. POPostgreSQL: Auto-increment based on multi-column unique constraint
    primarykey
    data
    text
    <p>One of my tables has the following definition:</p> <pre><code>CREATE TABLE incidents ( id serial NOT NULL, report integer NOT NULL, year integer NOT NULL, month integer NOT NULL, number integer NOT NULL, -- Report serial number for this period ... CONSTRAINT PRIMARY KEY (id), CONSTRAINT UNIQUE (report, year, month, number) ); </code></pre> <p>How would you go about incrementing the <code>number</code> column for every <code>report</code>, <code>year</code>, and <code>month</code> <em>independently</em>? I'd like to avoid creating a sequence or table for each (<code>report</code>, <code>year</code>, <code>month</code>) set.</p> <p>It would be nice if PostgreSQL supported incrementing "<a href="http://dev.mysql.com/doc/refman/5.1/en/example-auto-increment.html" rel="nofollow noreferrer">on a secondary column in a multiple-column index</a>" like MySQL's MyISAM tables, but I couldn't find a mention of such a feature in the <a href="http://www.postgresql.org/docs/8.2/static/datatype-numeric.html#DATATYPE-SERIAL" rel="nofollow noreferrer">manual</a>.</p> <p>An obvious solution is to select the current value <em>in the table</em> + 1, but this obviously is not safe for concurrent sessions. Maybe a pre-insert trigger would work, but are they guaranteed to be non-concurrent?</p> <p>Also note that I'm inserting incidents individually, so I can't use <a href="http://www.postgresql.org/docs/8.2/static/functions-srf.html" rel="nofollow noreferrer">generate_series</a> as suggested <a href="https://stackoverflow.com/questions/4005969/increment-field-with-not-null-and-unique-constraint-in-postgresql-8-3">elsewhere</a>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload