Link to home
Start Free TrialLog in
Avatar of sath350163
sath350163

asked on

OUTER JOIN and EXISTS condition

Hello,

 User generated image
The embedded image in this post has sample table structure and data related to my question.
Please refer to it.

Criteria
I want employee rec to be returned in the output if it satisfies any of the below 3 criterias:
If Employee's salary is > 0
or
If Employee exist in the EmployeeStatus table with EmpStatus as 'Active'
or
If Employee does not exist in the EmployeeStatus table


I should not get Employee = 4 in output as Kate's salary is 0, and although exist in the EmployeeStatus table, the EmpStatus is 'Inactive'                                                                  


Question:

I am trying to achieve this using EXISTS clause, but the problem is that when I use EXISTS, only Employee record that also exists in the EmployeeStatus gets returned.

Can you please show me how to achieve this using EXISTS approach, OUTER JOIN Approach, as well as anyother approach that would easily solve this problem.


Thanks!
ASKER CERTIFIED SOLUTION
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sath350163
sath350163

ASKER

Thank you so much for the response.


Can you also show me how to do this using CROSS APPLY (if its doable) and using OUTER JOIN?

Thanks!
Would this approach work?

SELECT *
FROM Employee e LEFT OUTER JOIN EmployeeStatus es
ON e.Eno = es.Eno
AND (e.Salary > 0.00 OR es.EmpStatus = 'ACTIVE' OR es.EmpStatus IS NULL) 

Open in new window


When I execute this sql, I get the Eno = 4 also in the result, along with others.

But Eno = 4 has salary =0 and the EmpStatus is 'INACTIVE' in EmpStatus table,
So technically this Employee record should not be returned in the resultset.

What is the problem here?
Is sql server applying the condition for merging the records between the two tables, and not for filtering?

Thanks!
CROSS APPLY is not usable here ....


I would have said that your LEFT JOIN should work, but visible it does not ...
but I wonder why.
I have tested that my syntax does work ...

let me check if I find something on this ...
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial