Compromised immune function may increase the risk of anal squamous cell carcinoma (SCC). We examined the risk of anal SCC in patients with HIV infection and other chronic disorders associated with immunosuppression. A population‐based cohort study was conducted using the Danish National Patient Registry and the Danish Cancer Registry (DCR). We identified all patients with a first‐time hospital contact or procedure for HIV infection, solid organ transplantation or autoimmune disease or a first‐time record of haematologic malignancy in the DCR, 1978–2005, and followed these for a subsequent anal SCC, starting follow‐up 1 year after diagnosis of the index disease. Standardised incidence ratios (SIRs) were computed as the ratio of observed to expected numbers of anal SCCs, based on national age‐, sex‐ and period‐specific rates. Among 4,488 patients with HIV, we observed 21 anal SCCs with 0.3 expected (SIR: 81.1 (95% confidence interval (CI): 51.6–121.9)). Risk of anal SCC was markedly increased among 5,113 solid organ recipients (SIR: 14.4 (CI: 7.0–26.4)) and 30,165 patients with haematologic malignancies (SIR: 2.3 (CI: 1.1–4.2)) but only moderately increased among 242,114 patients with autoimmune diseases (SIR: 1.3 (CI: 1.0–1.6)). SIRs varied according to type of autoimmune disease and were high in patients with Crohn's disease (SIR: 3.1 (CI: 1.2–6.4)), psoriasis (SIR: 3.1 (CI: 1.8–5.1)), polyarteritis nodosa (SIR: 8.8 (CI: 1.5–29.0)) and Wegener's granulomatosis (SIR: 12.4 (CI: 2.1–40.8)). In conclusion, we found HIV infection, solid organ transplantation, haematologic malignancies and a range of specific autoimmune diseases strongly associated with increased risk of anal SCC.