This second "sister story" in Genesis (compare 12:10–20) happened just before Sarah became pregnant with Isaac (chapter 21). In both instances, God protected Abraham and Sarah's marriage to keep it pure for the covenant promises. To be part of God's plan, his people must separate from worldly corruption.
This story happened in the promised land. It showed Israel how God intervened in people's lives to fulfill his plan. He protected them from threats from other tribes. He used his chosen people to mediate his relationship with other nations.
By preventing adultery from destroying Abraham's marriage, God reminded the Israelites not to marry those who would lead them away from the Lord (Ezra 9:1–4; Nehemiah 13:23–27; Malachi 2:10–17). They should not allow any chance for temptation. Adultery would eventually destroy the covenant and the people.