Replace psql + grep + wc with a single query