3

I want to simulate an auto_increment scenario during an insert without the field having the auto_increment property. Here is the scenario sql statement:

insert into acct set id=(select @vid:=max(id)+1); select @vid;

Basically, I want the insert and select done at the same time so I can guarantee the value of vid is unique.

2
  • 3
    Why don't you use the auto_increment feature MySQL has? dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html Commented Mar 14, 2011 at 18:55
  • 3
    You're going to have concurrency headaches if you try to roll your own auto_increment functionality. Commented Mar 14, 2011 at 18:55

3 Answers 3

1

If you want the autoincremented value to be shared across transactions with guaranteed uniqueness, you should have a lockable singleton visible to all transactions which would hold the last unique value.

In MyISAM, it is stored in the table's metadata, in InnoDB, in a special memory object populated with MAX(id) on the first insert after the server startup.

Of course you can make your own (say a dedicated table with a single record), but, honestly, I don't see any benefits over the build-in functionality in such a solution.

Sign up to request clarification or add additional context in comments.

Comments

0
insert into acct values ( (select max(id)+1 from acct), ... rest_of_vars );

2 Comments

How do I READ this value from the insert? That is, I need to know the value of select max(id)+1 during the insert operation.
new - incremented - value will be inserted automatically so knowing value during is not needed. if after is needed <code>(select max(id)+1 from acct)</code>
0

You can do all this in a transaction to guarantee no one else will access the table :

START TRANSACTION;
insert into acct set id=(select @vid:=max(id)+1);
select @vid;
COMMIT;

1 Comment

Can I do this in one SQL statement without transactions? Basically I want to read the value of max(id)+1 during the insert operation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.