It took 6 hours, 7 minutes to finish. Both teams scored a run in the 17th, and each club used eight pitchers.
Alvarez hit his 23rd homer, a solo shot off Barret Browning (1-3). Andrew McCutchen added a two-run single later in the inning.
Wandy Rodriguez (8-12), who was set to start for the Pirates on Monday night at San Diego, got the win with two scoreless innings of relief.
About 9,000 fans from the original crowd of more than 43,000 stayed until the end. This was the longest game by innings in the big leagues this year. At 6:07, it tied for the longest by time, matching a game between Baltimore and Boston on May 6.
Each team had played a marathon in recent years. St. Louis went 20 innings against the Mets on April 17, 2010, and Pittsburgh played 19 innings at Atlanta on July 26, 2011.
The Pirates improved to 4-0 in extra innings this season. They moved two games ahead of St. Louis in the race for the last wild card spot in the NL. The Cardinals have lost three of four overall.
Both teams ran out of position players after the 18th inning.