Performance
Readability
Using an implicit self-join in a correlated subquery in the WHERE clause can cause two problems.
An example. The employee table is used both in the outer and inner query
SELECT lastname
,firstname
,salary
FROM employee e1
WHERE e1.salary>(SELECT avg(salary)
FROM employee e2
WHERE e2.dept_id=e1.dept_id)
Using a window function instead of an implicit self-join will improve the query performance for most cases and also make it easier to understand.
SELECT lastname
,firstname
,salary
,AVG(salary) OVER(PARTITION BY dept_id) AS avg_sal
FROM employee
QUALIFY salary>avg_sal
If your database does not support the QUALIFY operator use a subquery
SELECT lastname
,firstname
,salary
FROM( SELECT lastname
,firstname
,salary
,AVG(salary) OVER(PARTITION BY dept_id) AS avg_sal
FROM employee)
WHERE salary>avg_sal
In some edge situations the implicit self-join can be more performant. The window function is generally more performant under the following conditions
It is a good idea to run a performance test to compare performance of the query with the self join to the performance of the window function.