Teradata Order By Clause

Teradata Order By clause sorts the result set based on the given expression. It is used with SELECT Statement to determine how the result set will be selected. If the order by clause is not used, then the result-set remains unsorted.

Teradata ORDER BY Clause Syntax

The syntax of the Teradata ORDER BY clause is as below.

SELECT column1, column2, ......,columnN
FROM DatabaseName.TableName
ORDER BY expression [ NULL First | NULL Last ];

Here,

expression can be three types. They are-

  • expression as column_name – The name of the column by which you want to sort the result-set.
  • expression as column_name_alias – The alias name of the column by which you want to sort the result-set.
  • expression as column_position – You can specify the position of the column in the select list.
  • ASC|DESC – Result-set can be ordered in ascending order or descending order.
  • NULL First – Null results are to be listed first.
  • NULL Last – Null results are to be listed last.

Teradata ORDER BY example

Suppose we have a student table stored in our Teradata database.

Now if you run the select statement on the table, you will get the following output.

SELECT * FROM TERADATAPOINT.STUDENT_RANK;

Output:

Teradata ORDER BY

Here you can see that the result-set is unsorted.

If you want to sort the result set on rollno, you can use the ORDER BY clause as below.

SELECT * FROM TERADATAPOINT.STUDENT_RANK order by rollno;

Output:

Teradata order by ascending

By default, Teradata will sort the rows in ascending order.

You can sort the result-set in descending order as well using the DESC keyword.

SELECT * FROM TERADATAPOINT.STUDENT_RANK order by rollno DESC; 

teradata order by descending