📜  order by with when (1)

📅  最后修改于: 2023-12-03 14:44:57.659000             🧑  作者: Mango

Order By with WHEN

ORDER BY is a commonly used clause in SQL which allows us to sort the results of a query based on specified criteria. In combination with the WHEN keyword, it allows us to customize the sort order of the query result based on certain conditions.

Syntax

The syntax for using ORDER BY along with WHEN is as follows:

SELECT column1, column2, ...
FROM table_name
ORDER BY
  column1,
  column2,
  ...,
  columnN
  WHEN column1 = value1 THEN 1
  WHEN column2 = value2 THEN 2
  ...
  ELSE N+1

Here, the ORDER BY clause is followed by a list of columns that we want to sort by. The WHEN keyword is then used to specify conditions that determine the priority of sorting. If the condition in WHEN is true, then the result is sorted based on the associated priority value. If not, the result moves on to the next WHEN condition. The ELSE keyword is used to specify a default priority value.

Example

Suppose we have a table named Employees with the following columns:

  • EmployeeID
  • EmployeeName
  • Salary
  • Department

We want to sort the result by Department first and then by Salary, with the employees in the 'Sales' department appearing at the top of the sorted list. We can achieve this using the following query:

SELECT EmployeeID, EmployeeName, Salary, Department
FROM Employees
ORDER BY
  Department,
  Salary,
  WHEN Department = 'Sales' THEN 1
  ELSE 2

In this example, if the Department is 'Sales', then the result will be sorted with a priority value of 1, causing these employees to appear at the top of the sorted list. If the Department is not 'Sales', then the default priority value of 2 is used.

Conclusion

In conclusion, using ORDER BY with WHEN in SQL allows us to apply conditional sorting based on specified criteria. By using this technique, we can create more complex sorting rules that make it easier to read and analyze the results of our query.