The electronic properties of Mg-doped perfect SrTiO 3 and crystals containing oxygen vacancies systems are investigated by first principles calculation. Dopant formation energy results show that the Mg atoms preferentially enter the Sr site in SrTiO 3 . Substitution of Ti by Mg brings some acceptor levels, which introduces the p-type conductivity of SrTiO 3 . Creation of oxygen vacancies in SrTiO 3 introduces donor levels, which can contribute to the n-type conductivity. In SrTiO 3 containing oxygen vacancies system, a self-compensation effect will occur when Ti is substituted by Mg, and the system undergoes n-type to p-type transition.