The 31-year-old Briton, under pressure after failing to top the times in three practice sessions, found the pace he needed in another desultory exhibition of the new qualifying format ahead of Sunday's Bahrain Grand Prix.
Read: Bahrain GP Qualifying - As it happened
The three-time champion said: "It's obviously not been a smooth weekend in terms of pace for me and Nico (Rosberg) has been right on it, but I was able to put a lap together, my best of the weekend, and it mattered for me at just the right time."
LH: "Big thanks to all at the track and back at the factories for this car. It’s very special" #F1 #BahrainGP #Quali pic.twitter.com/3onvQus9BK
— MERCEDES AMG F1 (@MercedesAMGF1) April 2, 2016
Hamilton's lap in 1minute and 29.493 seconds was the fastest lap recorded at the Sakhir track and it rescued him after an error had marred his first fast lap in Q3.
RECORD BREAKER
— Formula 1 (@F1) April 2, 2016
1:29.493 = fastest lap ever at Bahrain#Quali #BahrainGP ???? pic.twitter.com/n8iFMwZheo
Rosberg, who won the season-opener in Australia and looked set for pole position himself, wound up second fastest behind Hamilton in the second Mercedes.
Ferrari fall short in Q3
Rosberg will start ahead of the third-placed Ferrari of four-time champion Sebastian Vettel.
WATCH: Alonso gatecrashes live TV, slams F1 pundit
Kimi Raikkonen was fourth in the second Ferrari ahead of Daniel Ricciardo of Red Bull, Valtteri Bottas and his Williams team-mate Felipe Massa.
#Seb5 'The car feels good, it's a long and interesting race, we'll see' #BahrainGP #Quali #redseason pic.twitter.com/BechMcld4E
— Scuderia Ferrari (@ScuderiaFerrari) April 2, 2016
Nico Hulkenberg was eighth for Force India ahead of Romain Grosjean of the new American Haas team with Dutch teenager Max Verstappen 10th for Toro Rosso.n
Bahrain Grand Prix starting grid:
1. Lewis Hamilton (Britain) Mercedes
2. Nico Rosberg (Germany) Mercedes
3. Sebastian Vettel (Germany) Ferrari
4. Kimi Raikkonen (Finland) Ferrari
5. Daniel Ricciardo (Australia) Red Bull - TAG Heuer
6. Valtteri Bottas (Finland) Williams-Mercedes
7. Felipe Massa (Brazil) Williams-Mercedes
8. Nico Hulkenberg (Germany) Force India - Mercedes
9. Romain Grosjean (France) Haas - Ferrari
10. Max Verstappen (Netherlands) Toro Rosso - Ferrari
11. Carlos Sainz Jr (Spain) Toro Rosso - Ferrari
12. Stoffel Vandoorne (Belgium) McLaren
13. Esteban Gutierrez (Mexico) Haas - Ferrari
14. Jenson Button (Britain) McLaren
15. Daniil Kvyat (Russia) Red Bull - TAG Heuer
16. Pascal Wehrlein (Germany) Manor - Mercedes
17. Marcus Ericsson (Sweden) Sauber - Ferrari
18. Sergio Perez (Mexico) Force India - Mercedes
19. Jolyon Palmer (Britain) Renault
20. Rio Haryanto (Indonesia) Manor - Mercedes
21. Felipe Nasr (Brazil) Sauber - Ferrari
22. Kevin Magnussen (Denmark) Renault