Azarenka, who retained her Australian Open crown last month, overcame a second-set fightback from the American to triumph 7-6 (8/6) 2-6 6-3.
Despite the loss, Williams will return to number one spot for the sixth time when the new rankings are released on Monday.
At 31, she is the oldest player ever to hold the position.
It was Azarenka's first win over Williams since 2009 and marginally improved her head-to-head record to two wins from 13 meetings.
She had to stave off a set-point to claim the opening set on a breaker and although she was overpowered by Williams in the second, she impressively regained her composure to establish a 3-0 deciding-set advantage on her way to wrapping it up.
"I just wanted to fight and give myself every opportunity to get back," said Azarenka in remarks reported on the BBC website.
"I told myself, 'You have to keep it together, you have to do something otherwise Serena's on a roll and she's going to bring her A game'.
"I had to really step up my game and I'm glad that I could turn it around, stay tough and focused."