Luis Enrique's side progress thanks to their superior goal difference to Germany
Spain produced a shambolic performance but remained in the World Cup on Thursday despite losing 2-1 to Japan in Qatar.
Alvaro Morata gave Spain an 11th-minute lead but second-half goals from Ritsu Doan and Ao Tanaka earned Japan the three points and sent them through to the round of 16 as Group E winners.
Spain join them as runners-up, but only by the skin of their teeth after Germany came from behind to beat Costa Rica 4-2.
At the moment Costa Rica went 2-1 up against Germany, Spain were heading out despite having beaten Costa Rica 7-0 just a week ago.
Hansi Flick's side came back to win the game and help La Roja out, but the favour was not returned -- a Spain equaliser would have eliminated Japan and sent Germany through.
In the end, Japan won the group to set up a meeting with Croatia and Spain, who finished ahead of Germany on goal difference, will take on Morocco in the last 16.
Luis Enrique's side had dominated the first half after taking the lead through Morata's header from Cesar Azpilicueta's cross.
However, there was a lack of urgency about them and Japan took advantage of that after the break, coming from behind as they did when they beat Germany 2-1 a week ago.
Doan levelled in the 48th minute with a strike from distance that Unai Simon, who should have done better, parried into the net.
Three minutes later, Tanaka made it 2-1, bundling home after the ball had just -- it was decided after a long VAR review -- been kept in play by Kaoru Mitoma.
Spain pushed for a leveller but as news came through of Germany's turnaround, they appeared to slow down, settling for a result that in theory could give them an easier route to the final, with Brazil now in the other half of the draw.
That will do little to lift the mood in the Spain camp, though, with the dejected players looking like they had been knocked out at the final whistle.
Luis Enrique's task is to lift his team for Tuesday's game against Morocco. Japan play Croatia on Monday.
Topics with the letter