Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of Order By 1 in SQL select statement?

People also ask

What is the purpose of the ORDER BY clause in SELECT statement?

The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns. Some databases sort the query results in an ascending order by default.

What is the meaning of ORDER BY 1/2 in SQL?

It will order the results by the first column, and then, if there are some rows with the same value in the first column it will order them by the second column.

What does ORDER BY 3 mean in SQL?

Employee] Order by 3 DESC. In this query, column birthdate is at the 3rd position; therefore, we can use three in the Order by clause to sort results on this column data. Note: I would not recommend using column position in Order By clause. You should always use a column name in Order by clause.

What is ORDER BY statement in SQL?

The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.


This:

ORDER BY 1

...is known as an "Ordinal" - the number stands for the column based on the number of columns defined in the SELECT clause. In the query you provided, it means:

ORDER BY A.PAYMENT_DATE

It's not a recommended practice, because:

  1. It's not obvious/explicit
  2. If the column order changes, the query is still valid so you risk ordering by something you didn't intend

This is useful when you use set based operators e.g. union

select cola
  from tablea
union
select colb
  from tableb
order by 1;

it simply means sorting the view or table by 1st column of query's result.


I believe in Oracle it means order by column #1


This will sort your results by the first column returned. In the example it will sort by payment_date.


As mentioned in other answers ORDER BY 1 orders by the first column.

I came across another example of where you might use it though. We have certain queries which need to be ordered select the same column. You would get a SQL error if ordering by Name in the below.

SELECT Name, Name FROM Segment ORDER BY 1