> there's very much information about how transactions and locking works
> in InnoDB, but maybe there's also a simple and understandable answer to
> my simple question:
> When I start a transaction, then find the maximum value of a column and
> use that + 1 to write a new row into the table, how do transactions
> protect me from somebody else doing the same thing so that we'd both end
> up writing a new row with the same value?
They won't, a "constraint" protects you from inserting a new row with
the same value.
> Here's a description:
> BEGIN TRANSACTION
> new_id := (SELECT MAX(id) FROM table) + 1
> -- some more work here
> INSERT INTO table (id, ...) VALUES (new_id, ...)
> What happens if another user does the same in that "more work" region?
You will end up with the same "new_id" value, but the primary key
constraint - if you have one - will reject the insert.
Transactions come in multiple flavors, have a look at the different
Depending on your isolation level, for example, you will see new rows
in the table between your "begin transaction" and "select max..." or
between two "select max" statements. Other isolation levels will give
you the same max value when reading the value twice, even though
someone else inserted a new row.
Database Workbench - development tool for MySQL, and more!
Database development questions? Check the forum!