There are several ways this can be achieved, one of them is by antibiotic resistance selection. One of the most common ways is to have the the cloning vector (such as a plasmid) to have a selective antibiotic resistance gene such as the pUC19 plasmid high contains an ampicillin resistance gene (ampR). After transforming this plasmid into your bacteria, you can selectively grow bacteria that have taken up the plasmid by plating the culture onto plates containing ampicillin. If the bacteria has taken up the plasmid and is expressing the ampR gene, they will be able to grow on that plate and you should be able to isolate bacteria carrying the plasmid. Bacteria without the plasmid theoretically will not be able to grow as the penicillin will be toxic (bacteriocidal) to the bacterium (assuming its naturally susceptible such as E.coli).
A second method of selection that will preserve non-transformed bacteria on your samples is by using a gene tag like Green Fluorescent Protein (GFP). The gene that produces this molecular tag can be introduced via the same plasmid carrying your DNA fragment of interest. Transformed bacteria can be identified under ultraviolet light as the bacterium expressing GFP will glow fluorescent green under this condition.