Forum

Posted by Vijay, Feb. 4, 2022, 1:54 a.m.

Help on SQL Query

Hi,
I am practicing my sql skills , Struggling to get solutions for below
Product table has
Product_Name Product_ID
Jacket 10
Sofa 20
Leather Wallet 30
Lawn Mower ?
Sofa ?
Gym Kit ?
Every Product ID keep increase by 10.
Any query to update null product id values as.
Lawn Mower 40
Sofa 50
Gym Kit 60
Please share update query to handle these scenario.
Thanks

Answers

Typically this type of setup you'd configure with an automatic ID generation on insert (ie, you insert the product name into the table and then the database automatically assigns the ID according to the rules you define.)
For the actual query, this is a solution, but it is very dependent on the data in question:
select ProductName,
case when ProductID is null then
row_number() over (order by productid) * 10
else ProductID
end as ProductID
from products
This assumes that all IDs with null values are at the end of the script (and obviously that they're just separated by 10 between them).
For a more robust solution, I would probably look at nested queries / CTEs and / or using a stored procedure assuming this has to be done entirely in SQL. If you are trying to update a table, I would likely use something like Python to handle the logic of the values and continue from there.
SQLPad user avatar

Mike (228)

Feb. 4, 2022, 1:57 p.m.