DEV Community 👩‍💻👨‍💻

rajanand ilangovan
rajanand ilangovan

Posted on • Originally published at on

How to generate Permutations in SQL?


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: 03-permutations-output.png


Let us create the test data first for the demo.

-- test data
use demo;
if object_id (N'', N'u') is not null 
drop table

create table (
    id int identity(1,1),
    city_name varchar(100)

insert into (city_name) values 

select id, city_name from

Enter fullscreen mode Exit fullscreen mode

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
declare @total_cities int = (select count(1) from;
with travel (travel_path, level) as (
    select cast(city_name as varchar(200)), 
    level = 1 
    union all
    select cast(travel.travel_path + ' -> ' + city.city_name as varchar(200)), 
    level = level + 1
    inner join travel on level < @total_cities
    where charindex(city.city_name, travel.travel_path) = 0

id = row_number() over(order by travel_path),
from travel
where level = @total_cities
order by id

Enter fullscreen mode Exit fullscreen mode

If you like this interview question, you may also like this interview question and answer series.

Top comments (0)

All DEV content is created by the community!

Hey, if you're landing here for the first time, you should know that this website is a global community of folks who blog about their experiences to help folks like you out.

Sign up now if you're curious. It's free!