Fixes sql query for postgresql