The objective is to clarify the role of immunodeficiency and pneumonia in elevated lung cancer risk among HIV-infected individuals. Cohort study of HIV-infected and HIV-uninfected adults in a large integrated healthcare system in California during 1996-2011. We used Poisson models to obtain rate ratios for lung cancer associated with HIV infection, overall and stratified by recent CD4 cells/μl (HIV-uninfected as reference group), with χ tests for trends across CD4 strata. Fully adjusted models included demographics, cancer risk factors (smoking, drug/alcohol abuse, overweight/obesity), and prior pneumonia. Among 24 768 HIV-infected and 257 600 HIV-uninfected individuals, the lung cancer rate per 100 000 person-years was 66 (n = 80 events) for HIV-infected and 33 (n = 506 events) for HIV-uninfected individuals [rate ratio 2.0, 95% confidence interval (CI): 1.7-2.2]. Overall, HIV-infected individuals were at increased risk of lung cancer after adjustment for demographics and cancer risk factors (rate ratio 1.4, 95% CI: 1.1-1.7), but not after additional adjustment for pneumonia (rate ratio 1.2, 95% CI: 0.9-1.6). Lower CD4 cell counts were associated with higher risk of lung cancer in unadjusted and demographics-adjusted models (P < 0.001 for all), but this trend did not remain after adjustment for cancer risk factors and pneumonia. Compared with HIV-uninfected individuals, HIV-infected individuals with CD4 less than 200 cells/μl were not at increased risk of lung cancer in fully adjusted models. The increased lung cancer risk among HIV patients is attributable to differences in demographics, risk factors such as smoking, and history of pneumonia. Immunodeficiency does not appear to have an independent effect on lung cancer risk.