Non-local thermodynamical equilibrium (NLTE) line formation for Mg i and Mg ii lines is considered in classical 1D-LTE model atmospheres of the Sun and 17 stars with reliable atmospheric parameters and in a broad range of spectral types: 3900 ≤ T eff ≤ 17500 K, 1.1 ≤ logg ≤ 4.7, and −2.6 ≤ [Fe/H] ≤ +0.4.We find that, for each star, NLTE leads to smaller line-to-line scatter. For 10 stars, NLTE leads to consistent abundances from Mg i and Mg ii, while the difference in the LTE abundance varies between −0.21 and +0.23 dex. We obtain an abundance discrepancy betweeen Mg i and Mg ii in the two very metal-poor stars, HD 140283 and HD 84937. An origin of these abundance differences remains unclear.Our standard NLTE modelling predicts Mg i emission lines at 7.736, 11.789, 12.224, and 12.321 µm in the atmospheres with T eff ≤ 7000 K. We reproduce well the Mg i 12.2 and 12.3 µm emission lines in Procyon. However, for the Sun and 3 K-giants, the predicted Mg i emission lines are too weak compared with the observations. For stars with 7000 K ≤ T eff ≤ 17500 K, we recommend the Mg ii 3848, 3850, 4384, 4390, 4427, and 4433Å lines for Mg abundance determinations even at the LTE assumption due to their small NLTE effects. The Mg i 4167, 4571, 4702, 5528, 5167, 5172, and 5183Å lines can be safely used in the LTE analysis of stars with 7000 K < T eff ≤ 8000 K. For the hotter stars, with T eff from 8000 to 9500 K, the NLTE effects are minor only for Mg i 4167, 4702, and 4528Å.