Sorry if reply is shorter than I would like due to hand, but the dynamic aspects I have encountered have been solved by case when as mentioned, boolean expressions on parameters (where $1 is true or id = $2), or in the worst cast just not caring about DRY in this scenario. Also I use json_agg etc for ORM-like mapping to arrays and objects. I do some other tricks too like bypassing a bunch of redundant and slow parsing steps by sending the result in certain queries back to app server as a single text column that is in JSON (this is via wrapping queroes, not manually) so it can send that to the client. No db driver parsing, converting to objects, back to JSON, etc etc.