queryDB function optimization. Making it more robust.