The Talmud, Yoma 22b asks: Why weren’t the Kohanim counted by a headcount (why were their fingers counted)? Rabbi Yitzchak said: It is forbidden to count the people of Israel through a head count, even for the purpose of a mitzva for it is written in Shmuel Alef 11:8: “He counted them through pottery shards.” According to Rav Ashi we derive the prohibition from Shmuel Alef 15:4: “Saul had all the people summoned and he counted them through lambs.”
We see from here that even when preparing for war, King Saul counted the people indirectly.
The Gemara continues: Rabbi Elazar said: Whoever counts the people of Israel transgresses a negative commandment for it is stated in Hoshea 2:1 “The number of the children of Israel will be like the sand of the sea which cannot be measured.”
Why does the Gemara quote the prohibitions from the Neviim (Prophets) rather than from the Torah (Shmot 30:12) “When you take a census of B’nai Yisrael according to their numbers, every man shall give God an atonement for his soul (a half shekel) when counting them, so that there will not be plague among them when counting them.” ? According to the Maharsha, this pasuk in Shmot does not necessarily address future generations. It may have only been directed to the generation that sinned with the golden calf who needed atonement.
In Parshat Bamidbar (Bamidbar 1:2) there is no mention of the half shekel: “Take a head count of the entire congregation of B’nai Yisrael according to their families to the house of their fathers counting the names of all males individually.” Rashi and Ramban insist that this was done with the half shekel like in Shmot. Abravanel states that this time the count was taken without the half shekel.
According to Sefer HaChinuch, when the Mishkan and Beit HaMikdash stood, once a year the half shekel was collected to help pay for everything that was needed for the continual and additional burnt offerings.
At the end od Shmuel Bet, King David insisted that Yoav the captain count the people. Yoav didn’t want to count them but King David insisted so Yoav counted them. Afterwards, Kind David repented but God sent a plague that killed 70,000 men.
Abravanel explains that King David’s problem was that he counted the people for the wrong reasons. He was counting the people to pride himself in front of his enemies.
We learn from here that we shouldn’t count people for no reason.
The question remains, can we count people in times of necessity?
When necessary, we can count indirectly. In other words, you can count kipot, hats or jackets the same way that the fingers of the Kohanim were counted. In this way we have a clear picture of who is there without counting heads.
When counting to see if there are ten people for a minyan, words from the verse “Hoshia et amecha uvarech et nachlatecha ureim vinasem ad olam” are used instead of numbers. You only have a minyan once you have recited the entire verse!