refactored sql query building, search more flexible