The win allowed Barcelona to move six points off the top of the table whereas defeat meant Sociedad lost their place as leaders to be replaced by Atletico Madrid.
However, Barca did it the hard way.
Sociedad, without a point at Barcelona in 25 years, took the lead through Willian Jose in the 26th minute.
Jordi Alba levelled four minutes later with Frenkie de Jong adding the second just before the break.
Under-siege Barca coach Ronald Koeman played in the team which last yielded a home point to Sociedad in 1995.
The Dutchman was fearing the worst when Willian Jose scored with his right foot from close range after a Portu corner.
Alba's equaliser arrived on the half-hour mark after a fine interchange of passes between Antoine Griezmann and Pedri.
French star Griezmann hit the bar six minutes later after taking the ball past Sociedad keeper Alex Remiro.
De Jong then gave Barca a 42nd-minute lead with a right-foot drive for his first goal since February.
The goal, however, was only allowed after a VAR consultation for a possible offside.
Griezmann had back-to-back chances to increase the lead early in the second period.
Lionel Messi required treatment on a calf injury as the second half wound down before Barca goalkeeper Marc-Andre ter Stegen denied Willian Jose from long range and then Alexander Isak.