Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is ordering done by actual column or alias?

Let's say I have a simple query like this:

select 
    subgroup,
    subgroup + ' (' + cast(grade as varchar(1)) + 'G)' as grade, 
    count(*) as 'count' 
From table_empl 
where year(EnterDate) = year(getdate())  
group by subgroup, grade  
order by grade  

It seems that order by grade is being ordered by the alias grade instead of the actual column grade; at least that's what the result shows.

Is this correct?

Since I can't change the columns that are included in the result, is the solution to add an alias to the actual column? Something like this?

select 
    grade as 'grade2', 
    subgroup,
    subgroup + ' (' + cast(grade as varchar(1)) + 'G)' as grade,
    count(*) as 'count'
From table_empl 
where year(EnterDate) = year(getdate())  
group by subgroup,grade  
order by grade2
like image 504
fdkgfosfskjdlsjdlkfsf Avatar asked Dec 10 '25 19:12

fdkgfosfskjdlsjdlkfsf


1 Answers

If you prefix the column name by its table name (or an alias given to the table in the FROM clause) in the ORDER BY clause, then it will use the column, not the expression computed in the SELECT clause and given the same name as the column.

So this should sort using the original grade column:

select 
    subgroup,
    subgroup + ' (' + cast(grade as varchar(1)) + 'G)' as grade, 
    count(*) as 'count' 
From table_empl 
where year(EnterDate) = year(getdate())  
group by subgroup, grade  
order by table_empl.grade

Or:

select 
    subgroup,
    subgroup + ' (' + cast(grade as varchar(1)) + 'G)' as grade, 
    count(*) as 'count' 
From table_empl t
where year(EnterDate) = year(getdate())  
group by subgroup, grade  
order by t.grade
like image 165
Damien_The_Unbeliever Avatar answered Dec 12 '25 18:12

Damien_The_Unbeliever



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!