Rewrite functions to handle sort() command in query