The motion was backed by 82 legislators, with 170 voting against it and 97 abstaining, prompting it to fail on Wednesday.
The vote had not been expected to succeed, but it was brought to parliament by Podemos to put pressure on Rajoy’s ruling right-wing Popular Party (PP), which has been hit by a series of corruption scandals.
It was also an occasion for other opposition parties to express their differences in a highly fragmented parliament that has forced Rajoy to head up a minority government following successive inconclusive elections in 2015 and 2016.
“We are on the right track to build up an alternative majority,” Podemos leader Pablo Iglesias told Reuters news agency after the vote.
Rajoy said he was satisfied with the outcome of the vote. “It has been rejected by a wide majority and this means we will be able to keep working,” he told journalists.
The vote followed a 16-hour debate in which Rajoy faced off against Iglesias, who was proposed as an alternative candidate for prime minister, but lacked sufficient support in the lower house.
Rajoy defended his government’s record in creating jobs and boosting growth that has lifted Spain’s economy out of recession.
Iglesias and his supporters highlighted graft investigations into the funding of the ruling party. Iglesias said Rajoy would be remembered as “the president of corruption”.
Rajoy argued there were corruption cases in all parties, but that it was not the norm and no case involved members of his government.
But Rajoy has been dragged into one of the most damaging of the cases, an alleged kickbacks-for-contracts scheme. He is set to testify as a witness in the case on July 26.
Opinion polls regularly show corruption is a major concern in Spain after high unemployment.
Rajoy heads a minority government and his party, with 134 seats, counts on the support of the centrist Ciudadanos party’s 32 deputies and several others.
The leading opposition Socialist party, with 84 deputies, is considering presenting its own no-confidence motion, but on Wednesday decided to abstain rather than be seen supporting Iglesias, whom it deems to be an anti-establishment populist.
Podemos emerged in 2013 from grassroots protests that swept across the country during the five-year severe economic recession that ended that year.