WASHINGTON, May 30 — The Supreme Court declared today, in a ruling affecting millions of government employees, that the Constitution does not always protect their free-speech rights for what they say on the job.

In a 5-to-4 decision, the court held that public employees' free-speech rights are protected when they speak out as citizens on matters of public concern, but not when they speak out in the course of their official duties.

Today's ruling, involving a deputy Los Angeles district attorney who contended that he had been denied a promotion for challenging the legitimacy of a search warrant, came in a case that has been closely watched not just by public workers but by those who have worried that it could discourage internal whistle-blowers from speaking up about government misconduct and inefficiency.

"We hold that when public employees make statements pursuant to their official duties, the employees are not speaking as citizens for First Amendment purposes, and the Constitution does not insulate their communications from employer discipline," Justice Anthony M. Kennedy wrote for the court.