Marlins starter Sean West (3-3) allowed a leadoff double in the fifth to Juan Uribe and then walked Matt Cain and Aaron Rowand. After inducing Andres Torres to fly out, West served up the grand slam to Sandoval.
San Francisco starter Matt Cain (10-2) got the win, going 6 2/3 innings and allowing just two runs on five hits with five strikeouts and two walks.
Jeremy Affeldt pitched 1 1/3 shutout innings and Brian Wilson got his 22nd save despite giving up two runs on three hits in the ninth.
Bengie Molina had two hits for the Giants, who won for the third time in their last four games.
West gave up five runs on four hits for the Marlins, who lost for just the second time in their last seven games.
Emilio Bonifacio and Cody Ross each had three hits for Florida.