Query Exercise Answers: Returning Routes in the Right Order

In your most recent Query Exercise challenge, I gave you these two tables:

And your assignment was to return a result set that started with the first station by StationPhysicalOrder, and then move through the rows in StationPhysicalOrder – unless there was a matching StationRoutingOverride row, in which case you needed to follow that routing instead. A successful result would look like this:

The Dude Abides

In the challenge, I explained that I wasn’t actually able to solve it without using procedural code: looping through the rows one by one with a while loop or cursor, I knew y’all would be able to do it because the audience includes some real T-SQL wizards. All of y’all who solved it in the comments should officially feel Smarter Than Brent Ozar™.

An Against-the-Rules (But Real-World) Answer First

Brian Boodman first posted this answer, and then apologized for not reading the instructions about not using loops. However, I wanna show his answer because it was the first kind of answer I thought about doing at the client – because after all, this kind of brute force programming works, it’s just not elegant:

When I was working with the client, I said that if I had to get across the finish line in 15-30 minutes, this is the kind of solution I’d write. As it happened, this query would end up getting called millions of times per minute, and every millisecond of CPU would count, so I didn’t wanna do this. But I’m showing it here because it works, and I bet a lot of y’all went to this in your head first too – I did!

Using CTEs

The first answer was Ilya Makarov’s. Even though his was the fastest, he managed to work in cool examples of T-SQL features like LEAD, OUTER APPLY, and CASTing an integer for safety purposes:

Ilya used two CTEs: the first fetches the first station only, and then the second CTE joins to it to get all subsequent stations.

I got a chuckle out of Ilya’s answer because at the client, one of the developers had said, “Could we use OUTER APPLY to do this?” and my honest answer was, “Maybe, but I don’t use that a lot, and to get it right is going to take more time than we have here.” Hats off to Ilya (and the other commenters who banged out good answers.)

Similarly, Gregg Dodd used a recursive CTE, and he wrote a blog post about how he did it.

Michael Bogdanov’s answer came in next, managing to do it with a single CTE plus OUTER APPLY:

The first SELECT grabs the first station in the list, the one with the minimum order.

The second SELECT – still inside the CTE – queries back to the CTE itself. The first time it’s executed, it will only select the minimum row, then it’ll join to Stations again to get the next physical order. Then the OUTER APPLY also tacks on the overrides table.

Function-Based Answer

Michael J. Swart handled the recursion by using a user-defined function to fetch the next station for a route:

But then to put icing on the cake, Swart added another answer that uses string stuffing. I have to confess that this one was my favorite out of all of ’em because it was so out-of-left-field. I actually blurted out loud, “OH WOW!” when I walked through his code, hahaha.

All of the above answers get the job done! Good work, folks. Hope y’all had fun with that challenge – that was a little harder one than usual, for me at least!

Previous Post
SQLBits Added More Capacity to My Workshop! Move Quick.
Next Post
[Video] Office Hours at the Barcelona Pavilion

5 Comments. Leave new

  • Swart’s string stuffing is amazing

    Reply
  • Michael J Swart
    June 11, 2025 7:57 pm

    Hahaha. Thanks. The string answer is a bit fragile, but it was written using the “rule of cool”. I wouldn’t check it in for work, but it was perfect to use as a comment on a friend’s blog post.

    Reply
  • I forgot about this exercise. I tried it when he first posted, then bailed on it when I misread the initial directions. I tried another solution today (rCTE-based), and then decided to throw a stupid amount of data at it to see how it performed. 1M rows in Stations and 500 Overrides. I was actually impressed that mine completed. 🙂

    I’ll have to try to remember to blog about what I did this evening.

    Thanks again, Brent, and to everyone else who participated and shared their results. This was a lot of fun.

    Reply
  • Hi Brent, FYI this is a concept from CS called Linked Lists. In the field of DBAs it’ll be pretty niche, but I thought I’d at least put the term in the comments in case anyone wants to go looking for more.

    I found the exercise pretty useful in learning about recursive CTEs. I had a quick chat with Copilot which got me like 80% of the way there: https://copilot.microsoft.com/shares/Q61w1xzL6NQP82QZheFGT

    After which the exercise was reduced to constructing the linked list table, which was relatively trivial.

    Reply
    • Yep, I’m quite familiar with linked lists, but to participate here, you’ll want to follow the instructions in the original post and show your work. Cheers!

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.