Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AGE [1, 2, 3] vs. AGE BETWEEN 1 AND 3

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?

like image 776
Truong Ha Avatar asked Apr 24 '11 09:04

Truong Ha


People also ask

What is the age difference between 1 and 2?

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

How do I use the age difference calculator?

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 ...

What is the age difference between 2 people in 4 years?

■ 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

What is the difference between age and age range?

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."


1 Answers

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.

like image 134
Johan Avatar answered Sep 30 '22 19:09

Johan