How can I iterate through SQL results like a for loop and an array? - sql

I have a table, and I want to select only the single column of row IDs from it, but in a specific order. Then, I want to loop through that column like below:
for (i=0; i<rows.length; i++)
{
if(i==rows.length-1)
UPDATE myTable SET nextID = NULL WHERE ID = rows[i]
ELSE
UPDATE myTable SET nextID = rows[i+1] WHERE ID = rows[i]
}
I just dont know how to access the results of my select statement with an index like that. Is there a way of doing this in sql server?

Since you didn't provide many details, let's pretend your table looks something like this:
create table MyTable (
Id int not null primary key,
Name varchar(50) not null,
NextId int
)
I want to select only the single column of row IDs from it, but in a specific order
Let's just say that in this case, you decide to order the rows alphabetically by Name. So let's pretend that the select statement that you want to loop through looks like this:
select Id
from MyTable
order by Name
That being the case, instead of looping through the rows and attempting to update each row using the pseudo-code you provided, you can replace the whole thing with a single update statement that will perform the exact same work:
with cte as (
select *,
NewNextId = lead(Id) over (order by Name)
from MyTable
)
update cte
set NextId = NewNextId
Just make sure to adjust the order by clause to whatever your specific order really is. I just used Name in my example, but it might be something else in your case.

You could use a cursor, or you could use something a bit smarter.
Your example should be able to be written fairly easily along the lines of:
update mytable set nextID = LEAD(id,1) over (order by id)
Lead(id,1) will grab the next id, 1 row ahead in the record set and update the nextID field with it. If it can't find one it will return null. No looping or conditional logic needed!
edit: I forgot the over clause. This is the part that tells it how you would like it ordered for the lead

Related

UPDATE … FROM syntax with sub-query

I have a table, items, with a priority column, which is just an integer. In trying to do some bulk operations, I'm trying to reset the priority to be a sequential number.
I've been able to use ROW_NUMBER() to successfully generate a table that has the new priority values I want. Now, I just need to get the values from that SELECT query into the matching records in the actual items table.
I've tried something like this:
UPDATE
"items"
SET
"priority" = tempTable.newPriority
FROM
(
SELECT
ROW_NUMBER() OVER (
ORDER BY
/* pile of sort conditions here */
) AS "newPriority"
FROM
"items"
) AS tempTable
WHERE
"items"."id" = "tempTable"."id"
;
I keep getting a syntax error "near FROM".
How can I correct the syntax here?
SQLite is not as flexible as other rdbms, it does not support even joins in an update statement.
What you can do instead is something like this:
update items
set priority = 1 + (
select count(*)
from items i
where i.id < items.id
)
With this the condition is derived only by the ids.
So the column priority will be filled with sequential numbers 1, 2, 3, ....
If you can apply that pile of sort conditions in this manner, you will make the update work.
Edit.
Something like this maybe can do what you need, although I'm not sure about its efficiency:
UPDATE items
SET priority = (
SELECT newPriority FROM (
SELECT id, ROW_NUMBER() OVER (ORDER BY /* pile of sort conditions here */) AS newPriority
FROM items
) AS tempTable
WHERE tempTable.id = items.id
)
It turns out that the root answer to this specific question is that SQLite doesn't support UPDATE ... FROM. Therefore, some alternative methods are needed.
https://www.sqlite.org/lang_update.html

Update columns in DB2 using randomly chosen static values provided at runtime

