Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update with Where, Order by and Limit does not work

I am using SQLite 3.

When I input the following query

UPDATE MyTable Set Flag = 1 WHERE ID = 5 Order By OrderID DESC LIMIT 1;

I will always get an error:

near Order By, syntax error

I cannot figure out what is the problem with my query

like image 270
alancc Avatar asked Sep 16 '25 16:09

alancc


2 Answers

To use LIMIT and ORDER BY in an UPDATE or DELETE statement, you have to do two things:

  • Build a custom version of the sqlite3.c amalgamation from source, configuring it with the --enable-update-limit option.
  • Compile that custom sqlite3.c into your project with SQLITE_ENABLE_UPDATE_DELETE_LIMIT defined to 1.
like image 153
Shawn Avatar answered Sep 19 '25 06:09

Shawn


"Order By OrderID DESC LIMIT 1" is for selecting top one ordered result so you should use it in select query. you should do a subquery where you first get the id and then update it:

UPDATE  MyTable 
SET Flag = 1 
WHERE (ID,OrderID) IN (SELECT ID,OrderID
FROM MyTable 
WHERE ID = 5 
ORDER BY OrderID DESC LIMIT 1);

Demo

like image 41
Majva Avatar answered Sep 19 '25 07:09

Majva