While maybe a pretentious title, I’ve always enjoyed getting and giving what I call SQL Challenges. It is basically a short explanation for what you should do with pure SQL and some limitations to how you can do it and then you get to try to come up with a solution. It is frequently more about being able to do it, than it is that one would actually implement it that way. The idea is that you lear new ways to work with SQL or think about SQL and that will help you write better SQL for things you’d actually do in your application.
The “I” is in case this is something someone likes and I think of other ones in the future. It the first one isn’t I, then the second one cannot really be II, right?
To the challenge. I thought of this after reading a question on a forum a while back. The final more performant solution was not SQL, but I thought it was interesting to actually do this in SQL. In case anyone recognizes this from the forum, please don’t link to it. I will link to it when I show my version of a solution to this challenge. The challenge is about challenging yourself to learn something, it’s not about winning over everyone else. Learning is a personal adventure, not some form of competition.
The problem this challenge poses is to find all combinations of the letters in a string. Lets say that it is always three letters in this string to reduce complexity and make it more possible to solve it with pure SQL.
If the string contains ABC, you’d expect the query to return:
ABC
ACB
BAC
BCA
CAB
CBA
If it returns more or less, then you have not managed to get just the combinations. AAA, for example, is not a valid answer as there is just one A in the input.
You should limit your SQL to not use analytical functions at all, and not PL*SQL. The SQL should be written such that you only need one SQL statement and no other objects are created to support your single SQL statement.
Also consider that you will want a solution that is possible to rewrite for at least 8 letters instead of the three you’re writing the SQL for. Several ways of solving this will make the statement too large soon after three letters.
Hopefully this is complicated enough to be a challenge, I know it took me quite some time to figure out how I could solve it.