BERLIN (Reuters) - Voters handed German Chancellor Angela Merkel’s conservatives their worst-ever result in Hamburg on Sunday, punishing them for flirting with the far-right in an eastern state and descending into a messy leadership battle.

Preliminary results also showed the far-right Alternative for Germany (AfD) just scraping into the Hamburg parliament, only four days after a racist gunman killed 11 people, including himself, in the western town of Hanau.

The Social Democrats (SPD) and Greens celebrated in Germany’s second-biggest city after taking first and second place, meaning they will probably keep ruling together in the northern port and city-state.

The conservative Christian Democrats (CDU) suffered after party leader and Merkel protegee Annegret Kramp-Karrenbauer said she would stand aside, blowing open the race to succeed the chancellor and throwing the party into turmoil.

The CDU slipped into third place, scoring just 11.2%. The AfD, which has capitalised on anger over Merkel’s open-door migrant policy, especially in the former Communist East, won 5.3%, just over the 5% threshold needed to get into the state parliament, according to the preliminary results.

Kramp-Karrenbauer’s move came after an eastern branch of the CDU defied the national party and voted with the AfD to install a state premier from a third party - breaking a postwar consensus among established parties of shunning the far-right.

“It is a bitter day for the CDU in Germany and a historically bad result in Hamburg,” said CDU Secretary General Paul Ziemiak.

The CDU leadership team meets on Monday and Kramp-Karrenbauer is expected to set out a timetable for a decision on the party chair and possibly the chancellor candidate. Four or five candidates are jockeying for the jobs.

Merkel, chancellor for almost 15 years, has said she will not run again in the next federal election, due by October 2021.

Preliminary results put the SPD, who share power with the conservatives at the federal level, down about 6 points from the last vote in 2015 but on 39.1%, still by the far the biggest party in Hamburg.

The Greens were the biggest winners, reflecting their national strength driven by growing fears about climate change. They almost doubled their vote to 24.1% and national co-leader Robert Habeck declared it a “fantastic result”.

Nationally, the Greens are second, behind the conservative bloc, and many commentators expect them to have a role in the next federal government.