Added check for sorting query before using variable