The sanctuary city order was among a flurry of immigration measures Trump has signed since taking office in January, including a ban on travellers from seven Muslim-majority countries and a directive calling for a wall on the Mexican border.
A federal appeals court blocked the travel ban. The Administration then revised it, but the new version also is stalled in court.
The judge rejected the Administration's argument that the Executive Order applies only to a relatively small pot of money and said President Donald Trump cannot set new conditions on spending approved by Congress.
Even if the President could do so, those conditions would have to be clearly related to the funds at issue and not coercive, as the executive order appears to be, Orrick said.
"Federal funding that bears no meaningful relationship to immigration enforcement cannot be threatened merely because a jurisdiction chooses an immigration enforcement strategy of which the president disapproves," the judge said.
The Justice Department had no immediate comment.
San Francisco City lawyer Dennis Herrera said the President was "forced to back down".
"This is why we have courts - to halt the overreach of a president and an attorney-general who either don't understand the Constitution or chose to ignore it," Herrera said.
A Justice Department lawyer, Chad Readler, had defended the President's Executive Order as an attempt to use his "bully pulpit" to "encourage communities and states to comply with the law".
Readler said the order applied to only three Justice Department and Homeland Security grants that would affect less than US$1 million for Santa Clara County and possibly no money for San Francisco.
But the judge disagreed, saying the order was written broadly to "reach all federal grants" and potentially jeopardises hundreds of millions of dollars in funding to San Francisco and Santa Clara.
He cited comments by the President and Attorney General Jeff Sessions as evidence that the order was intended to target a wide array of federal funding and that the President himself had called it a "weapon" to use against recalcitrant cities.
- AP, AAP