The vote was originally scheduled for 2027. The right's rejection of urgent housing decrees in October prompted Sanchez to call it early.
The Socialists were on 116 seats and were unable to secure enough allies on the far left and among regional separatist parties.
With almost all votes counted, the PP had 132 seats and Vox 52 in the 350-member parliament. Together they hold a majority.
The result removes one of Europe's few leftist leaders. Sanchez is a favourite of international progressives, but his polarising status and anger over the cost of living had put his tenure at risk.
The right has blamed his successive governments for soaring housing costs. Anger over the cost of living had eroded support for Sanchez ahead of voting.
Sanchez had tried to leverage anger over a chronic housing crisis, passing measures for tenants earlier this month. Those steps did not save the left.
Final turnout surpassed 79 percent, the highest figure since 1982. That participation had not benefited the left.
One party equalled its best-ever general election result and gained 19 seats, whereas the PP and the Socialists lost five each.
Thousands of PP supporters waving red-and-yellow Spanish flags jumped for joy outside party headquarters to celebrate Sanchez's downfall.
A 65-year-old has long attacked Sanchez over corruption scandals, concessions to Catalan separatists and failing to pass a budget.
Nunez Feijoo, who ran the northwestern region of Galicia for 13 years, had projected an image of experience and competence.
Critics of the shift warned of social rollback."Our rights are being rolled back, we're going backwards with regards to abortion,"a 60-year-old said.
Sanchez had also enhanced his international profile through his virulent criticism of Israel. At home, housing costs and the cost of living decided the night.