Tantalum nitride (Ta3 N5 ) highlights an intriguing paradigm for converting solar energy into chemical fuels. However, its photocatalytic properties are strongly governed by various intrinsic/extrinsic defects. In this work, we successfully prepared a series of Mg-doped mesoporous Ta3 N5 using a simple method. The photocatalytic and photoelectrochemical properties were investigated from the viewpoint of how defects such as accumulation of oxygen and nitrogen vacancies contribute to the catalytic activity. Our findings suggest that Mg doping is accompanied by an accumulation of oxygen species and a simultaneous elimination of nitrogen vacancies in Ta3 N5 . These oxygen species in Ta3 N5 induce delocalized shallow donor states near the conduction band minimum and are responsible for high electron mobility. The superior photocatalytic activity of Mg-doped Ta3 N5 can then be understood by the improved electron-hole separation as well as the lack of nitrogen vacancies, which often serve as charge-recombination centers.