Background: Magnesium plays pivotal roles in physiological processes. Previous studies have shown that magnesium acts as an important mediator in ameliorating cellular injury and preventing the release of proinflammatory cytokines in septic patients. Therefore, we speculated that the serum magnesium ion level may affect the outcome of sepsis. However, research in this area is rarely reported and it is worth exploring.Methods: We conducted a retrospective study based on the MIMIC-IV database. According to the time-weighted magnesium levels during the ICU stay, we analyzed the relationship between serum magnesium levels and 28-day mortality and 90-day mortality using a time-dependent Cox proportional hazard model and restricted cubic splines. Additionally, we examined the effect of magnesium sulfate supplementation on prognosis with a time-fixed and time-dependent Cox model and restricted cubic splines.Results: In total, 8175 patients were included in this study. Patients with hypo-, normo- and hypermagnesemia were 22.87%, 66.84%, and 10.29%, respectively. When adjusted for confounders, hypermagnesemia was significantly associated with both 28-day mortality (HR=1.42, 95% CI=1.23-1.64, p<0.001) and 90-day mortality (HR=1.42, 95% CI=1.24-1.64, p<0.001). However, no significant difference was found between hypomagnesemia and mortality of septic patients (28-day mortality: HR=1.09, 95% CI=0.86-1.37, p=0.486, 90-day mortality: HR=1.06, 95%=0.85-1.34, p=0.573). For those who received magnesium sulfate supplementation, there was no significant difference among hypo-, normo-, and hypermagnesemia before MgSO4 supplementation. Interestingly, subsequent hypermagnesemia (28-day mortality: HR=1.44, 95% CI=1.17-1.78, p=0.001, 90-day mortality: HR=1.43, 95% CI=1.16-1.77, p=0.001), and even still hypomagnesemia (28-day mortality: HR=1.51, 95% CI=1.15-1.99, p=0.003, 90-day mortality: HR=1.53, 95% CI=1.18-1.99, p=0.001) after MgSO4 supplement were significantly associated with increased 28-day and 90-day mortality after adjustment for confounders.Conclusion: Hypermagnesemia was significantly associated with higher risk of 28-day mortality and 90-day mortality. Active supplementation with magnesium sulfate may be associated with a worse prognosis in sepsis.