Barca had edged past Leganes earlier in the day to open up a three-point lead over its bitter rival but Zinedine Zidane's side registered a second consecutive league win to rejoin it on 28 points.
Willian Jose took advantage of a woeful mistake by Sergio Ramos to put Sociedad ahead in the second minute but Karim Benzema restored parity before half-time.
Federico Valverde, who opened his Madrid account in the 4-0 win over Eibar before the international break, completed the turnaround shortly after the restart before Luka Modric sealed all three points 16 minutes from time.
Gareth Bale was introduced as a second-half substitute by Zidane and was greeted by a mixture of whistles and cheers from Madrid supporters after holding a banner following Wales' win over Hungary in midweek that read: 'WALES. GOLF. MADRID…IN THAT ORDER'.
Sociedad was gifted the lead inside the opening two minutes thanks to a moment of madness from Ramos.
The Madrid captain's backpass to Thibaut Courtois was cut out by Willian Jose, who took a touch past the Belgium international and rolled into an empty net.
Alex Remiro got down well to keep out Ferland Mendy's powerful drive soon after, while at the other end Courtois had to beat away Madrid loanee Martin Odegaard's fierce effort.
Madrid conjured up a scarcely deserved leveller eight minutes before the interval when Benzema used his chest to steer home Luka Modric's free-kick from six yards.
Madrid started the second half with a spring in its step and forged ahead in the 47th minute when Valverde's shot from just outside the penalty area took a wicked deflection off Mikel Oyarzabal to wrongfoot Remiro.
Bale shrugged off his hostile reception to play a part in Madrid's third. His cross from the right was headed down into Modric's path by Benzema and the Croatian lashed a fine half-volley past Remiro to add gloss to the scoreline.