Sex was used as a means of social control. By making premarital sex taboo and shameful, it forces people who want to have sex to get married.
Marriage historically was a convention controlled by the church. You could largely only get married with the approval of the church or temple, which meant they could control who you were having babies with, creating castes.
Also because sex is fun, it’s a reason to abide all the other bullshit we’d be like “naw, not doing that” over.