Magnesium in a metal, whereas oxygen is a non metal - therefore magnesium oxide is formed by an ionic bond (if it were 2 non metals it would be a covalent bond). It is important to understand that atoms prefer to be neutral and also have a full outer shell as this makes them more stable. Magnesium has 2 electrons in its outer shell, where as oxygen has 6 (tip: the group no. = no. of e- in the outerhsell)- it is easiest for Mg to lose 2 electrons and form Mg2+ and oxygen to gain 2 electrons to from O2-. This forms oppositely charged ions, so there are electrostatic forces of attraction between them to form an ionic bond.