With climate change and human activities, the Qinghai-Xizang Plateau (QXP) faces increasing risk of desertification. High-altitude desert plants exhibit remarkable resilience, making them ideal for restoring desertified lands on the QXP. Sandrice, a medicinal herb, disperses widely across Asian deserts including the QXP. To elucidate the molecular mechanism of sandrice adaptation to the QXP, in situ metabolome and transcriptome analyses were conducted between high and mid-altitude ecotypes. Comparison analysis revealed that up-regulated genes in the high-altitude ecotype were primarily involved in phenylpropanoid and flavonoid biosynthesis pathways, leading to higher accumulation of these medicinal metabolites in the high-altitude ecotype. Additionally, Ka/Ks analysis indicated significant divergence in DEGs such as FLS, CCoAOMT and HCT between the two ecotypes. Population genetic analysis across altitude gradients showed that FST values for genes in phenylpropanoid and flavonoid biosynthesis pathways were higher than genome-wide FST values. Notably, nine out of 15 genes in these pathways, including FLS and HCT, were fixed in all the high-altitude populations, as a consequence of strong directional selection by the alpine desert environment, which supports phenylpropanoids and flavonoids play critical roles for sandrice adapting to alpine desert environments. Moreover, balancing selection could also facilitate sandrice's spread across diverse desert conditions, whose signal was witnessed in CCoAOMT within the QXP populations. This study bridges our understanding from medicinal metabolites to the genetic basis of alpine ecotypes adapted to harsh environments on the QXP, providing valuable molecular insights and genetic resources for ecosystem restoration and the indigenous nature of high-altitude medicinal plants