Real Sociedad took the lead five minutes into the game with Ander Barrenetxea scoring on a rebound.
Former Madrid player Take Kubo assisted Barrenetxea's goal.
Federico Valverde equalized for Real Madrid at the start of the second half with his season's first goal.
Joselu regained the lead for Real Sociedad with a header, assisted by Fran Garcia.
Real Sociedad won the game held at Bernabeu Stadium, overcoming an early goal concession.
Real Madrid will host Union Berlin in the Champions League and visit Atletico Madrid in their league derby.