PostgreSQL – How to Show All Variations of 2 Characters

postgresql

How would I do this in postgres :

Lets say I have an x and a y and I want to show all possible combinations :

xx
yy
xy
yx

How can I make postgres do this for me ?

Best Answer

with characters (c) as (
  select unnest(string_to_array('xy', null))
) 
select *
from characters c1
  cross join characters c2

Edit:

Apparently this does not work in 8.4, but the following should:

with characters (c) as (
  select unnest(regexp_split_to_array('xy', ''))
) 
select *
from characters c1
  cross join characters c2

Thanks to Bruno for testing this.