1

I have a table with a certain column say created_time with datatype as datetime. It is also one of the primary key on that table.

Now when I try to query a date range created_time BETWEEN :startTime AND :endTime , it ends up looking through the entire table as I can see from the execution plan.

Now, there is another primary key column sensor_time with data type as INT which stores the time in unix format. When I use the range in this, it only looks through the database for a small subsection.

Please someone explain me why the range does not work efficiently with the datetime type even though it is a primary key.

2
  • date_time is not a data type Commented Jun 10, 2020 at 12:06
  • Sorry, I meant datetime. I have corrected it. Commented Jun 10, 2020 at 14:05

1 Answer 1

1

It is also one of the primary key on that table.

Uh. This is not possible. A primary key is a set of columns with the following characteristics:

  • The values are never NULL.
  • The combination of the column(s) in a given row are always unique.
  • There is only one primary key.

You probably have a composite primary key, composed of multiple columns. In that case, datetime filters would only be used for a query with this restriction:

where created_time between ? and ?

when created_time is the FIRST column in the primary key. Otherwise, the preceding columns need equality comparisons.

It sounds like you want a second column on datetime with that as the first column in the index (if there are multiple columns).

Sign up to request clarification or add additional context in comments.

2 Comments

My primary goal is to query between a specified range of dates without having to go for a full table lookup. Is it achievable in my case ?? Sorry, I didn't get the last paragraph.
@VikrantPradhan . . . Create a secondary index on created_time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.