Fixed SQL query for PG compatibility