rewrote SQL that counts rows