DF002: In the ORDER BY clause, constants are used to specify the position of columns in the SELECT list.

Last modified: December 25, 2024

The topic describes the DF002 T-SQL code analysis rule.

Category

BEST PRACTICE

Message

Order by with constant.

Description

In the ORDER BY clauses, constants are used to specify the position of columns in the SELECT list.

Additional information

Avoid specifying integers in the ORDER BY clause to represent the positions of columns in the select list. For example, while a statement such as SELECT ProductID, Name FROM Production.Production ORDER BY 2 is technically valid, but it can be confusing for others to understand compared to specifying the actual column name. In addition, any changes to the select list, such as rearranging column order or adding new columns, particularly before the existing columns in the select list, would require modifying the ORDER BY clause to prevent unexpected results.

Noncompliant code example

SELECT FirstName, LastName
FROM Sales.Customers
ORDER BY 1;

Compliant solution

SELECT FirstName, LastName
FROM Sales.Customers
ORDER BY FirstName;