Rahul Banerjee - 1 year ago 73
SQL Question

# How to use order by on a calculated field in SQL?

How to use order by on a calculated field in SQL?

``````select a.Customer
,a.PlanTo
,a.Dollar01
,a.Dollar02
,a.Dollar03
,a.Dollar04
,a.Dollar05
,a.Dollar06
,a.Dollar07
,a.Dollar08
,a.Dollar09
,a.Dollar10
,a.Dollar11
,a.Dollar12
,(CAST(a.Dollar01 as decimal) + CAST(a.Dollar02 as decimal)
+ CAST(a.Dollar03 as decimal) + CAST(a.Dollar04 as decimal)
+ CAST(a.Dollar05 as decimal) + CAST(a.Dollar06 as decimal)
+ CAST(a.Dollar07 as decimal) + CAST(a.Dollar08 as decimal)
+ CAST(a.Dollar09 as decimal) + CAST(a.Dollar10 as decimal)
+ CAST(a.Dollar11 as decimal) + CAST(a.Dollar12 as decimal)) as TOTAL1
from MDM_STAT.sds.SMarginText a
where a.salesyear = '2016'
order by a.total1
``````

This is giving me 'Total1' column does not exist but as you see I have created it and is working if I am not using the
`order by`
clause.

Answer Source

You can do what Mureinik suggests and use the ordinal notation of `ORDER BY 13`, which means "order by the 13th column." However, I would tend to avoid it because it's difficult to tell what you're intending to order by if you come back later. Also, if you need to add a column or change the order, you have to remember to update the ORDER BY clause. It's easy to miss that.

As others mention in the comments, it is possible to use the alias you specify in the ORDER BY. However, because it's a column alias, there's nothing to fully qualify. `a.TOTAL1` doesn't mean anything. You must `ORDER BY TOTAL1`:

``````select a.Customer
,a.PlanTo
,a.Dollar01
,a.Dollar02
,a.Dollar03
,a.Dollar04
,a.Dollar05
,a.Dollar06
,a.Dollar07
,a.Dollar08
,a.Dollar09
,a.Dollar10
,a.Dollar11
,a.Dollar12
,(CAST(a.Dollar01 as decimal) + CAST(a.Dollar02 as decimal)
+ CAST(a.Dollar03 as decimal) + CAST(a.Dollar04 as decimal)
+ CAST(a.Dollar05 as decimal) + CAST(a.Dollar06 as decimal)
+ CAST(a.Dollar07 as decimal) + CAST(a.Dollar08 as decimal)
+ CAST(a.Dollar09 as decimal) + CAST(a.Dollar10 as decimal)
+ CAST(a.Dollar11 as decimal) + CAST(a.Dollar12 as decimal)) as TOTAL1
from MDM_STAT.sds.SMarginText a
where a.salesyear = '2016'
order by total1
``````

This works because of the query solve order. ORDER BY is solved after the SELECT, unlike WHERE or FROM which are solved before the SELECT and therefore can't refer to column aliases in SQL Server.

This can be confusing or ambiguous if your column alias has the same name as a column from a table, so you need to be aware of that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download