As was often the case in Greek tragedy, the story of Oedipus Rex was not created by Sophocles (nor were its characters), but, rather, the entire play was derived from traditions within Greek mythology. The tragedy of Oedipus, who killed his father and married his mother, was a well-known story of Ancient Greece.
This larger story is one that revolves heavily around the idea of fate. As the story tells it, before Oedipus was born, it was prophesied that Laius, the King of Thebes, would be killed by his son. Thus, when Oedipus was born, Oedipus was abandoned to die of exposure. However, rather than leaving the child to this fate, the herdsman entrusted with this task would take pity on Oedipus. He gives Oedipus to a visiting shepherd, who would take the child away. Oedipus would later be raised by Polybus and Merope, King and Queen of Corinth.
Later in life, Oedipus travels to the Oracle at Delphi, who alerts him to his fate (to marry his mother and kill his father). Horrified by this, he flees, killing his biological father on the road (not knowing the man's identity). Meanwhile, Thebes itself is being menaced by the Sphinx, who would pose its famous riddle to its victims, killing those who get the answer wrong. Oedipus confronts the Sphinx and correctly answers the riddle, thus defeating the monster. In gratitude for his victory over the Sphinx, Oedipus is made King of Thebes, marrying Jocasta in the process.
It is after these events that Oedipus Rex opens, with Oedipus at the height of his power, married to his mother (though he is unaware of his relation to Jocasta) and reigning as King of Thebes. Meanwhile, the entire city has been struck with plague as divine punishment for Oedipus's crime. It is in this context that Sophocles's play takes shape.