How to update and order by using ms sql
⚡TLDR
Here is a quick and handy snippet to UPDATE rows in a specific order using a Common Table Expression (CTE):
As you see, the first 5 rows where ConditionColumn
matches 'ConditionValue', ordered by OrderColumn
, receive new shine.
The power of subqueries
Subqueries are the real lifesavers when updating rows without the privilege of ORDER BY
. They bolt down your target rows:
Notice, the power moves through the streets of IN-clause
that helps you update only the targeted rows.
ORDER BY tricks: No unique key, no problem!
Ever faced an update scenario with no identity or unique columns, yet target the top N rows? Don't fret, subqueries come to the rescue:
Nested subqueries go about their task like a well-knit spy network, filtering out the top items based on your command.
Linked
Was this article helpful?