Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`UPDATE` and `LIMIT` in `MySQL`

I would like to update a specific range of rows, say starting from 30 and ending at 50. How may I achieve that.

I have tried with:

UPDATE tab
SET    col = 'somevalue' 
LIMIT 30, 50

but this doesn't work. Is there any way that I can update these rows?

The error that I get is:

Check the manual ... for the right syntax to use near ' 50'

like image 804
Kamran Ahmed Avatar asked Apr 20 '14 13:04

Kamran Ahmed


People also ask

Does LIMIT work on UPDATE MySQL?

Yes, it is possible to use UPDATE query with LIMIT in MySQL.

How do I LIMIT data in MySQL?

Assume we wish to select all records from 1 - 30 (inclusive) from a table called "Orders". The SQL query would then look like this: $sql = "SELECT * FROM Orders LIMIT 30"; When the SQL query above is run, it will return the first 30 records.

What is UPDATE in MySQL?

The UPDATE statement is used to modify the existing records in a table.

What is LIMIT command in MySQL?

In MySQL the LIMIT clause is used with the SELECT statement to restrict the number of rows in the result set. The Limit Clause accepts one or two arguments which are offset and count. The value of both the parameters can be zero or positive integers.


1 Answers

Your statement is not valid MySQL syntax and it doesn't make sense. The problem with the syntax is that offset is not supported for update statements (see here).

The problem with the logic is that you have no order by clause. MySQL doesn't guarantee the order of tables when processing them. So the "first" twenty rows and the "next" twenty" rows make no difference.

Why doesn't this do what you want?

UPDATE tab
  SET    col = 'somevalue' 
  LIMIT 20;

If you have a specific column that specifies the ordering, you can use where:

UPDATE tab
  SET    col = 'somevalue' 
  wHERE ID >= 30 and ID < 50;
like image 84
Gordon Linoff Avatar answered Oct 10 '22 11:10

Gordon Linoff