Real Sociedad’s Sweden forward Alexander Isak inspired an incredible attacking display, scoring twice in the second period.
He beat goalkeeper Alex Remiro at the near post moments after receiving a volley of boos from the home fans for his haphazard display.
But rampant Real Sociedad soon restored a three-goal cushion when Isak teed up Merino for a simple tap-in after 69 minutes.
Real Madrid substitute Rodrygo pulled a goal back in the 81st minute to make it 4-2.
This was after Brazilian team mate Vinicius Jr had a strike ruled out for offside following a VAR review.
Nacho struck in added time for the hosts to set up a tense finish.
Real Sociedad defender Andoni Gorosabel was sent off in stoppage time but Real Madrid, who are top of La Liga, could not find an equaliser.
They thus suffered their first defeat in any competition since losing 1-0 at Real Mallorca on Oct. 19.
Also, FC Barcelona’s hopes of reaching a seventh successive Copa del Rey final ended at the same quarter-final stage with a 0-1 defeat by Athletic Bilbao.
The tight contest was decided in the third minute of stoppage time when Spanish forward Inaki Williams headed past Marc-Andre ter Stegen.
The two surprise results have come a day after second-tier side Mirandes defeated Villarreal 4-2.
Granada, who overcame Valencia 2-1, make up the semi-final line-up.