I would like to update rows with values chosen randomly from a set of possible values.
Ideally I would be able to provide this values at runtime, using JdbcTemplate from Java application.
Example:
In a table, column "name" can contain any name. The goal is to run through the table and change all names to equal to either "Bob" or "Alice".
I know that this can be done by creating a sql function. I tested it and it was fine but I wonder if it is possible to just use simple query?
This will not work, seems that the value is computed once, and applied to all rows:
UPDATE test.table
SET first_name =
(SELECT a.name
FROM
(SELECT a.name, RAND() idx
FROM (VALUES('Alice'), ('Bob')) AS a(name) ORDER BY idx FETCH FIRST 1 ROW ONLY) as a)
;
I tried using MERGE INTO, but it won't even run (possible_names is not found in SET query). I am yet to figure out why:
MERGE INTO test.table
USING
(SELECT
names.fname
FROM
(VALUES('Alice'), ('Bob'), ('Rob')) AS names(fname)) AS possible_names
ON ( test.table.first_name IS NOT NULL )
WHEN MATCHED THEN
UPDATE SET
-- select random name
first_name = (SELECT fname FROM possible_names ORDER BY idx FETCH FIRST 1 ROW ONLY)
;
EDIT: If possible, I would like to only focus on fields being updated and not depend on knowing primary keys and such.
Db2 seems to be optimizing away the subselect that returns your supposedly random name, materializing it only once, hence all rows in the target table receive the same value.
To force subselect execution for each row you need to somehow correlate it to the table being updated, for example:
UPDATE test.table
SET first_name =
(SELECT a.name
FROM (VALUES('Alice'), ('Bob')) AS a(name)
ORDER BY RAND(ASCII(SUBSTR(first_name, 1, 1)))
FETCH FIRST 1 ROW ONLY)
or may be even
UPDATE test.table
SET first_name =
(SELECT a.name
FROM (VALUES('Alice'), ('Bob')) AS a(name)
ORDER BY first_name, RAND()
FETCH FIRST 1 ROW ONLY)
Now that the result of subselect seems to depend on the value of the corresponding row in the target table, there's no choice but to execute it for each row.
If your table has a primary key, this would work. I've assumed the PK is column id.
UPDATE test.table t
SET first_name =
( SELECT name from
( SELECT *, ROW_NUMBER() OVER(PARTITION BY id ORDER BY R) AS RN FROM
( SELECT *, RAND() R
FROM test.table, TABLE(VALUES('Alice'), ('Bob')) AS d(name)
)
)
AS u
WHERE t.id = u.id and rn = 1
)
;
There might be a nicer/more efficient solution, but I'll leave that to others.
FYI I used the following DDL and data to test the above.
create table test.table(id int not null primary key, first_name varchar(32));
insert into test.table values (1,'Flo'),(2,'Fred'),(3,'Sue'),(4,'John'),(5,'Jim');

Insert row over existing row, move rows down

I'm trying to insert a new row in the middle of a sql table and move all other rows first to make space for it.
I've tried
setting id=id+1,
but that gives me an error(obviously) because the row id+1 exists already, so this only works for going in the other direction so id=id-1.
What is the correct solution then?
To do the stuff, you should update you table from the end:
UPDATE `table` SET `id`=`id`+1 WHERE `id`>$value ORDER BY `id` DESC
Where $value is your value
You could try something like this:
UPDATE table_name SET id = id + 1 WHERE id >= your_id_value ORDER BY id DESC;
INSERT INTO table_name(..., id, ...) VALUES(..., your_id_value, ...)

How to select items with all possible id-s or just a particular one using the same query?

Is there a variable in SQL that can be used to represent ALL the possible values of a field? Something like this pseudo-code
SELECT name FROM table WHERE id = *ALL_EXISTING_ID-s*
I want to return all rows in this case, but later when I do a search and need only one item I can simply replace that variable with the id I'm looking for, i.e.
SELECT name FROM table WHERE id = 1
The simplest way is to remove the WHERE clause. This will return all rows.
SELECT name FROM table
If you want some "magic" value you can use for the ID that you can use in your existing query and it will return all rows, I think you're out of luck.
Though you could use something like this:
SELECT name FROM table WHERE id = IFNULL(?, id)
If the value NULL is provided, all rows will be returned.
If you don't like NULL then try the following query, which will return all rows if the value -1 is provided:
SELECT name FROM table WHERE id = IFNULL(NULLIF(?, -1), id)
Another approach that achieves the same effect (but requires binding the id twice) is:
SELECT name FROM table WHERE (id = ? OR ? = -1)

Update with function for value only seems to evaluate the function once

I'm trying to change all the NULLs in an INT column to an incrementing value using a statement like this:
UPDATE [TableName] SET [ColumnName] = dbo.FunctionName() WHERE [ColumnName] IS NULL
where the function looks like this:
CREATE FUNCTION FunctionName() RETURNS INT AS
BEGIN
RETURN (select MAX(ColumnName) + 1 from TableName)
END
but the result of this is that all the values that were NULL are now set to the same value (i.e. 1 greater than the max before the statement was called).
Is this the expected behaviour? If so, how would I go about getting the result I'm after?
I'd like to avoid using an auto-increment column as all I really want is uniqueness, the incrementing is just a way of getting there.
Yes, this is by design, it is called Halloween protection. To achieve what you want (that is a one time) use an updatable CTE:
with cte as (
SELECT Column,
ROW_NUMBER() OVER () as rn
FROM Table
WHERE Column IS NULL)
UPDATE t
SET t.Column = m.max + t.rn
FROM cte t
JOIN (
SELECT MAX(Column) as max
FROM Table) m;