I have a SQL database with 250 rows. I inserted a column filled with 0’s. I updated the first rows 11 rows to be 1,2,3,4,5,6,7,8,9,10 & 11. The rest of the rows are still 0’s.
How would I go about updating rows 11-250 to go from 0 to each of the relevant row value.
thank you!
3
Answers
There are two approach (which i can think of) to this problem. You can either using window function alternatively, you can use variable.
Assuming you have the following test table:
Using Variable
The variable one is pretty straight forward. Though you have less control over which one first. This part is adapted from row_number() in mysql.
The
@rownum
variable is used to keep track the current rank of the row.See fiddle: https://www.db-fiddle.com/f/Jmn5x34WXaBJq7oyemtXp/0
Using Window Function
The window functions comes with
rank()
which we will use this time. It require at least mysql version 8 to use.The reason i’m asking for point of reference how to rank the rows is that, the
rank()
need to be partitioned to work otherwise everyone is rank 1. The important part is the:To determine the "position" of the row, you could use
id
or other column as you needed.See fiddle: https://www.db-fiddle.com/f/nwLv9R7weQt4e5RhUbgaUL/0
Note:
If a classic version (prior to 8.0) is being used, which does not support CTE and window functions, we have to find a workaround. To resolve the issue, we can use the user variable trick. Below are the complete steps to demonstrate it.
Create a user-defined variable (
@rownumber
for example) to increment a value of1
.Result:
Demo here.