devxlogo

Advantages of EXISTS over IN Clause in a Query

Advantages of EXISTS over IN Clause in a Query

If you wish to retrieve from the department table all the department numbers that have at least one employee assigned to them, write the query as:

 select deptno, deptname from   dept where  deptno in 	 ( select deptno    from   emp) ;

This query will run a full table scan on both the emp and dept tables. Even if there was an index on the deptno column of emp table, the sub-query would not be using the index and, hence, performance would suffer.

We can rewrite the query as:

 select deptno, deptname from   dept where  exists in 	 ( select deptno    from   emp   where  dept.deptno = emp.deptno) ;

This query uses an existing deptno index on the emp table, making the query much faster. Thus, wherever possible use EXISTS in place of IN clause in a query.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist