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.
PostgreSQL can be setup like this with a
CREATE SEQUENCE seq_nameand usingnextval(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_INCREMENTon that column.You always insert into that table first read the
LAST_INSERT_IDof 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_INCREMENTand 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
INSERTwill have to wait for others to update theseq_tablebefore being able to update it themselves and read the new value.Also you’d have to wrap the
UPDATEand theSELECTonseq_tablein a transaction with an appropriateISOLATION LEVELto avoid reading the value that some other thread incremented after you incremented it.This means that
INSERTSbecome a transactional issue but normally they aren’t, so i wouldn’t recommend the second approach.