17.05 - Example: Ordering By a Column Alias Name - Advanced SQL Engine - Teradata Database

Teradata Vantage™ - SQL Data Manipulation Language

Product
Advanced SQL Engine
Teradata Database
Release Number
17.05
Release Date
January 2021
Content Type
Programming Reference
Publication ID
B035-1146-175K
Language
English (United States)

You cannot explicitly order by a column alias name. You must specify the column position of the column aliased by the name in the select list.

Suppose you have the following base table definition:

   CREATE TABLE t1
    (i INTEGER,
     j INTEGER,
     k INTEGER);

The following query against this table fails because it specifies ordering on the column alias name j, which the system interprets as column j in table t1 rather than as the expression SUM(t1.j):

   SELECT t1.i, SUM(t1.j) AS j, t1.k
   FROM t1
   GROUP BY 1,3
   ORDER BY j;
   *** Failure 3504 Selected non-aggregate values must be part of the associated group.

The following rewrite of the query successfully performs the desired ordering:

   SELECT t1.i, SUM(t1.j) AS j, t1.k
   FROM t1
   GROUP BY 1,3
   ORDER BY 2;