With all mainland votes counted, the centre-right group led by ex-PM Lars Lokke Rasmussen beat PM Helle Thorning-Schmidt’s centre-left coalition, although her party is the largest.
Ms Thorning-Schmidt has now stood down as Social Democratic Party leader.
The right-wing, anti-immigration Danish People’s Party will become the second-largest in parliament.
The DPP’s leader Kristian Thulesen Dahl had previously poured cold water on the idea of going into government (in Danish).
He told Denmark’s Politiken he preferred “the little free bird role, which can make the Danish People’s Party come closer to getting our policy through in the real world than you think”.
But Mr Dahl could yet be in a position to make a bid to become prime minister.
In a victory speech just before 01:30 local time (23:30 GMT), Mr Rasmussen – who led the country between 2009 and 2011 – said: “Four years ago, we returned the keys to the PM’s office. I said [at] that time that they were only a loan.”
He said he would push for “control of the flow of refugees”.
Ms Thorning-Schmidt’s governing Social Democratic Party was the biggest party, winning at least 26.3% of the vote, according to Danish broadcaster DR.
But her allies failed to gain as much of the vote as those of the opposition and she stood down as leader after conceding victory.
Ms Thorning-Schmidt said she was proud to have led the Social Democratic Party to the highest percentage of the vote, adding: “We lost at the finish line.”
According to DR, the Danish People’s Party won 21.1% of the vote, and Mr Rasmussen’s Denmark Liberal Party came third on 19.5%.