Skip to content
Advertisement

SQL – updating column based on next row value

I have a table, and the requirement is to update column ‘val’ based on the value in the column ‘val’ in next row (ordered by by id).

Table is shown below :

I’m able get the select query to get the next value, however the update query is not working.

Here is the select query (working fine):

Here is the update query, not working :

Any inputs on how to fix this ? tia!

Advertisement

Answer

Your order of clauses are a bit off, the following modification will work

View Live Demo

You may consider using the following query which also uses the lead function but without the join.

Schema (MySQL v8.0)


Query #1

id val dt
1 k 2021-01-01 00:00:00
3 k1 2021-05-15 00:00:00
5 k2 2021-10-11 00:00:00

Query #2

There are no results to be displayed.


Query #3

id val dt
1 k1 2021-01-01 00:00:00
3 k2 2021-05-15 00:00:00
5 2021-10-11 00:00:00

View on DB Fiddle

Let me know if this works for you.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement