Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL UPDATE TOP with ORDER BY?

Tags:

sql

sql-server

I have a following query:

UPDATE TOP (@MaxRecords) Messages  SET    status = 'P'  OUTPUT inserted.*  FROM   Messages  where Status = 'N' and InsertDate >= GETDATE() 

In the Messages table there is priority column and I want to select high priority messages first. So I need an ORDER BY. But I do not need to have sorted output but sorted data before update runs.

As far as I know it's not possible to add ORDER BY to UPDATE statement. Any other ideas?

like image 640
Marcin Avatar asked Oct 25 '13 08:10

Marcin


People also ask

Can we use order by in update statement?

UPDATE t SET id = id + 1 ORDER BY id DESC; You can also perform UPDATE operations covering multiple tables. However, you cannot use ORDER BY or LIMIT with a multiple-table UPDATE .

Can we use top in update statement?

Without the TOP clause, if you are doing a manual update and your mouse text selection only selects from "UPDATE" to just before the "WHERE" clause, then the update is applied to ALL rows. With the TOP clause, only one row would get the undesired update.

Can we use order by in update query SQL Server?

You Can Use ORDER BY And LIMIT Within UPDATE And DELETE Statements In MySQL 5.6.

Can we use top with Group By clause?

Typically, these are accomplished using the TOP or LIMIT clause. Problem is, Top N result sets are limited to the highest values in the table, without any grouping. The GROUP BY clause can help with that, but it is limited to the single top result for each group.


2 Answers

you can use common table expression for this:

;with cte as (    select top (@MaxRecords)        status    from Messages     where Status = 'N' and InsertDate >= getdate()    order by ... ) update cte set     status = 'P' output inserted.* 

This one uses the fact that in SQL Server it's possible to update cte, like updatable view.

like image 56
Roman Pekar Avatar answered Oct 09 '22 08:10

Roman Pekar


You can try sub query like

  UPDATE Messages      SET    status = 'P'      WHERE MessageId IN (SELECT TOP (@MaxRecords) MessageId FROM Messages where Status = 'N' and InsertDate >= GETDATE() ORDER BY Priority) output inserted.* 
like image 28
Upendra Chaudhari Avatar answered Oct 09 '22 09:10

Upendra Chaudhari