A major goal in neuroscience is to elucidate the principles by which memories are stored in a neural network. Here, we have systematically studied how the four types of associative memories (short-and long-term memories, each formed using positive and negative associations) are encoded within the compact neural network of C. elegans worms.Interestingly, short-term, but not long-term, memories are evident in the sensory system.Long-term memories are relegated to inner layers of the network, allowing the sensory system to resume innate functionality. Furthermore, a small set of sensory neurons is allocated for coding short-term memories, a design that can increase memory capacity and limit non-innate behavioral responses. Notably, individual sensory neurons may code for the conditioned stimulus or the experience valence. Interneurons integrate these information to modulate animal behavior upon memory reactivation. This comprehensive study reveals basic principles by which memories are encoded within a neural network, and highlights the central roles of sensory neurons in memory formation.