rewrite template using more Postgres-friendly statements - AERGO-546