Fix build in postgres

Wrong api and different sql ordering were causing failures in postgres