We infer the time evolution of the stellar metallicity for Sloan Digital Sky Survey (SDSS) galaxies by interpreting their spectra through stellar population models using a sample that spans 5 orders of magnitude in stellar mass (). Assuming the Bruzual & Charlot stellar population models, we find that more massive galaxies are more metal rich than less massive ones at all redshifts; the mass–metallicity relation is imprinted in galaxies from z∼ 3, close to the epoch of formation. For galaxies with present stellar masses >1010 M⊙, the time evolution of stellar metallicity is very weak, with at most dex shift over 12 Gyr – for this reason, the mass–metallicity relation evolves little with redshift. However, for galaxies with present stellar masses <1010 M⊙, the evolution is significant, with metallicity increasing by more than a decade from redshift 3 to the present. By being able to recover the metallicity history, we have managed to identify the origin of a recent discrepancy between the metallicity recovered from nebular lines and absorption lines. As expected, we show that the young population dominates the former while the old population the latter. We have investigated the dependence on the stellar models used and find that older stellar population synthesis codes do not produce a clear result. Finally, we have explored the relationship between cluster environment and metallicity, and find a strong correlation in the sense that galaxies in high-density regions have high metallicity.