Ordering Rows Using a User-Defined Order

By Sean Baird on 01 September 2000 | 3 Comments | Tags: ORDER BY


Jonathan writes: "How would I go about ordering results using a specified order in order to offset and limit the results. Say I have non-unique ids, (23, 12, 98, 3) and I need to return rows that contain these ids in the order I specified above. How could I do this without using any extra queries or sub-queries?

Jonathan -

Thankfully, you didn't say "How can I do this without using any extra tables", because that would have been trickier :o)

Since SQL doesn't natively provide this sort of ordering, you need to use another table that contains your desired key order and join to it. Something like this:

CREATE TABLE Sorter (
      KeyID int,
      SortOrder int
)

INSERT Sorter VALUES (23,1)
INSERT Sorter VALUES (12,2)
INSERT Sorter VALUES (98,3)
INSERT Sorter VALUES (3,4)

SELECT ID, yada
FROM foo
      JOIN Sorter
            ON foo.ID = Sorter.KeyID
ORDER BY Sorter.SortOrder

That should do the trick.
-SQLGuru

Discuss this article: 3 Comments so far. Print this Article. This page has been read 26,415 times.

If you like this article you can sign up for our newsletter. We send it out each week that we post a new article. There's an opt-out link at the bottom of each newsletter so it's easy to unsubscribe at any time.

Email Address:

Email ThisSubscribe to this feedKick itSave to del.icio.usView blog reactions

Related Articles

Dynamic ORDER BY (22 January 2001)

Other Recent Forum Posts

Find all DBOs (5 Replies)

reg delegates and events (3 Replies)

Online pharmacy! (0 Replies)

Online pharmacy! (0 Replies)

Online pharmacy! (0 Replies)

Foreign Key References Invalid Table (3 Replies)

nothing in tray (5 Replies)

SQL Server Job fails (8 Replies)

Subscribe to SQLTeam.com

Weekly SQL Server newsletter with articles, forum posts, and blog posts via email:

SQLTeam.com Articles via RSS

SQLTeam.com Weblog via RSS

- Advertisement -

SQL Server Jobs