There is evidence of greater opioid prescription to individuals in the United States with mental health conditions. Whether these associations generalize beyond the US prescription environment and to familial mental health and socioeconomic status (SES) has not been examined comprehensively. This study estimated associations of diverse preexisting mental health diagnoses, parental mental health history, and SES in childhood with opioid analgesic prescription patterns nationwide in Sweden. Using register-based data, we identified 5,071,193 (48.4% female) adolescents and adults who were naive to prescription opioid analgesics and followed them from 2007 to 2014. The cumulative incidence of any dispensed opioid analgesic within 3 years was 11.4% (95% CI, 11.3%-11.4%). Individuals with preexisting self-injurious behavior, as well as opioid and other substance use, attention-deficit/hyperactivity, depressive, anxiety, and bipolar disorders had greater opioid therapy initiation rates than did individuals without the respective conditions (hazard ratios from 1.24 [1.20-1.27] for bipolar disorder to 2.12 [2.04-2.21] for opioid use disorder). Among 1,298,083 opioid recipients, the cumulative incidence of long-term opioid therapy (LTOT) was 7.6% (7.6%-7.7%) within 3 years of initiation. All mental health conditions were associated with greater LTOT rates (hazard ratios from 1.66 [1.56-1.77] for bipolar disorder to 3.82 [3.51-4.15] for opioid use disorder) and were similarly associated with concurrent benzodiazepine-opioid therapy. Among 1,482,462 adolescents and young adults, initiation and LTOT rates were greater for those with parental mental health history or lower childhood SES. Efforts to understand and ameliorate potential adverse effects of opioid analgesics must account for these patterns.