Should move this outside the for loop around granularities. You'll reduce the number of db calls.