Republican Dan Bishop eked out a win in a special election Tuesday in a longtime GOP House district in North Carolina that had become a harbinger for the 2020 general election.

The narrow victory provides bragging rights for President Trump but also a moral victory for Democrats who came close to flipping a district that has been in Republican hands for more than 50 years.

With 99% of the precincts reporting, Mr. Bishop captured 50.9% of the vote to Democrat Dan McCready’s 48.5%. The Republican’s margin of victory was 4,160 votes out of about 185,808 cast.

They had been in a neck-and-neck race heading into Election Day. Their closely watched race pitted Mr. Bishop’s pro-Trump campaign against Mr. McCready’s run as a moderate Democrat hoping to ride to Washington on an anti-Trump wave building in the Charlotte suburbs.

“Tonight is a victory shared by all who believe in the promise of America, in the promise of American exceptionalism, and the promise of freedom and opportunity,” Mr. Bishop said at a victory party.

He quoted former President Ronald Reagan, saying those freedoms are not free but must be fought for.

He also thanked Mr. Trump, saying the president “laid himself on the line for this race.”

“Dan Bishop was down 17 points 3 weeks ago. He then asked me for help, we changed his strategy together, and he ran a great race,” he tweeted. “Big Rally last night. Now it looks like he is going to win. @CNN & @MSNBC are moving their big studio equipment and to talent out. Stay tuned!”

The results ended an election saga that has left vacant the state’s 9th District seat since Congress convened in January.

“My opponent represents the Nancy Pelosi choice and the Elizabeth Warren choice toward Green New Deal, sanctuary cities, which she is specifically in favor of. And ultimately socialism. More government domination of everything. That’s the choice voters have,” Mr. Bishop said earlier in the day on Fox News.

The district, which Republicans have held since 1963, stretches from the financial hub of Charlotte and its affluent suburbs through rural communities along the South Carolina line.

Mr. McCready found a trove of support in the cities and suburbs, where women and college-educated voters are repulsed by Mr. Trump.

“I am a registered Republican, but I am fed up with the agenda of the Republican Party,” Charlotte suburban voter Bob Southern, 75, told The Associated Press. “I am so disappointed in this president, and he frightens me very much.”

The special election was a do-over of the 2018 midterm election in which the results were thrown out because of absentee ballot fraud linked to the campaign of Republican Mark Harris.

The initial count in November showed Mr. Harris beating Mr. McCready by 905 votes out of more than 280,000 cast. The scandal and the election board investigation of ballot fraud discouraged Mr. Harris from running again.

The special election attracted national attention because Democrats and Republicans sought bragging rights for the first major test of the 2020 cycle.

Democrats desperately wanted to show that Mr. Trump’s base had weakened in North Carolina, which is among the six most crucial battleground states he won in 2016 and needs for his reelection bid. The others are Florida, Georgia, Michigan, Ohio and Pennsylvania.

Mr. Trump, who carried the 9th District by about 12 percentage points over Democrat Hillary Clinton, made holding the district a top priority.

At a campaign rally Monday in Fayetteville, Mr. Trump called Mr. Bishop an ally in the fight against illegal immigration and what he called the socialist agenda of Democrats. He urged the crowd to use their votes to send a message to “the America-hating left.”

Vice President Mike Pence made a surprise visit Monday. He stopped at a pro-Bishop call center in Charlotte and joined Mr. Bishop for lunch at a barbecue restaurant in Marshville.

Mr. Bishop gained national prominence as the author of the state’s “bathroom bill,” which required people to use public restrooms corresponding with their biological sex. The 2016 law touched off protests and boycotts that were estimated to cost North Carolina nearly $4 billion before it was repealed a year later as part of a bipartisan deal.

He counted on the district’s right-leaning tendencies and played strictly to the Republican base with a pro-Trump message. In a TV ad, he is promising to fight “crazy liberal clowns” in Washington.

Mr. McCready, a Marine veteran, ran a replay of the midterm race with a focus on health care, the same message that helped get enough moderate Democrats elected last year to take control of the House.

He avoided attacks on Mr. Trump that could have energized conservative voters.

The political parties and outside groups poured money into the race. Pro-Republican groups helped Mr. Bishop close a fundraising gap. Mr. McCready raised more than $4.8 million for the race, compared with Mr. Bishop’s haul of less than $1.7 million.

Democratic groups such as the Environmental Defense Action Fund’s super PAC and Stand Up Republic, an anti-Trump super PAC, spent heavily on the race.

By Monday, the National Republican Congressional Committee and other conservative political action committees had spent more than $6.8 million in support of Mr. Bishop, according to campaign finance data compiled by the political statistics website FiveThirtyEight.