[Solved] ORDER BY followed by a number
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

ORDER BY followed by a number

I took this query from this question.

SELECT *
FROM A 
WHERE x='abc' 
    OR y=0
order by case when x='abc' then 0 else 1 end;

This query supposedly will prioritize x='abc' cases. But I'm really confused why is this happening? Isn't ORDER BY followed by a column name or column number? Also, I researched on the syntax of ORDER BY and they don't tell anything about this. I also tried something like this but it says: "1st ORDER BY term out of range - should be between 1 and 1":

SELECT A
FROM B
ORDER BY 2

So, can anyone explain this query or at least point to a good documentation? Thank you very much.

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.
The optimized query:
SELECT
        * 
    FROM
        A 
    WHERE
        A.x = 'abc' 
        OR A.y = 0 
    ORDER BY
        CASE 
            WHEN A.x = 'abc' THEN 0 
            ELSE 1 END

Related Articles



* original question posted on StackOverflow here.