While Executing SQL query, in Common Table Expression is where clause is different from join clause ?
I have created Database Schema called techTFQ and inside schema created table employee as table name. employee table further categorised into three columns named as emp_id, emp_name, salary
After inserting data into the table it looks like as depicted in figure below:](https://i.sstatic.net/nSuccqXP.png)
From this table I wanted to fetch the data of employees who earn more than average salary of all employees
My Query using Common Table Expression for this Question is:
with average_salary as ( select avg(salary) from employee ) select * from employee where salary > average_salary;
But this Query Generates Error :
15:04:37 with average_Salary as ( select avg(salary) from employee ) select * from employee where salary > average_salary Error Code: 1054. Unknown column ‘average_salary’ in ‘where clause’ 0.00072 sec
But when i use JOIN clause with the following SQL Query :
with average_salary_cte as (
select avg(salary) as average_salary
from employee
)
select *
from employee e
join average_salary_cte a
on e.salary > a.average_salary;`
Successfully executed the Query & gives output as i needed :](https://i.sstatic.net/zOpbrkw5.png)
Now, the Question is Why i’m not able to execute the code with First SQL query i.e
with average_salary as ( select avg(salary) from employee ) select * from employee where salary > average_salary;
`