We integrate biological experiment, empirical theory, numerical simulation and a physical model to reveal principles of undulatory locomotion in granular media. High-speed X-ray imaging of the sandfish lizard, Scincus scincus, in 3 mm glass particles shows that it swims within the medium without using its limbs by propagating a single-period travelling sinusoidal wave down its body, resulting in a wave efficiency, η, the ratio of its average forward speed to the wave speed, of approximately 0.5. A resistive force theory (RFT) that balances granular thrust and drag forces along the body predicts η close to the observed value. We test this prediction against two other more detailed modelling approaches: a numerical model of the sandfish coupled to a discrete particle simulation of the granular medium, and an undulatory robot that swims within granular media. Using these models and analytical solutions of the RFT, we vary the ratio of undulation amplitude to wavelength (A/λ) and demonstrate an optimal condition for sand-swimming, which for a given A results from the competition between η and λ. The RFT, in agreement with the simulated and physical models, predicts that for a single-period sinusoidal wave, maximal speed occurs for A/λ ≈ 0.2, the same kinematics used by the sandfish.