Dukes County has lost its ranking as the healthiest county in Massachusetts, but hasn’t fallen far — it is now in second place.

The fifth annual county health rankings were released Wednesday, ranking Middlesex County as the healthiest in Massachusetts and Hampden County as the least healthy. The rankings are created by the Robert Wood Johnson Foundation and the University of Wisconsin Population Health Institute, which does the rankings for every state. The counties are ranked on 29 factors, including access to health care, social and economic factors, and physical environment.

Dukes County, which includes Martha’s Vineyard and the Elizabeth Islands, came out on top in the rankings for the last two years, but fell to second this year in a ranking of health outcomes, a ranking that looks at length and quality of life. Dukes County has the fewest premature deaths, but has higher than the state average of reported poor physical and mental health days.

The rankings are compiled with data from several sources, including the Center for Disease Control, the Environmental Protection Agency and the National Center for Health Statistics.

Elsewhere a study of health factors showed Dukes County has above average high school graduation rates and lower than state average rates of violent crime and death by injury. Dukes is also below state average in smoking and obesity rates among adults, sexually transmitted diseases and teen births.

Dukes County did not get uniformly high marks. Once again, it had a rate of excessive drinking (defined as the percent of adults reporting either binge drinking or heavy drinking) higher than the state average. Dukes County also had a higher-than-average rate of alcohol-impaired driving deaths,

While Dukes County was in the top five counties in the state for most factors, it was ranked 13 out of 14 counties when it comes to clinical care. The county has higher rates of people who are uninsured, the study found, and has fewer dentists and mental health providers per person than the state average. Dukes County is slightly better than state average when it comes to the ratio of primary care physicians to residents.

Dukes was ranked second in the state for physical environment, with lower levels of air pollution and far lower numbers of people who have a long commute compared with the state average. It also exceeds the state average when it comes to severe housing problems, defined as overcrowding, high housing costs and lack of kitchen or plumbing facilities. The study found 36 per cent of the population is getting water from a public water safety facility with at least one health-based violation; the state average is eight per cent.

Click here to see how Dukes County stacked up against other Massachusetts county in the report.