Update randomly selected row in SQLite

I have a table and it has a specific value - by default it is set to -1, but I want to change it to 0 for a random row.

What is the correct query for this operation?

Here is what I tried:

UPDATE statuses SET status = 0
WHERE word_id = (
      SELECT word_id FROM statuses WHERE status = -1 ORDER BY RANDOM() LIMIT 1
)
+3
source share
1 answer

Hmm, I just made a sample table, and your query works as written:

sqlite> create table statuses (word_id, status default -1);
sqlite> insert into statuses (word_id) values (1);
sqlite> insert into statuses (word_id) values (2);
sqlite> insert into statuses (word_id) values (3);
sqlite> insert into statuses (word_id) values (4);
sqlite> insert into statuses (word_id) values (5);
sqlite> select * from statuses;
1|-1
2|-1
3|-1
4|-1
5|-1
sqlite> UPDATE statuses SET status = 0
   ...> WHERE word_id = (
   ...>       SELECT word_id FROM statuses WHERE status = -1 ORDER BY RANDOM() LIMIT 1
   ...> );
sqlite> select * from statuses;
1|-1
2|-1
3|0
4|-1
5|-1

So, in other words, your request is right - your mistake is probably elsewhere in your code.

+3
source

Source: https://habr.com/ru/post/1710742/


All Articles