Abstract: Locomotion within granular media like sand, soil and debris that display both solid and fluid-like behavior is challenging and is less understood than locomotion within fluids or on solid ground. As a representative case of subsurface locomotion in granular media, we studied the undulatory sand-swimming of the sandfish lizard (Scincus scincus). We developed a resistive force model with empirical force laws to explain the swimming speed observed in the animal experiment. By varying the amplitude of the undulation in RFT, we found that the range of amplitude used by the animal coincides with the maximum speed, which implies that the animal optimizes its speed. We developed a numerical model of the sandfish coupled to a discrete element method simulation of the granular medium to test assumptions as well as predictions in RFT and to study more detailed mechanics of sand-swimming. The principles learned from the models guided the development of a 7-segment robot that can effectively swim in granular media. To understand the general mechanics of swimming in granular media, we examined a reduced system: the three-link swimmer. By combining the RFT model with geometric mechanics theory, we predicted the optimal gaits for forward, lateral and rotational motion and confirmed the predictions using a three-link robot.