We employ a large sample of 20 171 optically selected groups and clusters at 0.15 ≤ z ≤ 0.4 in the Sloan Digital Sky Survey to investigate how the stacked stellar mass fraction varies across a wide range of total mass, M500. Our study improves upon previous observational studies in a number of important ways, including having a much larger sample size, an explicit inclusion of the intracluster light (ICL) component and a thorough examination of the accuracy of our total mass estimates via comparisons to simulations and weak lensing observations. We find that the stellar mass fraction depends only weakly on total mass and that the contribution of ICL to the total stellar mass fraction is significant (typically 20–40 per cent). Both of these findings are in excellent accordance with the predictions of cosmological simulations. Under the assumption of a Chabrier (Salpeter) initial mass function, the derived star formation efficiency (fstar/fb, where fb ≡ Ωb/Ωm) is relatively low at 8 per cent (14 per cent) and is consistent with the global star formation efficiency of semi-analytic models that reproduce the galaxy stellar mass function. When our measured stellar mass fractions are combined with the observed relation between the hot gas mass fraction and total mass from X-ray observations, our results imply that galaxy groups have significantly lower baryon fractions than massive clusters. Ejection of gas due to energetic AGN feedback (most likely at high redshift) provides a plausible mechanism for explaining the trends we observe.