I’m not quite sure how indexes works.
Here’s how I understood it, please correct me if I’m wrong or confirm if I’m right:
I have the query:
SELECT * FROM people WHERE age < 40 AND country = 'United States'
My index is on country field.
It firstly searches the country (because there’s an index), makes a list of results and then searches a list for age < 40.
Am I right?
That might be what the DBMS chooses to do. Your DBMS will look at the SQL and generate a few possible “execution plans”, figure out how “expensive” they are, and choose the best one. Certainly the plan you described is one that the DMBS will likely consider, but it’s not 100% guaranteed to choose that plan.
It depends on a lot of other factors, including what the data looks like. The DBMS will try to choose plans that filter the data as early as possible, so that the data flowing through the system is minimized. If the DBMS can see that there are very few countries = ‘United States’, it may likely choose to process that part of the query first. This will make the subsequent operations cheaper.
For more information, run
MYSQL EXPLAIN(documentation) to see exactly what the DBMS chooses to do.