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 \leq T _ { eff } \leq 17500 K , 1.1 \leq log g \leq 4.7 , and - 2.6 \leq [ Fe/H ] \leq +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 \mu m in the atmospheres with T _ { eff } \leq 7000 K. We reproduce well the Mg i 12.2 and 12.3 \mu 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 \leq T _ { eff } \leq 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 } \leq 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 Å .