I would like to know what will happen in the following hypothetical situation. Let’s say two teachers give the exact same class to the same students, they both want to update the student’s, bob’s, grades. Bob’s current average is 60%, teacher 1 wants to update his average with a test where he got 70% and teacher 2 wants to update his average with a test where he scored 40%.
So in the 1 to a million chance that the 2 teachers hit the update button simultaneously, precisely to the split-second exactly at the same time, what will happen? Will it give an error message, does php or mysql magically queue updates, will only the first score update bob’s average and the second user get an error?
Edit: My concern is that the second user must get the value after the first user edited the values, I was thinking of fetching the record then doing the calculations in php and then updating the record again, but in this situation how can I ensure that the second user fetches a value of 65% and not 60%, can this be done with transactions?
Both will go through and the last one to be processed will be the new value. Due to consistency guarantees from the database system you won’t get corrupt data, but because this is a calculated value you may get wrong data.
I suspect that this average is a calculated value based on data in some other table. If that’s the case, do all the work in one transaction. Add the new test score to the table, and let the database both calculate the average and insert the result directly into the second table. That way, either the result will be guaranteed to be correct or the transaction will fail. This requires a storage engine with transaction support (e.g., InnoDB).