[Solved] SQL Select Unique Entires

EverSQL Database Performance Knowledge Base

SQL Select Unique Entires

I have in my table:

ID Name   Age
1  James  15
2  James  16
3  Joseph 16
4  Joseph 18
5  Steve  4

and I want to return:

5 Steve 4
1 James 15
3 Joseph 16

ie. Unique entries based on the Name row (choose the one with lowest ID when there are multiple of the same Name), and ordered by Age

What would be the correct SQL statement?

I have:

Select * FROM table Where True GROUP BY Name ORDER BY Age

It seems to be returning a lot of unique results, but it's too slow (table has >250,000 entries and it takes >30seconds to process), I wonder if there is a faster way to do this?

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. Avoid Selecting Unnecessary Columns (query line: 2): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
  2. 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_name` (`Name`);
The optimized query:

Related Articles

* original question posted on StackOverflow here.