Geneating postgres queries with chaining + sort