changing agap query for postgresql