Reputation: 16494
Is there a proper native non-workaround auto increment possiblity for ALL tables together in mySQL ? I mean, not just auto inc per table, i mean ONE number counting up for EACH new row in the database ?
I have seen this on a professional oracle (?) set up. The main advantage is that you have unique id for ALL rows/elements in ALL tables, not just PER TABLE.
Upvotes: 5
Views: 738
Reputation: 16127
PostgreSQL can be setup like this with a CREATE SEQUENCE seq_name
and using nextval(seq_name)
on every insert.
MySQL does not have native support for this, you can simulate the behavior of a PostgreSQL SEQUENCE by creating a table with only one column and an AUTO_INCREMENT
on that column.
You always insert into that table first read the LAST_INSERT_ID
of that table to get the id you need to insert into your table. It would be transaction safe so not duplicates would ever be generated.
Another way to achieve this is to create a table with one column no AUTO_INCREMENT
and only one row holding the current max value.
Every time you need to increment you execute UPDATE seq_table SET seq_column = seq_colum+1;
an increment update is in itself atomic but you need to also read the value afterwards which makes two statements and they are not atomic together unless you set a transaction around them and an appropriate isolation level. This approach saves space but also generates locking queries.
Multiple threads trying to INSERT
will have to wait for others to update the seq_table
before being able to update it themselves and read the new value.
Also you'd have to wrap the UPDATE
and the SELECT
on seq_table
in a transaction with an appropriate ISOLATION LEVEL
to avoid reading the value that some other thread incremented after you incremented it.
This means that INSERTS
become a transactional issue but normally they aren't, so i wouldn't recommend the second approach.
Upvotes: 6