MOSUL, Iraq — Iraq on Monday declared “total victory” over the Islamic State in Mosul, retaking full control of the country’s second-largest city three years after it was seized by extremists bent on building a global caliphate.

“This great feast day crowned the victories of the fighters and the Iraqis for the past three years,” said Prime Minister Haider al-Abadi, flanked by his senior military leadership at a small base in western Mosul on the edge of the Old City. Iraqi forces had backed the last pockets of Islamic State militants against the banks of the Tigris River.

Al-Abadi alluded to the brutality of the battle for Mosul – Iraq’s longest yet in the fight against IS – saying the triumph had been achieved “by the blood of our martyrs.”

The nearly nine-month campaign, which was backed by airstrikes from the U.S.-led coalition, left thousands dead, entire neighborhoods in ruins and nearly 900,000 displaced from their homes.

Shortly after al-Abadi’s speech, the coalition congratulated him on the victory but noted that parts of the Old City still “must be back-cleared of explosive devices and possible ISIS fighters in hiding.” ISIS, ISIL and Daesh are alternative acronyms for the Islamic State group.

Earlier in the day, airstrikes pounded the last IS-held territory on the western edge of the Tigris, Humvees rushed the wounded to field hospitals and soldiers hurriedly filled bags with hand grenades to ferry to the front.

Iraqi troops had slowly pushed through the narrow alleyways of the Old City during the past week, punching holes through walls and demolishing houses to carve out supply routes and fighting positions.

For days, the remaining few hundred militants held area measuring less than a square kilometer, and Iraqi commanders described victory as imminent.

Al-Abadi also visited Mosul on Sunday, congratulating the troops on recent gains but stopping short of declaring an outright victory as clashes continued.

The drawn-out endgame in Iraq’s fight for Mosul highlighted the resilience of the extremists and the continued reliance of Iraqi forces on air support to retake territory.

Iraqi commanders said gains slowed to a crawl in recent days as IS fighters used their families as human shields. As the battle space constricted, the coalition began approving airstrikes, dropping bombs of 200 pounds or more on IS targets within 50 yards of friendly forces.

Over the campaign, the Iraqi special forces who largely led the assault have faced casualty rates of 40 percent, according to a report in May.

As the Iraqi army celebrated imminent victory on Sunday, Muhammad Abdul Abbas, a 20-year-old soldier, said he lost 15 close friends fighting for Mosul.

“Honestly, all this death and all this destruction, I don’t believe it was worth it,” he said.