C
C
censor20052021-10-12 13:42:56
SQL
censor2005, 2021-10-12 13:42:56

How to get the last actual row of a table in parallel queries?

There is a table datas:
id | last_data
------------
1 | 25000
2 | 75000
...
From time to time new data is inserted into the table according to the following algorithm: last_data = previous last_data + 50000. To do this, I use

SELECT last_data FROM datas ORDER BY id DESC LIMIT 1
I get the last value, add 50000 and INSERT a new row

Now, if many parallel insert requests come in, is it possible that two requests will receive the same last_data (for example, 75000), and both will insert the same new row (125000) ? In theory, I need the values ​​\u200b\u200bof 125000 and 175000 to be inserted.

The project uses Laravel

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2021-10-12
@Rsa97

Either a transaction with a table lock, or an atomic query like

INSERT INTO `table` (`last_data`)
  WITH `cte` (`max`) AS (
    SELECT MAX(`last_data`)
      FROM `table`
  ) SELECT `max` + 50000 FROM `cte`;

S
Slava Rozhnev, 2021-10-12
@rozhnev

There is no point in adding - you need to store only the difference And get the sum when you select the data:

SELECT 
  id,
  diff,
  SUM(diff) OVER (ORDER BY id ASC)
FROM t;

MySQL fiddle here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question