In basic terms, SEO works by showing to search engines that the best result for the subject at hand is your content.
An algorithm operates in real-time as you search for something in Google (or some other search engine) to get you what the search engine deems the “best” answer.
There is a crawler on Google (or any search engine you use) that goes out and collects information about all the information you can find on the Internet. All those 1s and 0s are taken back to the search engine by the crawlers to create an index. That index is then fed into an algorithm that tries to match your question with all that data.