1

I have the below SQL query and want to know if there is a way to optimise the query.

SELECT * FROM LogEntry WHERE UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(updateTime) > 10;

Will adding index on updateTime improve the performance on something more can be done to improve the performance

1
  • Bug in query?? That only excludes rows in the last 10 seconds; won't that be nearly all the table? Commented Oct 12, 2017 at 17:22

3 Answers 3

5

Yes. You need to think of a way to remove the function on the column. So if I have the logic right:

SELECT le.*
FROM LogEntry le
WHERE le.updateTime < NOW() - interval 10 second;

This can then take advantage of an index on LogEntry(updateTime).

There are good reasons to explicitly list the columns being returned. This only has a small effect on performance -- unless the row size is quite big.

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

1 Comment

"Don't hide an indexed column (updateTime) inside a function (UNIX_TIMESTAMP and -)" is an important rule is optimization.
0

The first thing i would do is remove your select * and select specific columns

1 Comment

This is often useful, but not nearly as important for performance as Gordon's optimization.
0

In addition to the optimisation of the request, you may think about partitioning your table. For instance, you could partition the table LogEntry on updateTime by day. It would speed your request drastically if you have a lot of data in your table.

Note: to partition your table on updateTime, updateTime must be part of the primary key.

5 Comments

Partitioning will not help. The Optimizer cannot see unixTime inside that expression. So, it cannot do any pruning.
My suggestion was to partition the table in addition to Gordon's optimization
In this case, partitioning will not help with performance. (Furthermore, since only 10 seconds are excluded [maybe that is a bug], the entire table will be scanned.)
Besides the fact that there might be a bug in the query, could you explain why partitioning by date will not help the performance of a query searching by date?
SELECT ... WHERE x=1 AND date BETWEEN... works excellently with INDEX(x,date). Adding partitioning will not speed it up; it would then need to do "partition pruning" before using the index. Do you have an example for me to critique?

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.