[Solved] How to rewrite \'select top N syntax\' in mysql?

EverSQL Database Performance Knowledge Base

How to rewrite \'select top N syntax\' in mysql?

Database type:

With the help of many comments, I could make a query for selecting top 2 score for each subject for each person.

FROM test_result AS t
WHERE t.id In (SELECT TOP 2 id
               FROM test_result
               WHERE student = t.student 
               AND subject = t.subject
               ORDER BY score desc, id asc)
ORDER BY t.student asc, t.score asc;

This time I want to make this query in MYSQL.
Unfortunately, there isn't top syntax in MYSQL.
So, I searched the Internet and I finally get an answer like this:

set @num := 0, @type := '';

select type, variety, price
from (
   select type, variety, price,
      @num := if(@type = type, @num + 1, 1) as row_number,
      @type := type as dummy
  from fruits
  order by type, price
) as x where x.row_number <= 2;

Can anyone help me how to add one more condition on this query?

I'm sorry that I wasn't clear enough. I want the result to be "top 2 prices of each variety of each type of fruits without using 'group by' clause."

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 Correlated Subqueries (query line: 7): A correlated subquery is a subquery that contains a reference (column: student) to a table that also appears in the outer query. Usually correlated queries can be rewritten with a join clause, which is the best practice. The database optimizer handles joins much better than correlated subqueries. Therefore, rephrasing the query with a join will allow the optimizer to use the most efficient execution plan for the query.
  2. 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.
  3. 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.
  4. Mixed Order By Directions Prevents Index Use (query line: 15): The database will not use a sorting index (if exists) in cases where the query mixes ASC (the default if not specified) and DESC order. To avoid filesort, you may consider using the same order type for all columns. Another option that will allow you to switch one direction to another is to create a new reversed "sort" column (max_sort - sort) and index it instead.
Optimal indexes for this query:
ALTER TABLE `test_result` ADD INDEX `test_result_idx_id_student_score` (`id`,`student`,`score`);
ALTER TABLE `test_result` ADD INDEX `test_result_idx_student_subject` (`student`,`subject`);
The optimized query:
        test_result AS t 
        t.id IN (
                TOP 2 test_result.id 
                test_result.student = t.student 
                AND test_result.subject = t.subject 
            ORDER BY
                test_result.score DESC,
                test_result.id ASC
        t.student ASC,
        t.score ASC

Related Articles

* original question posted on StackOverflow here.