Avoiding to run sql multiple times