Martin had initially claimed provisional pole with a lap record of his own but Bagnaia went more than two-tenths of a second faster with a time of one minute and 30.031 seconds to claim his second pole at the circuit in as many weeks.
Bagnaia is set for his 100th race in the premier class while Ducati are chasing their 100th victory, and the Italian could only smile after he nearly went below the 1:30 mark on his qualifying lap.
"Yesterday I said it could be difficult for the temperature and it was more or less the situation, because it was difficult to push like we wanted in the left corners," he said.
"But I'm very happy because being in both positions is the most important thing and we stand in the best position possible to try to win this afternoon (in the sprint)."
Misano, where the San Marino Grand Prix was also held two weeks ago, is hosting two races this year after MotoGP cancelled a scheduled race in Kazakhstan at Almaty's Sokol circuit due to flooding across the region.
Pramac Racing's Martin leads Bagnaia in the championship by seven points and he will look to redeem himself at the Misano circuit where his gamble to switch bikes during the San Marino Grand Prix backfired and he finished 15th.
"In terms of pace, Pecco (Bagnaia) and I are so close," Martin said.
Brad Binder had initially gone third fastest for KTM but Bagnaia's factory Ducati teammate Bastianini clinched third on the grid on home turf towards the end of the second qualifying session.
MotoGP rookie Pedro Acosta was fifth fastest for Tech3 while Marco Bezzecchi of VR46 Racing completes the second row.
Marc Marquez won the San Marino Grand Prix but he crashed in Q2 yet again and could not set a faster lap after swapping bikes, with the Spaniard coming in seventh-fastest and set to start on the third row.