After all the votes were counted, right-wing conservative historian Karol Nawrocki has been elected Poland's new president, the state electoral commission (PKW) said.
PKW said Nawrocki won 50.9 percent percent of the votes – ahead of Warsaw's liberal mayor Rafal Trzaskowski on 49.1 percent.
It's a sensational turnaround from the result of the first exit poll – published immediately after voting ended at 21:00 local time (19:00 GMT) on 1 June – that showed Trzaskowski winning on 50.3 percent to Nawrocki's 49.7 percent.
Trzaskowski had claimed victory after the first exit poll, while Nawrocki cautioned that the results were too close to call.
"We won, although the phrase 'razor's edge' will forever enter the Polish language and politics," Trzaskowski told his supporters.
His wife, Malgorzata, jokingly told the crowd: "I'm close to having a heart attack."
Nawrocki, 42, had said after the result of the first exit poll: "Let's not lose hope for this night. We will win during the night, the difference is minimal. I believe that we will wake up tomorrow with President Karol Nawrocki."
As Poland's new president, Nawrocki is likely to continue to use his presidential power of veto to block Polish Prime Minister Donald Tusk's pro-EU programme.
The result is also likely to re-energize Nawrocki's supporters, the national conservative Law and Justice (PiS) opposition, which lost power eighteen months ago, giving them renewed belief they will be able to defeat Tusk's coalition in 2027 parliamentary elections.
Tusk said following the result that he understood "the gravity of the moment" and did not intend to "take a step back".
He also announced that he will call a vote of confidence in his government in parliament in the near future.
This vote has already been seen by some as a piece of political theatre. Tusk is likely to win as it requires a simple majority - something his ruling party has.
Nawrocki supports traditional Catholic and family values, and is a strong supporter of Polish sovereignty within the EU.
He backs continued support for Ukraine, but has said he does not want to see the country joining Nato and the EU during Russia's ongoing aggression.