CRISPR–Cas immunity protects prokaryotes against invading genetic elements1. It uses the highly conserved Cas1–Cas2 complex to establish inheritable memory (spacers)2,3,4,5. How Cas1–Cas2 acquires spacers from foreign DNA fragments (prespacers) and integrates them into the CRISPR locus in the correct orientation is unclear6,7. Here, using the high spatiotemporal resolution of single-molecule fluorescence, we show that Cas1–Cas2 selects precursors of prespacers from DNA in various forms—including single-stranded DNA and partial duplexes—in a manner that depends on both the length of the DNA strand and the presence of a protospacer adjacent motif (PAM) sequence. We also identify DnaQ exonucleases as enzymes that process the Cas1–Cas2-loaded prespacer precursors into mature prespacers of a suitable size for integration. Cas1–Cas2 protects the PAM sequence from maturation, which results in the production of asymmetrically trimmed prespacers and the subsequent integration of spacers in the correct orientation. Our results demonstrate the kinetic coordination of prespacer precursor selection and PAM trimming, providing insight into the mechanisms that underlie the integration of functional spacers in the CRISPR loci.