Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql + update top n

I've got a query like this:

update  table
set     status = 1
where   status = 2;     

but I'd only like to do this to the top 400. I tried adding a 'limit 0, 400' (like I would in a query) but that didn't work. I did some searching and mysql doesn't seem to support the TOP(n) command as sql server does.

Any idea how I'd do this?

edit: for future reference, I was using the following style for selects, which worked fine:

select  * 
from    table
where   ... limit 0, 400;

but in the update it wouldn't work with the "0, " for whatever reason. I would consider this inconsistent and ambiguous behaviour, but oh well.

like image 306
Steven Evers Avatar asked Apr 07 '09 15:04

Steven Evers


People also ask

How do I limit a SQL update query?

Let us now see the syntax to use UPDATE query with limit. UPDATE yourTableName SET column_name='some value'' WHERE column_name1 IN ( SELECT column_name1 FROM ( select column_name1 from yourTableName order by column_name1 asc limit integerValue,integerValue) anyAliasName );

How do you UPDATE a few rows in SQL?

There are a couple of ways to do it. INSERT INTO students (id, score1, score2) VALUES (1, 5, 8), (2, 10, 8), (3, 8, 3), (4, 10, 7) ON DUPLICATE KEY UPDATE score1 = VALUES(score1), score2 = VALUES(score2);


3 Answers

for future reference don't forget to set the safe mode off

SET SQL_SAFE_UPDATES = 0;
update YOUR_DATABASE_NAME.TABLE_NAME
set COLUMN_NAM = 0
limit 400;
SET SQL_SAFE_UPDATES = 1;

MySQL for example does not allow you to update records to prevent you from making mistakes with something called safe mode, so you will have to disable it to be able to update your records.

The other syntax is pretty forward. limit will restrict the number of records returned to a number of your choosing.

like image 165
Hatim Abu Tir Avatar answered Sep 29 '22 17:09

Hatim Abu Tir


UPDATE  table
SET     status = 1
WHERE   status = 2
ORDER BY id
LIMIT 400

Checked in MySQL 5.2.0-falcon-alpha-community-nt-log, confirmed working.

In your case it's 0 in LIMIT 0, 400 that does not work.

You cannot use the lower bound in UPDATE's LIMIT.

like image 24
Quassnoi Avatar answered Sep 29 '22 17:09

Quassnoi


Try this:

update  table
set     status = 1
where   status = 2
LIMIT 400

You can also put an order by clause

update  table
set     status = 1
where   status = 2
ORDER BY id
LIMIT 400
like image 25
Neil Aitken Avatar answered Sep 29 '22 17:09

Neil Aitken