Example: Ordering by a Column Alias Name - Teradata Vantage

Teradata® VantageCloud Lake

Deployment
VantageCloud
Edition
Lake
Product
Teradata Vantage
Published
January 2023
ft:locale
en-US
ft:lastEdition
2024-12-11
dita:mapPath
phg1621910019905.ditamap
dita:ditavalPath
pny1626732985837.ditaval
dita:id
phg1621910019905

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 table t1 fails because the ordering is specified 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;