Optimized code in retrieving records