Food can be hazardous, either through toxicity or through bacterial infections that follow the ingestion of a tainted food source. Because learning about food quality enhances survival, one of the most robust forms of olfactory learning is conditioned avoidance of tastes associated with visceral malaise. The nematode Caenorhabditis elegans feeds on bacteria but is susceptible to infection by pathogenic bacteria in its natural environment. Here we show that C. elegans modifies its olfactory preferences after exposure to pathogenic bacteria, avoiding odours from the pathogen and increasing its attraction to odours from familiar nonpathogenic bacteria. Particular bacteria elicit specific changes in olfactory preferences that are suggestive of associative learning. Exposure to pathogenic bacteria increases serotonin in ADF chemosensory neurons by transcriptional and post-transcriptional mechanisms. Serotonin functions through MOD-1, a serotonin-gated chloride channel expressed in sensory interneurons, to promote aversive learning. An increase in serotonin may represent the negative reinforcing stimulus in pathogenic infection.