The count was close – veteran leftist Mr da Silva polled 50.8% of votes, compared with 49.2% for Mr Bolsonaro, the far-right incumbent.
Luiz Inacio Lula da Silva has won the Brazilian election, narrowly beating Jair Bolsonaro, official figures show.
On his victory, Mr da Silva tweeted a simple picture of his hand over the Brazilian flag and the word: “Democracy.”
It is a stunning return to power for Mr da Silva, 77, whose 2018 imprisonment over a corruption scandal sidelined him from that year’s election, paving the way for then-candidate Mr Bolsonaro’s win and four years of far-right politics.
Mr da Silva’s convictions were annulled, but he faced an uphill battle, when he decided to re-run for president, with many millions of Brazilians continuing to believe he was corrupt.
After his victory was announced, he said: “They tried to bury me alive, and I’m here!”
And in his first speech to the nation as president-elect, he vowed his most urgent commitment would be to “end hunger” in Brazil.
His victory marks the first time since Brazil’s 1985 return to democracy that the sitting president has failed to win reelection.
‘Time of hope and future’
Colombian president Gustavo Petro wrote: “Viva Lula,” while Argentina’s leader Alberto Fernandez said the victory ushered in a new era “for the history of Latin America”.
He added: “A time of hope and future begins today.”
Brazil’s Supreme Electoral Court’s count showed it was a close contest – Mr da Silva polled 50.8% of votes compared with 49.2% for Mr Bolsonaro, with 98.8% of voting machines counted.
The election, in the world’s fourth-largest democracy, served as a referendum on two starkly different – and vehemently opposed – visions for Brazil’s future.
Mr Bolsonaro vowed to consolidate a sharp rightward turn in Brazilian politics after a presidency that witnessed one of the world’s deadliest outbreaks of COVID-19 and widespread deforestation in the Amazon basin.
Mr da Silva promised more social and environmental responsibility, evoking the rising prosperity of his 2003-2010 presidency, before corruption scandals tarnished his Workers’ Party.
More than 120 million Brazilians were expected to cast ballots, with the vote conducted electronically.
There are also fears Mr Bolsonaro could challenge the election results should he lose – much like former US President Donald Trump.
For months, he claimed the nation’s electronic voting machines are prone to fraud, though he never presented evidence.
As Mr da Silva prepared to give a speech at a hotel in São Paulo on Sunday evening, Mr Bolsonaro had yet to concede the election.
It was the country’s closest poll in more than three decades. Just over two million votes separated the two candidates, with 99.5% of the vote counted. The previous closest race, in 2014, was decided by a margin of 3.46 million votes.
The new president, known universally as Lula, will be sworn in on 1 January 2023.