# Alias reference in SQL

**URL:** <https://forum.codewithmosh.com/t/alias-reference-in-sql/18478>\
**Category:** SQL\
**Created:** [March 1, 2023, 12:46pm UTC](https://forum.codewithmosh.com/t/alias-reference-in-sql/18478 "2023-03-01T12:46:34Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![rohit4334](https://avatars.discourse-cdn.com/v4/letter/r/a698b9/32.png) [@rohit4334](https://forum.codewithmosh.com/u/rohit4334)\
**Post date:** [March 1, 2023, 12:46pm UTC](https://forum.codewithmosh.com/t/alias-reference-in-sql/18478/1 "2023-03-01T12:46:34Z")

</div>

i am in the " subquery in select Clause " chapter to SQL module  
just wanted to confirm or correct my understanding that, the ALIAS used for a subquery can be used in calculation of difference using SELECT and alias name , however we cannot use Alias name denoted to without subquery to a calculation

say

select  
client\_id, name,  
SUM(invoice\_total) AS total,  
(  
select AVG(invoice\_total)  
from invoices  
)  
AS AVG

and now trying to find diff between AS total and AS Avg columns

(  
SELECT total - AVG  
)  
AS difference

error -Error Code: 1247. Reference ‘AB’ not supported (reference to group function)

complete code

select  
client\_id, name,  
SUM(invoice\_total) AS AB,  
(  
select AVG(invoice\_total)  
from invoices  
)  
AS AV,  
(  
SELECT AB - AV  
)  
AS difference

```
from Clients
left JOIN Invoices USING (Client_id)
GROUP BY client_id

```
