Bilbao dominated the opening stages of the match and went ahead through Ibai Gomez's vicious volley at the half-hour mark.
But Antoine Griezmann headed Sociedad level four minutes later, and striker Imanol Agirretxe then gave the visitor the lead in the 66th minute thanks to an error by goalkeeper Raul Fernandez. Substitute Carlos Vela added another goal 10 minutes later.
Sociedad's first win at Bilbao since 2001 provisionally lifts it into fifth place in the Spanish standings. Philippe Montanier's side is on a seven-game unbeaten streak and has only one loss in the past 15 rounds.
"It had been a long time," said Sociedad's veteran midfielder Xabi Prieto. "We came in playing well so we knew it was possible, and we are leaving in great spirits."
Inaugurated in 1913, San Mames is scheduled to be torn down after 100 years and replaced by a new stadium at the end of this season.
The first Basque Country derby was at the venue in 1929. The final tally for derbies rests at 37 wins for Bilbao, 12 for Sociedad and 17 draws.
Prieto remained cautiously optimistic about his team's chances of making a top-six finish and qualifying for the UEFA Champions League or Europa League next season.
"We will see. We are playing well," he said. "We are near the top now and on a very good run."
Bilbao could not have asked for a better start with Gomez smashing Jon Aurtenetxe's cross into the top of the net after Aritz Aduriz and Mikel San Jose had both come close with headers.
Sociedad responded in perfect fashion with Chori Castro picking out Griezmann floating free at the far post to turn his lobbed pass into the net.
Both defences then appeared to have settled down until Fernandez, Bilbao's little-used goalkeeper in his second start, gifted Sociedad the goal that proved to be the winner. Fernandez failed to pull in or punch out a routine cross that bounced off his chest, letting Agirretxe send the ball ricocheting off both players before it trickled over the goalline.
Vela sealed the result with a shot just inside the upright for his 11th goal of the season.