Optimization some SQL query function.