Optimize count queries

Use nested selects to count the number of rows on server and avoid pointlessly
sending 500 rows to apaches.

Change-Id: I08182b7626dcf0509d1dc5f5aa8e87814c153acc
Merge "Optimize count queries"