The Norwegian midfielder, who is on a two-year loan, opened the scoring.
Alexander Isak netted twice in two minutes, including a superb acrobatic effort, as Sociedad went 3-0 ahead.
Marcelo and Rodrygo scored for Madrid, in between Mikel Merino adding Sociedad’s fourth, with Nacho heading in late on.
The defender’s 93rd-minute goal set up a tense finish at the Bernabeu as the referee played eight additional minutes. Although Sociedad’s Andoni Gorosabel was sent off for a second yellow card, Real Madrid were unable to find the equaliser.
Real Madrid’s Vinicius Junior had a header ruled out by the video assistant referee for offside in the second half.
Odegaard, 21, who joined Real Madrid as a 15-year-old, was rewarded with a standing ovation from the home fans as he was substituted in the 64th minute.
Zinedine Zidane’s side are top of La Liga and have the best defensive record in the top flight with just 13 goals conceded from 22 games. They were unbeaten in 21 games coming into the tie.
It was the first time that Madrid have conceded four times under Zidane in more than 190 matches across two spells in charge.
“It hurts, we have to be honest, nobody likes a defeat,” said Zidane.
“Despite [trailing] 1-4, we have fought until the end, but it has not been possible.
“We must congratulate the opponent and also accept losing.”
Sociedad, who are eighth in La Liga, have won the competition just twice in their history, most recently in 1987.
The draw for the last four takes place on Friday, with Granada – who knocked out holders Valencia – and second division side Mirandes both in the pot.
Athletic Bilbao took the last place in the draw by beating Barcelona 1-0 on Thursday.
The News Editor ,Reporter at Kagadi Kibaale community Radio