Bottas, on soft tyres, was the early pacesetter, but a mistake on turn two led to Hamilton overtaking him as practice leader, before the Finn bounced back and finished top of the classification with a time of 1.42.742.
With only one lap to complete after the red flags, Hamilton made the greater improvements to take pole position over Bottas by 0.434 of a second.
Valtteri Bottas slotted his Mercedes AMG Petronas vehicle into second on the grid with Kimi Raikkonen outqualifying Sebastian Vettel at Scuderia Ferrari for the second time in three races. Qualifying in second place should be seen as a good day's work, but after leading Hamilton in the three free practice sessions, Bottas didn't see things that way.
We have to say that we saw very exciting qualifications in Baku and the Mercedes driver managed to win this pole position in the last lap, leaving behind his team-mate Valtteri Bottas, who came second. I wasn't quite comfortable with the tire temperatures. Ferrari's Kimi Raikkonen was second. "The first lap I easily had the time, I just made a mistake in the last corner, so there was a lot of pressure". Lewis had a good lap.
"Yesterday we were at a bit of a loss and we had to make a lot of changes overnight", said Hamilton, who was 10th in P2. "This morning didn't help but it's not an excuse".
The narrow confines of the Baku City Circuit have caused a number of problems for drivers here with Turn Eight - the strip of tarmac which measures just 7.8 metres in width - the scene of two crashes. The Spaniard won't be too anxious though, as he will start from the pit lane anyway with a 40 place grid penalty.
Lakers Select Lonzo Ball With No. 2 Overall Pick
The Sixers had acquired the top slot in a trade with the Boston Celtics, who now have the third pick. The L.A. native Ball gets his wish as he will continue to play in his hometown for the Lakers.
Hamilton topped Q2 ahead of Bottas and Vettel.
The Force Indias of Sergio Pérez and Esteban Ocon were sixth and seventh respectively, whilst rookie Lance Stroll outqualified his Williams team-mate Felipe Massa to bag eighth spot.
Accepting responsibility for his qualifying result, Vettel said, "In the end, I was alone and had no tow in the last sector".
"Obviously it's better than where I was before. A big thank you to the team who stayed late last night to get the auto to where it is today - they did a fantastic job".
"I thought the hunger might drop off after I matched him (Senna)", Hamilton said.
However, beleaguered McLaren-Honda will be spared a back-row lockout by the luckless Jolyon Palmer, who was unable to take part in qualifying after an engine fire in his Renault in final practice.