Basic SQL Atomicity "UPDATE ... SET .. WHERE ..."
I have a rather simple and general question about the atomicity of the "UPDATE ... SET .. WHERE ..." statement.
having a table (no additional limitation),
+----------+
| id | name|
+----------+
| 1 | a |
+----+-----+
now I will execute the next 4 statements "at the same time" (simultaneously).
UPDATE table SET name='b1' WHERE name='a'
UPDATE table SET name='b2' WHERE name='a'
UPDATE table SET name='b3' WHERE name='a'
UPDATE table SET name='b4' WHERE name='a'
is there only one UPDATE statement to update the table? or, is it possible that more than one UPDATE statement can actually update the table?
Do I need an additional transaction or lock so that only one UPDATE value is written to the table?
thanks
[EDIT] 4 UPDATE statements are executed in parallel from different processes. [EDIT] with Postgresql
a source to share
One of these statements will lock the record (or the page or the entire table, depending on your mechanism and granularity) and will be executed.
The rest will wait for the resource to be released.
When the peer statement commits, the others will either re-read the table, or do nothing (if the transaction isolation mode is set to READ COMMITTED
), or failed to serialize the transaction (if the transaction isolation level is SERIALIZABLE
).
a source to share
There will be an implicit transaction around each one that will contain other UPDATEs in the queue. Only the first one would win in this case, since every subsequent update won't see the name named "a".
Edit: I assumed you were calling each UPDATE from separate processes. If they were called in the same script, they will run sequentially in the order they appear.
a source to share
There is only one UPDATE statement that can access the record. Before starting it starts a transaction and locks the table (or rather, the page on which the record is written, or even the record itself - it depends on many factors). Then he makes the change and unlocks the table again, committing a transaction in the process.
Updates / deletes / inserts to a specific record are single-threaded by their very nature, it is necessary to ensure the integrity of the table. This does not mean that updates for many records (which are on different pages) cannot be done in parallel.
a source to share
I believe this might be what you are looking for (in T-SQL):
UPDATE [table]
SET [table].[name] = temp.new_name
FROM
[table],
(
SELECT
id,
new_name = 'B'+ cast(row_number() over (order by [name]) as varchar)
FROM
[table]
WHERE
[table].name = 'A'
) temp
WHERE [table].id = temp.id
Other SQL attributes must have an equivalent function row_number.
a source to share