Background Sleep's impact on the human immune system and inflammatory responses makes it a potential risk factor for lung function impairment. However, the relationship between sleep duration and lung function impairment in middle-aged and young adults has been rarely investigated. Methods A total of 9,284 aged 20-64 years were categorized into four groups according to sleep duration (<= 6 h, 7 h, 8 h, and >= 9 h), with 7 h as the reference, by using the U.S. NHANES data, 2007-2012. Forced expiratory volume in the 1 s (FEV1), forced vital capacity (FVC), FEV1 to FVC (FEV1/FVC) ratio, peak expiratory flow (PEF), and forced expiratory flow at 25-75% (FEF25- 75%) were measured by spirometry. Restrictive impairment was defined as baseline FVC < 80% predicted and obstructive impairment as FEV1/FVC < 0.70. Generalized linear regression and logistic regression were performed to estimate the associations between sleep duration and lung function. Results Compared with 7 h of sleep duration, shorter and longer sleep duration were associated with decreases in FEV1 (<= 6 h: beta=-0.010, 95% CI=-0.014 to -0.006; 8 h: beta=-0.005, 95% CI=-0.009 to -0.001), FVC (<= 6 h: beta=-0.018, 95% CI=-0.014 to -0.007; 8 h: beta=-0.005, 95% CI=-0.009 to -0.002), and PEF (<= 6 h: beta=-0.006, 95% CI=-0.010 to -0.002; 8 h: beta=-0.007, 95% CI=-0.011 to -0.002; >= 9 h: beta=-0.012, 95% CI=-0.020 to -0.004). Similarly, shorter (<= 6 h: OR = 1.346, 95% CI = 1.065 to 1.700) and longer (>= 9 h: OR = 1.827, 95% CI = 1.236 to 2.700) sleep duration were associated with increased risks of restrictive impairment. Moreover, the aforementioned associations were more pronounced among male participants. Conclusions Compared with 7 h of sleep duration, shorter and longer sleep duration were associated with impaired lung function among adults aged 20-64 years, and these associations were stronger among males.