A powerful, swerving free kick from Juraj Kucka in the 17th minute that deceived goalkeeper Iker Casillas put the hosts ahead and Spain struggled to find a way past inspired home goalkeeper Matus Kozacik despite dominating possession.
Substitute Paco Alcacer levelled for the visitors eight minutes from time but any hopes the 2008 and 2012 champions had of snatching a winner were shattered when Stoch headed past Casillas in the 87th minute.
It is the first time Spain have lost a qualifier in the European Championship or World Cup since they were beaten by Sweden in October 2006 and it sparked wild celebrations among the Slovakia players and supporters.
“They hit us on the counter attack, we lost concentration and they scored a second goal,” Alcacer told the Spanish television broadcaster TVE.
“There are still plenty of games to turn things around,” added the Valencia forward. “It will do us good as it means we won’t let ourselves make the same mistake again.”
Slovakia, who won 1-0 in Ukraine in their opening qualifier last month and are ranked 40th in the world, top Group C with a maximum six points. Spain have three after they began their campaign with a 5-1 triumph at home to Macedonia.
Ukraine and Macedonia also have three points and Luxembourg and Belarus a point each.
Slovakia made a bright start at the MSK stadium in Zilina and Casillas had to conjure a brilliant reaction save to keep out Robert Mak’s 11th-minute volley.
Forward Diego Costa, who has been in red-hot form for Chelsea but has failed to score for Spain in six appearances, nodded a Cesc Fabregas centre narrowly wide two minutes later before Kucka struck.
The champions went close to an equaliser at a corner moments before the break when Kozacik denied first Costa and then Sergio Busquets with a pair of fine saves and the Slovakia players were given a standing ovation as they trooped off.
Spain pressed hard at the start of the second period and Fabregas and Costa went close as they tried to break through the massed Slovak ranks.
Coach Vicente del Bosque threw on Pedro and Alcacer to try to add extra zip to the Spain attack and although the visitors thought they had secured at least a point when Alcacer scored, there was still time for substitute Stoch to bury his header past Casillas.
The 24-year-old, who plays for Al Ain in the United Arab Emirates, tore off his shirt in celebration before being engulfed by ecstatic team mates-Reuters