Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ORDER BY 1,2,3,4

Tags:

sql

sql-server

What does order by 1, 2, 3, 4 stand for?

like image 997
Robertuzzo Avatar asked Mar 21 '26 15:03

Robertuzzo


1 Answers

Sort by ordinal positions of columns

SQL Server allows you to sort the result set based on the ordinal positions of columns that appear in the select list.

The following statement sorts the customers by first name and last name. But instead of specifying the column names explicitly, it uses the ordinal positions of the columns:

SELECT
    first_name,
    last_name
FROM
    sales.customers
ORDER BY
    1,
    2;

In this example, 1 means the first_name column and 2 means the last_name column.

Using the ordinal positions of columns in the ORDER BY clause is considered as bad programming practice for a couple of reasons.

  1. First, the columns in a table don’t have ordinal positions and need to be referenced by name.
  2. Second, when you modify the select list, you may forget to make the corresponding changes in the ORDER BY clause.

Therefore, it is a good practice to always specify the column names explicitly in the ORDER BY clause.

For more details, go Here

like image 67
mkRabbani Avatar answered Mar 24 '26 19:03

mkRabbani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!