change sql query to be compatible with postgresql