[Solved] Query of getting distinct latest value from table

EverSQL Database Performance Knowledge Base

Query of getting distinct latest value from table

Database type:

In MySQL I am trying to get the only one latest data of each user. I am cureently doing the following query

SELECT DISTINCT username, value, date
FROM table
WHERE date >=  CURDATE()
ORDER BY date DESC

Its returning all the values by username and the query is to slow. Is there any way to make it faster and get only one latest value of each user?

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
ALTER TABLE `table` ADD INDEX `table_idx_date` (`date`);
The optimized query:
SELECT
        DISTINCT table.username,
        table.value,
        table.date 
    FROM
        table 
    WHERE
        table.date >= CURDATE() 
    ORDER BY
        table.date DESC

Related Articles



* original question posted on StackOverflow here.