Skip to content
Advertisement

SQLite how to use UPDATE and LIMIT at the same time?

What I’m looking for is to update only 1 row in a table where all the entries are, in the beginning, zero.
After a while surfing the internet for answers, I found out that LIMIT should work fine with UPDATE, but also not quite. From what I’ve seen, I should have “enabled” some stuff with SQLITE_ENABLE_UPDATE_DELETE_LIMIT, but I have no idea what that is or where and when I should have done it.
I’ve also seen different solutions for those in my situation, things like:

UPDATE Table_name
Set Column_name= new_value
WHERE Column_name IN 
(   SELECT Column_name
    FROM Table_name
    WHERE Column_name = initial_value
    LIMIT 1
)

But this, for some reason, is not working for me. The LIMIT 1 has absolutely no effect, as the entire column gets modified.

Is it because I’m using the same column name in both SET/SELECT and in WHERE?

My table only consists of a single column.

Advertisement

Answer

You can get the minimum (or maximum) rowid of the rows that satisfy your conditions and use it to update only 1 row:

UPDATE Table_name
Set Column_name= new_value
WHERE rowid = (   
  SELECT MIN(rowid)
  FROM Table_name
  WHERE Column_name = initial_value
)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement