In 2005, scientists discovered sequence similarities between an unusual region in many bacterial genomes and the DNA sequences of many viruses that typically infect these cells. After some research, they found that this region acted as a sort of “immune memory” – a record of previously encountered viruses used by these cells to recognize and specifically destroy the DNA of such viruses.
Upon first exposure to a virus, the bacterial cell activates a set of enzymes that cut the DNA into very short fragments which are incorporated into the bacteria’s own genome as shown below.

Modified from: www.nature.com
The short DNA sequences in these regions are used to produce short RNA molecules called crRNA . These crRNAs work in tandem with a short accessory RNA molecule called tracrRNA, to attract an enzyme called Cas9. Cas9 binds to the two RNA molecules and then uses the sequence of the crRNA to find target DNA sequences in the cell that are complementary to it. It then cuts this foreign target sequence.

Modified from: www.nature.com
Because the sequences in the CRISPR region are collected in a very specific way, this system specifically targets foreign DNA. When the “spacers” are initially produced, they are specifically cut upstream (in front) of a specific DNA sequence (referred to as PAM – Protospacer Adjacent Motif). The PAM sequence is not part of the spacer and does not appear in the “repeats” that surround the spacer, therefore the bacteria’s own DNA will not be cut the CRISPR/Cas9 system. The PAM sequence however, is part of the foreign DNA and will thus allow this defence system to destroy it.