Search code examples
sqloracle-databasesubquerywhere-clause

Using a SQL correlated sub-query with exists operator


I'm trying to find all records in the job_history table with their department_ID is not the same as department_id in employees table by using a correlated sub-query with exists operator, however, I'm getting the error code:

ORA-00933: SQL command not properly ended

Can someone tell please tell me what I'm doing wrong based on the schema and code below?

Select * 
from Job_History as J 
where Exists(Select * from hr.Employees e where e.Department_ID != J.Department_ID);

enter image description here


Solution

  • Here:

    from Job_History as J 
    

    Oracle does not support keyword as to alias a table (it is supported in column aliases only).

    You also most probably want a correlation clause on the employee_id in the subquery.

    So:

    select * 
    from job_history j 
    where exists (
        select 1 
        from hr.employees e 
        where e.employee_id = j.employee_id and e.department_id <> j.department_id
    );