Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting the Sql table using alias column

I have a sql select statement which contains some columns that are computed from some other columns or tables. I gave a name for this column using As keyword.

Now, I want to sort this table by the computed column. I cant use that name for sorting.

Someone please help to sort the sql table using computed column.

like image 976
Kokila Avatar asked May 06 '13 11:05

Kokila


People also ask

Can we sort column using column alias in SQL?

Sort Items Based on Host Variable Values Specify the ASC and DESC argument after the CASE END keyword. You must specify fields in a CASE expression by column name. Column aliases and column numbers are not permitted in this context.

Can you sort by alias in SQL?

Due to logical query processing order, alias can be used in order by.

Can we ORDER BY alias?

You can use the alias in GROUP BY, ORDER BY, or HAVING clauses to refer to the column.

Can we use column alias in ORDER BY clause Oracle?

In ORDER BY you can refer to column aliases in the SELECT clause. This is what's happening in query 2. It isn't sorting by the values in the column.


2 Answers

In older versions of SQL Server, you can define the alias in a subquery:

select  *
from    (
        select  col1 + col2 as col3
        from    YourTable
        ) SubQueryAlias
order by
        col3

In SQL Server 2008+ you should be able to order by an alias without a subquery:

select  col1 + col2 as col3
from    YourTable
order by
        col3
like image 197
Andomar Avatar answered Oct 16 '22 20:10

Andomar


one more option you can use COLUMN INDEX NUMBER in order by as show in follwoing example

select ACol,AVal,CAST(ACol as varchar(3)) + aval as 'New' from ABC order by 3

this will use 'New' columnd to sort

like image 29
Dhaval Avatar answered Oct 16 '22 19:10

Dhaval