A new study released Wednesday by the Centers for Disease Control and Prevention shows that while vaccination and immunity from prior infection offered protection against new COVID-19 infections and hospitalization, vaccination provides the best defense in the longer term.

The study looked at case data from more than 1 million cases in New York and California between May and November of 2021, prior to the discovery of the omicron variant.

Overall, those who were unvaccinated and were not previously infected with COVID-19 had a much higher risk of infection and hospitalization. 

Initially, people who were vaccinated had the lowest risk of COVID-19 infection and hospitalization, followed closely by unvaccinated people with a previous infection, according to the study.

However, as the study wore on, when the delta variant of COVID-19 became the predominant strain in the U.S., vaccinated people who previously COVID-19 had the lowest case rates.

“Before the Delta variant, Covid-19 vaccination resulted in better protection against a subsequent infection than surviving a previous infection,” Dr. Benjamin Silk, an infectious diseases epidemiologist with the CDC, told reporters on Wednesday. “When looking at the summer and the fall of 2021, when Delta became the dominant in this country, however, surviving a previous infection now provided greater protection against subsequent infection than vaccination.”

“These results demonstrate that vaccination protects against COVID-19 and related hospitalization, and that surviving a previous infection protects against a reinfection and related hospitalization,” the authors of the study wrote. 

The study noted that the immunity from prior infection may have been due to the waning immunity from vaccines: “Importantly, infection-derived protection was higher after the Delta variant became predominant, a time when vaccine-induced immunity for many persons declined because of immune evasion and immunologic waning.”

It’s also unclear how long such immunity lasts.

The CDC said that while previous infection and vaccination provided protection against COVID-19, the only safe and effective way to ensure lasting protection against the coronavirus is to get vaccinated.

“Although the epidemiology of COVID-19 might change with the emergence of new variants, vaccination remains the safest strategy to prevent SARS-CoV-2 infections and associated complications,” the authors of the study urged. “All eligible persons should be up to date with COVID-19 vaccination.”

“Additional recommendations for vaccine doses might be warranted in the future as the virus and immunity levels change,” they added. 

The CDC warned that the results of the study may not apply to the current situation with the pandemic, specifically related to the omicron surge and the booster dose drive.

“These findings cannot be generalized to the current Omicron wave,” Dr. Silk told reporters.