SQL Query to Resequence Data

Let's say I have the following data in a table:
Description  Sequence
-----------  --------
Apple         1
Turnip        2
Orange        3
Pear          4
Banana        5

Open in new window

If I then delete "Turnip" my data would look like this:
Description  Sequence
-----------  --------
Apple         1
Orange        3
Pear          4
Banana        5

Open in new window

What's an easy way to renumber the sequences so I don't have a gap and the resulting data looks like this:
Description  Sequence
-----------  --------
Apple         1
Orange        2
Pear          3
Banana        4

Open in new window

LVL 22
Russ SuterSenior Software DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Daniel ReynoldsSoftware Applications Developer / IntegratorCommented:
using the derived table approach in the following linked solution would probably be the best solution for you.

Credit to KM

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Scott PletcherSenior DBACommented:
It depends.

If you're only deleting (or adding) a single row, it's easiest to just adjust the other sequence values:

DECLARE @sequence_to_delete int

--this value could instead come from an OUTPUT statement on the DELETE,
--if you need to delete by name
SET @sequence_to_delete = 2

WHERE @sequence_to_delete = 2

SET sequence = sequence - 1
WHERE sequence >= @sequence_to_delete
Russ SuterSenior Software DeveloperAuthor Commented:
That mostly works but I found this which is easier.

      [Fruits].[Sequence] = [Fruits].[NewSequence]
      ROW_NUMBER() OVER (ORDER BY [Fruits].[Sequence]) AS [NewSequence]
) AS [Fruits]
ste5anSenior DeveloperCommented:
The easiest solution: Don't use a sequence column at all. Use ROW_NUMBER() to calculate it on the fly.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.