Fixing the bugs in the query function