Re: auto increment within a compound key

From: Michael Fuhr <mike(at)fuhr(dot)org>
To: "Bogdoll, Dieter" <dieter(dot)bogdoll(at)siemens(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: auto increment within a compound key
Date: 2006-01-20 03:42:44
Message-ID: 20060120034244.GA31102@winnie.fuhr.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Tue, Jan 17, 2006 at 04:33:46PM +0100, Bogdoll, Dieter wrote:
> Is there any way to achieve the same result in Postgresql as the MySQL
> AUTO_INCREMENT does?

Not without an adverse impact on performance. PostgreSQL's serial
type is just a notational convenience for an integer column that
takes its default value from a sequence; the sequence's value isn't
affected by other columns' values. You could achieve the effect
you're after with a trigger but you'd have to allow for concurrency.

I see that a table definition such as the one you posted isn't
allowed for InnoDB tables:

mysql> CREATE TABLE foo (
-> x int AUTO_INCREMENT,
-> y int,
-> PRIMARY KEY (y, x)
-> ) TYPE INNODB;
ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key

It's allowed if you reverse the order of the columns in the primary
key, but then you get the same effect as in PostgreSQL:

mysql> CREATE TABLE foo (
-> x int AUTO_INCREMENT,
-> y int,
-> PRIMARY KEY (x, y)
-> ) TYPE INNODB;
Query OK, 0 rows affected, 1 warning (0.08 sec)

mysql> INSERT INTO foo (y) VALUES (1), (1), (2);
Query OK, 3 rows affected (0.06 sec)
Records: 3 Duplicates: 0 Warnings: 0

mysql> SELECT * FROM foo;
+---+---+
| x | y |
+---+---+
| 1 | 1 |
| 2 | 1 |
| 3 | 2 |
+---+---+
3 rows in set (0.01 sec)

--
Michael Fuhr

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2006-01-20 06:00:44 Re: mount -o async - is it safe?
Previous Message Rich Shepard 2006-01-20 03:08:22 Re: Upgrade Problem: 7.4.3 -> 8.1.2