Socialist party leader Pedro Sanchez is set to become Spain's new prime minister after a no-confidence vote in parliament Friday unseated Mariano Rajoy's conservative government.

Sanchez, the leader of the largest opposition party, could be sworn in as early as Saturday and appoint his Cabinet next week.

To prevent a power vacuum after a no-confidence motion, Spanish law makes the motion's author — in this case, Sanchez — the country's new leader as soon as the king swears him in.

The end of Rajoy's more than six-year reign as Spanish prime minister was the first ouster of a serving leader by parliament in four decades of democracy.

Rajoy went to shake hands with Sanchez after the result was announced.

The reputation of Rajoy's Popular Party's was badly damaged by a court verdict last week that identified it as a beneficiary of a large kickbacks-for-contracts scheme.

Sanchez saw that as his opening and managed to muster enough support from smaller parties to send him to La Moncloa palace, the seat of government in Madrid.

Sanchez, 46, takes the helm of the 19-country eurozone's fourth-largest economy at a time when the European Union faces numerous challenges, including the United Kingdom's departure from the bloc and migrants continuing to enter the continent from North Africa.

Sanchez and his party are staunch supporters of the EU and the continent's shared currency.

The Madrid stock exchange was up nearly 1.6 percent after Sanchez won the vote, earning a standing ovation from his party's lawmakers.

Sanchez, who will be Spain's seventh prime minister since the country's return to democracy in the late 1970s, arrives in power after a spectacular turnaround in his political fortunes.

He was ousted by his own party's heavyweights in 2016 over back-to-back losses in general elections and after he tried to block Rajoy's bid to form a government.

The former economics professor regained the Socialists' leadership last year.

The incoming prime minister has outlined that his priorities will be social issues before calling elections, though he hasn't said when there might be a vote.

He faces a tough time, however, catering to demands from small nationalist parties whose votes he captured in the no-confidence motion.

The support of leftist and nationalist parties for ousting Rajoy won't necessarily lead to parliamentary backing for Sanchez's government and could produce a political stalemate.