Home

Column names should be used in an ORDER BY clause

Description

    This rule states that when using the ORDER BY clause in SQL Server, column names should be used instead of column numbers. This ensures that the ordering of the results is based on the columns that are specified, and not on the order of the columns in the table.

    For example, if you wanted to order a table by the columns "FirstName" and "LastName", you should use the following code:

    ORDER BY FirstName, LastName

    Instead of using the column numbers, which may change in the future, this rule ensures that the ordering of the results is always based on the specified columns.

Key Benefits

  • Accuracy: Using column names in an ORDER BY clause ensures that the sorting is accurate and consistent.
  • Efficiency: Using column names in an ORDER BY clause can improve query performance, as the database engine can more quickly identify the columns to be sorted.
  • Readability: Using column names in an ORDER BY clause makes the query easier to read and understand.

 

Non-compliant Code Example

SELECT ProductID, Name, Color  
FROM Production.Product  
ORDER BY 1;  --Non compliant code (Column name is not used in Order by Clause)

Compliant Code Example

SELECT ProductID, Name, Color, ListPrice  
FROM Production.Product  
ORDER BY ListPrice;  --Compliant code (Column name is used in Order by Clause)
Visual Expert 2024
 VETSQLRULE33