Search code examples
sqlsql-servert-sqlsql-order-bysql-update

How to update and order by using ms sql


Ideally I want to do this:

UPDATE TOP (10) messages SET status=10 WHERE status=0 ORDER BY priority DESC;

In English: I want to get the top 10 available (status=0) messages from the DB and lock them (status=10). A message with a higher priority should be gotten first.

unfortunately MS SQL doesn't allow an order by clause in the update.

Anyway how to circumvent this?


Solution

  • You can do a subquery where you first get the IDs of the top 10 ordered by priority and then update the ones that are on that sub query:

    UPDATE  messages 
    SET status=10 
    WHERE ID in (SELECT TOP (10) Id 
                 FROM Table 
                 WHERE status=0 
                 ORDER BY priority DESC);