[Solved] Order by clause with multiple columns for different cases to sort

How to optimize this SQL query?

In case you have your own slow SQL query, you can optimize it automatically here.

For the query above, the following recommendations will be helpful as part of the 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. Mixed Order By Directions Prevents Index Use (modified query below): 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.
The optimized query:
SELECT
        student_details.roll_number,
        student_details.admission_date,
        student_details.student_name,
        student_details.total_marks,
        student_details.progress 
    FROM
        student_details 
    ORDER BY
        CASE 
            WHEN upper(:dir) = 'ASC' THEN decode(:sort,
            'student_name',
            student_details.student_name,
            'roll_number',
            student_details.roll_number,
            'admission_date',
            student_details.admission_date,
            'total_marks',
            student_details.total_marks,
            'progress',
            student_details.progress) END ASC,
CASE 
    WHEN upper(:dir) = 'DESC' THEN decode(:sort,
    'student_name',
    student_details.student_name,
    'roll_number',
    student_details.roll_number,
    'admission_date',
    student_details.admission_date,
    'total_marks',
    student_details.total_marks,
    'progress',
    student_details.progress) END DESC

Related Articles



* original question posted on StackOverflow here.