I also forgot to say that this is postgres specific. Writing an oracle version is an exercise left to the reader.