"The enemy made a hasty withdrawal, leaving behind 31 hostages, among them 12 youngsters," Brigadier General Restituto Padilla told Reuters.
He said another 20 civilians who were trapped in the area because of the crossfire were also rescued.
Police said about 300 armed men from the Bangsamoro Islamic Freedom Fighters (BIFF) stormed the school early on Wednesday. Padilla, however, said later only about 50 terrorists were involved.
Military officials were initially not certain if any hostages were taken and whether they included children.
Community leaders in the area were called in to help in negotiations to rescue the hostages, Padilla said.
"It's over ... but we're also on guard because they might carry out other attacks," said Padilla.
Abu Misry Mama, a spokesman for the BIFF, told Reuters that the terrorists had taken civilians to a safe place, away from any crossfire, and did not intend to hold them hostage.
Both Pigcawayan and Marawi are on the large southern island of Mindanao.
Some members of the BIFF have joined fighters from two more powerful Islamist factions, the Maute group and Abu Sayyaf, who occupied the town of Marawi a month ago and have been battling government forces there since.
But Padilla said the incident at Pigcawayan was not related to the fighting in Marawi.
"This has come from a group that has long committed harassments," he said.
The seizure of Marawi and the dogged resistance by the rebels there who have pledged allegiance to ISIS has alarmed Southeast Asian countries.
Government fear ISIS, on a backfoot in Iraq and Syria, is trying to set up a stronghold in the Muslim south of the mainly Roman Catholic Philippines that could threaten the whole region.