Fix sort bug in the query class