The cost of performing an SQL query depends on many factors. The way to really know is to ask the database to actually perform the query and measure it:
That would be done with the EXPLAIN
command:
EXPLAIN ANALYZE VERBOSE SELECT * FROM my_table WHERE Name='Tom' AND age=18;
The database will output the execution plan that it decided that was the best (with the given configuration settings), together with the estimated and actual costs and row counts.
If the query is asumed to take a long running time, or you just want to know which is the execution plan that the database would execute, you can just use
EXPLAIN SELECT * FROM my_table WHERE Name='Tom' AND age=18;
This will just output estimated costs and number of rows.
For your specific case:
If the database doesn't have an index on columns Name
nor age
, it will be forced to perform a complete sequential scan
(that is, it will have to look all the rows in the table, and take only the ones where the condition Name='Tom' and age=18
is met).
If the database has one index on either the Name
or the age
columns, and the number of rows in the table is big, and the number of rows where Name
is 'Tom' or age
is 18 is (according to the statistics collected by it) is comparatively low, it will use this index to fetch only the rows where one of the conditions is met, and check whether the other condition is also met.
If the database has one multi-column index containing both columns as the first two (or the only two), such as (age, Name, ...) or (Name, age, ...) it will be able to fetch the rows by finding the rows it must retrieve by just using this index.
What the database actually does (by means of its query planner/optimizer) is: check all (or a reasonable number of) the possible execution plans to retrieve the information; make an educated guess at how long it will take to execute each of them, and choose the fastest (cheapest in terms of cost). Some parameters in the database configuration may further limit the plans which can be considered.
WHERE
conditions, the fewer hits, the faster the query. Basically. But that's guesswork while we don't know more about your schema and data. All Toms might be 18 years old ...