SQL SERVER – How to Order By a Parameter?

There are no stupid questions or smart questions, they are all information. Recently while working with a huge telecommunication organization on Comprehensive Database Performance Health Check, we figured out that one of the stored procedures is taking too long to run for a client. After a quick investigation, we figured out that there was a very poor code written in one of the Stored Procedure’s Order By clause which accepts parameters. Let us learn today how to order by a parameter.

SQL SERVER - How to Order By a Parameter? orderbyaparameter-800x323

Order By a Parameter

Let us discuss a scenario. We have a  sample database WideWorldImporters and we have a table called Sales.Invoices. Now let us assume that we want to order the table ascending and descending based on the sort direction and also based on columns passed in the variable. Here is the T-SQL example of how we can do that easily.

DECLARE @SortDirection VARCHAR(10);
DECLARE @SortBy VARCHAR(100);
SET @SortDirection = 'D';
SET @SortBy = 'InvoiceID';
SELECT *
FROM [Sales].[Invoices]
ORDER BY
    CASE WHEN @SortDirection = 'A' THEN
        CASE 
           WHEN @SortBy = 'OrderID' THEN OrderID
           WHEN @SortBy = 'InvoiceID' THEN InvoiceID 
        END
    END ASC
    , CASE WHEN @SortDirection = 'D' THEN
        CASE 
           WHEN @SortBy = 'OrderID' THEN OrderID
           WHEN @SortBy = 'InvoiceID' THEN InvoiceID  
        END
    END DESC;

In the above example, @SortDirection is descending and the column to SortBy is InvoiceID. You can use see how the Order by constructed in the above example and also add more columns if you want to. There are many such simple tricks out there but often we miss them out. Once I fixed the example for the stored procedure, the stored procedure started to work efficiently.

Here are a few related blog posts:

If you have any such example, please post it here and I will be happy to post it with due credit to you. SQL Server is a very interesting subject. You can connect with on LinkedIn here.

Reference: Pinal Dave (https://blog.sqlauthority.com)

SQL CASE, SQL Order By, SQL Scripts, SQL Server
Previous Post
How to Find IP Address of All SQL Server Connection? – Interview Question of the Week #280
Next Post
Why SQL Server Doesn’t Give the Memory Back to OS?

Related Posts

7 Comments. Leave new

  • Good info.

    Reply
  • Sorry, got it now…

    Reply
  • Antonio Ortiz
    June 11, 2020 4:10 am

    Excelente

    Reply
  • Evelyn Portnaya
    December 30, 2021 2:04 am

    Hello,
    I have two issues with this
    1. That “select * ” works perfect, but when I add “distinct” and list of fields I get error “ORDER BY items must appear in the select list if SELECT DISTINCT is specified.” even so all fields listed.

    2. I need to sort either by ID or by Name
    In your example both sorting fields are integers. In my case one integer and another one is varchar. And when I switch to the second one I get an error :”Conversion failed when converting the varchar value….. to data type int.”

    I would love to hear from you

    Evelyn, long term subscriber :)

    Reply
  • if want sort by date at a once & string at a once, if is throwing error as below

    CODE:

    ORDER BY
    CASE WHEN @P_ShortDirection = ‘asc’ THEN
    CASE
    WHEN @P_ShortBy = ‘Title’ THEN Title
    WHEN @P_ShortBy = ‘SubmittedDate’ THEN SubmittedDate
    END
    END ASC
    , CASE WHEN @P_ShortDirection = ‘desc’ THEN
    CASE
    WHEN @P_ShortBy = ‘Title’ THEN Title
    WHEN @P_ShortBy = ‘SubmittedDate’ THEN SubmittedDate
    END
    END DESC

    ERROR:
    Conversion failed when converting date and/or time from character string.

    Reply
    • If you’re mixing datatypes in your sort you’ll have to create case statements for each type e.g.

      ORDER BY

      CASE WHEN @SortBy = ‘OrderID’ AND @SortDirection = ‘A’ THEN OrderID END ASC,
      CASE WHEN @SortBy = ‘InvoiceID’ AND @SortDirection = ‘A’ THEN InvoiceID END ASC,

      CASE WHEN @SortBy = ‘OrderID’ AND @SortDirection = ‘D’ THEN OrderID END DESC,
      CASE WHEN @SortBy = ‘InvoiceID’ AND @SortDirection = ‘D’ THEN InvoiceID END DESC

      Reply
      • Hi @gmb, you saved my life. It does indeed need each case statements for each type when then are different datatypes

Leave a Reply