Michael A
Michael A

Reputation: 9930

Can I be more specific with SQL ordering?

I have the following SQL query:

SELECT  w.financial_year ,
        ISNULL(e.entity_name, 'Entity code ' + CAST(w.integer_1 AS VARCHAR) + ' is not available on the entity table. Please add.') ,
        COUNT(w.form_guid)
FROM    portal.workflow AS w
        LEFT OUTER JOIN property.entity AS e -- MS: Do not make inner join! Left outer join allows for exceptions to this case to be handled. Important as source data doesn't use property.entity
            ON w.integer_1 = e.entity_id
GROUP BY
        w.financial_year ,
        w.integer_1 ,
        e.entity_name
ORDER BY
        w.financial_year , e.entity_name

With my ordering I would like to show cases where e.entity_name was null first, and then sort the rest of the column alphabetically.. Is such a thing even possible?

Upvotes: 1

Views: 72

Answers (3)

Andrey Khmelev
Andrey Khmelev

Reputation: 1161

use NULLS FIRST or NULLS LAST in clause ORDER BY like this:

SELECT  w.financial_year ,
        ISNULL(e.entity_name, 'Entity code ' + CAST(w.integer_1 AS VARCHAR) + ' is not available on the entity table. Please add.') ,
        COUNT(w.form_guid)
FROM    portal.workflow AS w
        LEFT OUTER JOIN property.entity AS e -- MS: Do not make inner join! Left outer join allows for exceptions to this case to be handled. Important as source data doesn't use property.entity
            ON w.integer_1 = e.entity_id
GROUP BY
        w.financial_year ,
        w.integer_1 ,
        e.entity_name
ORDER BY
        w.financial_year , e.entity_name NULLS FIRST

Upvotes: 0

Himanshu
Himanshu

Reputation: 32612

You can try this:

ORDER BY
        CASE WHEN e.entity_name IS NULL 
             THEN 0 
             ELSE w.financial_year END 
        ,e.entity_name

See this SQLFiddle

Upvotes: 2

Charles Bretana
Charles Bretana

Reputation: 146603

of course,

  SELECT w.financial_year,
    ISNULL(e.entity_name, 'Entity code ' + CAST(w.integer_1 AS VARCHAR) + 
        ' is not available on the entity table. Please add.') ,
    COUNT(w.form_guid)
  FROM portal.workflow AS w
     LEFT JOIN property.entity AS e
         ON w.integer_1 = e.entity_id
  GROUP BY case When e.entity_name Is Null Then 0 Else 1 End,
        w.financial_year, w.integer_1, e.entity_name
  ORDER BY case When e.entity_name Is Null Then 0 Else 1 End, 
      w.financial_year, e.entity_name

Upvotes: 3

Related Questions