Came up with a better query algorithm