I have an InnoDB table and an index on age
column just like this
CREATE TABLE Person (
....
age int(11) not null;
key (age);
....
) engine=InnoDB;
I just want to know the real things behind these queries:
SELECT * FROM Person WHERE age IN [1, 2, 3];
and
SELECT * FROM Person WHERE age BETWEEN 1 AND 3;
As what I've learnt, the first one MySQL will use the index on column age while the second one it can't use. Is it? Which is better for performance?
The age difference between the two persons is 4 years, 4 months, 12 days. Person 2 is older than Person 1 with 4 years, 4 months, 12 days. Person 1 is 24 years, 9 months, 7 days old, while Person 2 is 20 years, 4 months, 26 days old. The “half your age plus seven” rule of age difference
Using the Age Difference Calculator 1 Age Difference: We'll report back who is older and how much older they are 2 Person One Age: We report the first person's age in years and days 3 Person Two Age: The second person's age today in years and days More ...
■ The age difference between the two persons is 4 years, 4 months, 12 days. ■ Person 2 is older than Person 1 with 4 years, 4 months, 12 days. ■ Person 1 is 24 years, 9 months, 7 days old, while Person 2 is 20 years, 4 months, 26 days old. The “half your age plus seven” rule of age difference
Age is usually used to describe a single age, but can be used for a range as well, as in "children age 5 to 10." Ages is used commonly for ranges ("children ages 5 to 10"). The adjective aged can be used, but it occasionally draws criticism as some prefer it reserved for things like wines and cheese, or in combining forms like "college-aged."
Both queries will use an index.
Query A will translated to:
select * from person where age = 1 or age = 2 or age 3;
Query B will translate to
select * from person where age >= 1 and age <= 3;
So query A will do 3 tests using OR.
Query B will do 2 tests using AND.
Query B is faster.
In general, queries using AND
are faster than queries using OR
.
Also Query B is doing fewer tests and because it's testing a range it can more easily exclude results that it does not want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With