Fix query to work in postgresql