I’m trying to optimize the following query. I’ve used EXPLAIN to troubleshoot but it keeps showing up in our logs as a non-indexed query. What am I missing? I’ve created indexes on all columns referenced, but it’s still showing up.
select `users`.`nickname`, `users`.`userId`, `userdata`.`avatarUpdatedAt` from `users` inner join `userdata` on `userdata`.`userId` = `users`.`userId` order by `lastActivity` desc limit 28
+---+---+---+---+---+---+---+---+---+---+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +---+---+---+---+---+---+---+---+---+---+ | 1 | SIMPLE | users | index | PRIMARY,userId | lastActivity | 8 | NULL | 28 | | | 1 | SIMPLE | userdata | eq_ref | userdata_userid_unique | userdata_userid_unique | 8 | prod.users.userId | 1 | Using index condition | +---+---+---+---+---+---+---+---+---+---+
# Time: 200703 6:14:18 # User@Host: prod[prod] @ localhost [127.0.0.1] # Thread_id: 17988 Schema: prod QC_hit: No # Query_time: 0.000201 Lock_time: 0.000011 Rows_sent: 28 Rows_examined: 56 # Rows_affected: 0 Bytes_sent: 1039 # Full_scan: Yes Full_join: No Tmp_table: No Tmp_table_on_disk: No # Filesort: No Filesort_on_disk: No Merge_passes: 0 Priority_queue: No
Advertisement
Answer
If you have a big table which contains millions of row, it would be the best to have where
condition to filter out the data to make query run faster.
Indexing will help in retrieving data so just having index does not make query to run faster.
select u.nickname, u.userId, ud.avatarUpdatedAt from users u inner join userdata ud on ud.userId = u.userId where ud.avatarUpdatedAt >= '2020-01-01' and ud.avatarUpdatedAt <= '2020-05-01' order by lastActivity desc