Aims/hypothesis Preterm birth (gestational age <37 weeks) has been associated with insulin resistance early in life. However, no large population-based studies have examined risks of type 1 and type 2 diabetes and potential sex-specific differences from childhood into adulthood. Clinicians will increasingly encounter adults who were born prematurely and will need to understand their long-term risks. We hypothesised that preterm birth is associated with increased risks of type 1 and type 2 diabetes into adulthood. Methods A national cohort study was conducted of all 4,193,069 singletons born in Sweden during 1973-2014, who were followed up for type 1 and type 2 diabetes identified from nationwide diagnoses and pharmacy data to the end of 2015 (maximum age 43 years; median age at the end of follow-up 22.5 years). Cox regression was used to adjust for potential confounders, and cosibling analyses assessed the influence of shared familial (genetic and/or environmental) factors. Results In 92.3 million person-years of follow-up, 27,512 (0.7%) and 5525 (0.1%) people were identified with type 1 and type 2 diabetes, respectively. Gestational age at birth was inversely associated with both type 1 and type 2 diabetes risk. Adjusted HRs for type 1 and type 2 diabetes at age <18 years associated with preterm birth were 1.21 (95% CI, 1.14, 1.28) and 1.26 (95% CI, 1.01, 1.58), respectively, and at age 18-43 years were 1.24 (95% CI, 1.13, 1.37) and 1.49 (95% CI, 1.31, 1.68), respectively, compared with full-term birth. The associations between preterm birth and type 2 (but not type 1) diabetes were stronger among females (e.g. at age 18-43 years, females: adjusted HR, 1.75; 95% CI, 1.47, 2.09; males: 1.28; 95% CI, 1.08, 1.53; p < 0.01 for additive and multiplicative interaction). These associations were only partially explained by shared genetic or environmental factors in families. Conclusions/interpretation In this large national cohort, preterm birth was associated with increased risk of type 1 and type 2 diabetes from childhood into early to mid-adulthood. Preterm-born children and adults may need early preventive evaluation and long-term monitoring for diabetes.