AdventureWorks Database: Order a table in ASC or DESC condionally

SQL Query - AdventureWorks: Exercise-32 with Solution

32. From the following table write a query in SQL to ordered the BusinessEntityID column descendingly when SalariedFlag set to 'true' and BusinessEntityID in ascending order when SalariedFlag set to 'false'. Return BusinessEntityID, SalariedFlag columns.

Sample table: HumanResources.Employee

Click to view Full table

Sample Solution:

SELECT BusinessEntityID, SalariedFlag  
FROM HumanResources.Employee  
ORDER BY CASE SalariedFlag WHEN 'true' THEN BusinessEntityID END DESC  
        ,CASE WHEN SalariedFlag ='false' THEN BusinessEntityID END;

Sample Output:

               4|false       |
              11|false       |
              12|false       |
              13|false       |
              17|false       |
              18|false       |
              19|false       |
              20|false       |
              21|false       |
              22|false       |
              23|false       |
              24|false       |
              27|false       |
              28|false       |
              29|false       |
              30|false       |
              31|false       |

SQL AdventureWorks Editor:

Practice Online

Contribute your code and comments through Disqus.

Previous: Retrieve persons last name begins with R.
Next: Order table conditionally using case statement.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Share this Tutorial / Exercise on : Facebook and Twitter

SQL: Tips of the Day

T-SQL Cast versus Convert?

CONVERT is SQL Server specific, CAST is ANSI.

CONVERT is more flexible in that you can format dates etc. Other than that, they are pretty much the same. If you don't care about the extended features, use CAST.

Ref : https://bit.ly/3VKT5M8