Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - Query most recent input based on username - VERY SLOW

I have a table being constantly inserted to with various usernames. I have a page a user can load which shows the most recent entry in the database that was posted by them.

An example of the query I'm using: SELECT timestamp FROM entry_list WHERE username='user' ORDER BY entry_id DESC LIMIT 1

There is a 2-column index in the table: username, timestamp . This index is being used according to the EXPLAIN query, with the following additional information:

select_type: SIMPLE
type: ref
key_len: 34
ref: const
rows: 5654
Extra: Using where; Using index; Using filesort

How can I optimize my query? It's fairly fast for a single user (0.2~0.4 sec), but some accounts load this information for 5, 10, or even 20 different users at once. Even 0.2~0.4 seems a bit long, and when it ends up slowing page load down by 4-8 seconds, it's unacceptable.

like image 332
Michael Marsee Avatar asked Jan 28 '26 07:01

Michael Marsee


1 Answers

Try SELECT MAX(timestamp) FROM entry_list WHERE username = 'user'

also, probably not the best idea to use reserved keywords as column names, try changing timestamp to insert_date or something like that

like image 107
Ascherer Avatar answered Jan 30 '26 22:01

Ascherer