How to generate Permutations in SQL?
Question:
You are planning to go for a summer vacation and finalized the cities you want to visit. But you have not finalized in which order you want to visit them yet.
Write a SQL query to list out all different possible order you can visit these cities.
Note that you don’t want to visit the same city again and you don’t want to skip any city in your travel plan either.
Expected output:
Let us create the test data first for the demo.
Solution: 1
This solution is implemented using the Recursive CTE in SQL Server. If you are using other database engines, you can implement it in similar way.
Solution: 2
This solution is implemented using a bitwise exclusive or ^ in recursive CTE. I learned this one while I was checking for few other way to implement permutations in SQL.
If you like this interview question, you may also like these scenario based interview question and answers.