File photo: People wait in line to cast their ballots during local elections in Barcelona, Spain, Sunday, May 28, 2023. AP
Widely seen as a dress rehearsal for a general election that had been expected at the end of the year, Sunday's polls saw the main opposition conservative Popular Party chalk up the largest number of local votes.
The PP also scored significant gains at a regional level, seizing six regions that had been under Socialist control.
In a televised address, Sanchez said he had informed King Felipe VI of his decision to dissolve parliament and "call a general election" on July 23.
"I have taken this decision in light of the results of yesterday's elections," he said.
"As the head of the government and of the Socialist party, I take responsibility for the results and I think it is necessary to respond and submit our democratic mandate to the popular will."
The polls will come shortly after Spain takes over the rotating presidency of the European Union on July 1.
In office since 2018, Sanchez has faced several obstacles: voter fatigue with his left-wing government, soaring inflation and falling purchasing power in the eurozone's fourth-largest economy.
He has struggled to contain the fallout from repeated crises between the Socialists and their hard-left coalition partner Podemos.
The PP secured just over seven million votes (31.52 percent) in the municipal elections, compared with nearly 6.3 million for the Socialists (28.11 percent).
The figures are a major blow for Sanchez, whose Socialist party governs the eurozone's fourth-largest economy in coalition with the far-left Podemos.
"We have won a clear victory and Spain has taken the first steps towards a new political era," said the jubilant opposition leader Alberto Nunez Feijoo, head of the right-wing Popular Party (PP) in a victory speech early on Monday.
But the PP will only be able to govern in several regions with the support of the far-right Vox, also a winner in Sunday's polls -- which poses a major headache for Feijoo.
Vox, the third-largest party in parliament, is hoping to become an indispensable partner for the PP -- both at a regional level and, ultimately, nationally.
Aware that the key to winning the general election is conquering the centre, Feijoo has sought to moderate the PP's line while also keeping Vox at a distance.
In Madrid, the PP was celebrating a double win, with its hardline regional leader Isabel Diaz Ayuso winning an absolute majority meaning she will no longer have to rely on Vox for support.
And the capital's PP mayor, Jose Luis Martinez-Almeida, was also reelected with an absolute majority.