Djokovic saved seven break points in the final game and converted on his third match point of the night to secure the win over the defending champion, moving one victory ahead of Rafael Nadal in Masters tournament victories.
It was Djokovic's second title in Madrid, and fifth of the year this season. He reached 33 wins, the most on tour in 2016.
The loss allows Roger Federer to surpass Murray for No.2 in the world on Monday. It also kept the British player from winning his 12th Masters 1000 title, and second on clay.
"Congratulations to Novak on a great win, there's been a lot against me in the last few years," Murray said on court with a smile. "He's doing great things."
Djokovic dominated the first set but it was even from then until the end, with both players faltering on decisive moments. Djokovic hit 25 winners but had as many unforced errors, while Murray had 10 aces in the match that lasted 2 hours, 6 minutes at the "Magic Box" center court in the Spanish capital.
The thrilling last game finally ended when Murray sent a forehand into the net, giving Djokovic his 15th straight win against top-10 opponents, a streak in which he has lost only two of 35 sets.
The top-ranked Serb has won four of the last five Masters titles, including three this year. He had already won in Indian Wells and Miami, and had also clinched the Australian Open in a final against Murray.
The nine Masters tournaments of the season are elite tournaments ranked just below the four Grand Slams.
It was Djokovic's first clay-court tournament since being upset by 55th-ranked Jiri Vesely in the second round in Monte Carlo last month.
Djokovic had won in Madrid for the first time in 2011.
In addition to beating home-crowd Nadal in straight sets in last year's final, Murray had also won the Madrid tournament in 2008, when it wasn't considered a Masters. He defeated Nadal in the semifinals on Saturday.
The British player has been impressive this season on clay, the surface which has seen him struggle the most in his career. He was coming off a semifinal loss to Nadal in three sets in Monte Carlo.
Sunday's defeat leaves him tied in points with Federer for the No.2 ranking, but behind on the tiebreakers.
Murray is still expected to be considered one of the main favorites at the French Open, which begins in two weeks. He lost to Djokovic in last year's semifinals at Roland Garros.