In his brief verdict, Judge Mohamad Zabidin Diah said that he could not rely on controversial DNA evidence submitted by the prosecution in the case lodged by Anwar's aide Mohamad Saiful Bukhari Azlan.
"Thank God, justice has been served," Anwar said after being cleared of the charge while pledging to topple the government in national polls expected to be held this year.
"In the coming election, the voice of the people will be heard and this corrupt government will be toppled from its pedestals of power," he added in a posting on Twitter.
Chaos followed the surprise decision at the Kuala Lumpur High Court where Anwar - a former deputy premier who was sacked and convicted on separate sodomy charges in 1998 - was mobbed by his family and opposition politicians.
Thousands of supporters who had gathered outside under heavy security since before dawn, many in Muslim skullcaps or Anwar masks, erupted into cheers and punched their fists in the air.
The verdict in the long-running trial defied the expectations of many political observers and even Anwar himself, who had said the government of Prime Minister Najib Razak was intent on eliminating him as a political threat.
"Malaysia has an independent judiciary and this verdict proves that the government does not hold sway over judges' decisions," said Information Minister Rais Yatim.
Tensions spiked briefly outside the court as two people were injured in at least three small blasts, with police blaming firecrackers for the explosions that damaged a motorcycle and shattered the window of a van.