Ruud van Nistelrooy scored with a spectacular volley to put Real in front before Fernando Morientes levelled against his former club soon after the break.
Beckham, fit again after a knee injury, came on as a second-half substitute and provided a trademark free kick for Sergio Ramos to head the deciding goal in the 73rd minute.
Real climbed to second in the table on 57 points, two behind leaders Barcelona who visit Villarreal on Sunday.
Third-placed Sevilla (55) host Athletic Bilbao on Sunday. Valencia (53) are fourth.
Real Sociedad kept up their chances of avoiding relegation with a 2-0 home win over Atletico Madrid.
Serbian striker Darko Kovacevic poked in Savio's cross for the opener before Brazilian forward Savio made it 2-0 with a volley six minutes from time.
Atletico had midfielder Peter Luccin and defender Fabiano Eller sent off in the second half.
The Basque side, who claimed their third win in four, remained second bottom with 27 points, three from safety. Atletico stayed sixth with 50.
REAL DESIRE
Real showed more desire to get forward early at the Bernabeu and took the lead after a sweeping move in the 18th minute.
Put clear down the left, fullback Miguel Torres crossed and Dutch striker Van Nistelrooy lashed in a volley from the edge of the area.
Real midfielder Fernando Gago was lucky to be on the pitch at halftime.
Having already received a yellow card, the Argentine's mistimed tackle on Miguel went unpunished before the interval.
Winger Joaquin created the equaliser for Valencia in the 52nd minute, beating his man down the right and crossing low for an unmarked Morientes to steer the ball inside the far post.
Beckham came on as a substitute in the 65th minute and eight minutes later his free kick set up Ramos's winner.
Real went close to adding a third through Van Nistelrooy and Robinho, though keeper Iker Casillas had to be sharp to push out an Asier del Horno volley near the end.
More from rediff