The defending champion at the clay event fought back from 4-2 and a break down in the third set to see off the local favourite, who was cheered on by a partisan crowd at the Magic Box Arena, after she was 'bagelled' for the first time in five years in the second stanza.
"It was definitely a battle," Williams said.
"I obviously didn't do much in the second set, and I think I gave her a lot confidence to play better. I thought she played really well in the third."
Williams made it 26 wins and only one defeat since the start of last year's claycourt season, but was up against an experienced player on the surface.
The 30-year-old Spaniard has the highest number of clay-court title wins with 10 among players currently on the circuit and stunned the American taking the second set to love.
"I wasn't really there," Williams said. "I wasn't really in it. My feet weren't moving. I don't know what happened.
"To turn it around I got up earlier on the changeover and started doing high knees and just stretching and doing anything to try to get my intensity back up where it needed to be.
"I definitely want to cut back on my unforced errors. I had a lot today. Also, I went for a lot more today than I have been doing in my past few matches.
"So I think I'm going to go back to the way I have been playing, and being more calm, and not making as many errors as I did today."
Williams will now meet seventh-seeded Italian Sara Errani after she saw off Russian Ekaterina Makarova in straight sets.
Madrid Open results
2-Maria Sharapova (Russia) beat Kaia Kanepi (Estonia) 6-2 6-4
1-Serena Williams (U.S.) beat Anabel Medina Garrigues (Spain) 6-3 0-6 7-5
16-Ana Ivanovic (Serbia) beat 6-Angelique Kerber (Germany) 6-3 6-1
7-Sara Errani (Italy) beat Ekaterina Makarova (Russia) 6-4 6-3
- Sports & Recreation
- Maria Sharapova
- Kaia Kanepi