Optimized query search so its O(n) instead of O(n^2)