Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
73 views9 pages

Sub Queries

Uploaded by

sriprasad.a14
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views9 pages

Sub Queries

Uploaded by

sriprasad.a14
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Sub Query: A select query contains another select query is called sub Query.

In this,
there will be two queries those are called as inner query and outer query.

Syntax: select * from <Table Name> where (condition) (select * from…….. (Select *
from….. (select * from……..)));

 Root query
 Parent query or outer query or main query
 Child query or inner query or sub query

Root query:-

The query which is not depend on any other query for its conditional value. Or
independent query.

Example:-sql>select ename,sal from emp where deptno=10;

Parent query:-

The query which is depend on any other query for its conditional v alue.

Example:-

Sql>select empno,ename,job from emp where job=(select job from emp where
ename=’SMITH’);

Sub query:-

the qurery which provides conditional values to its parent query.

A Query within another query is called nested query or Subquery, generally


child query is al called as subquery.

There are two type of subqueries supported by all database Systems.

1.non corelated subqueries.

2.corelated subqueries.

Non corelated subqueries:-

In non corelated subqueries child query is executed first then only parent query is
executed .
Non corelated subquery subqueries:-

1.single row subqueries

2.multiple row subqueries

Single row subqueries:-

Subqueries that can return only one or zero rows to the outer statement are
called single-row subqueries. Single-row subqueries are subqueries used with a
comparison operator in a WHERE, or HAVING clause.

Single-row subquery operators are =, >,<,>=,<=,<>,

Where clause always used for single row sub query,it return only one row hence it is
suitable for single row subquery.

Syntax:-

Select col1,col2,----- from table name where column name=(select column name from
table name);

Example for single row subqueries:-

SQL>select *from emp where sal>(select sal from emp where ename='SMITH');

Explaination:-the above example the inner query determines the salary of employee
smith.the outer query takes the result of the inner query and uses this result to display
all the employees who earn more than this salary

Sql>select *from emp where job=(select job from emp where empno=7566);

SQL>select *from emp where job=(select job from emp where ename='SMITH');

SQL>select *from emp where job=(select job from emp where ename='SMITH')

AND ENAME<>'SMITH';

Multiple-row subqueries

Sub queries return more than one row are called multiple-row sub queris.We use
multiple row operator,instead of single row operator,with multiple row subquery.

Multiple row operator expects one or more values.

Subqueries that can return more than one row (but only one column) to the outer
statement are called multiple-row subqueries.
A sub query always enclosed in parenthesis.

A sub query must appear on the right side of the comparision operator.

A sub query should not contain any order by clause.but over all select select statement
contain order by clause.

Multiple-row subqueries return sets of rows. These queries are commonly used to
generate result sets that will be passed to a DML or SELECT statement for further
processing. Both single-row and multiple-row subqueries will be evaluated once, before
the parent query is run.

Multiple-row subqueries are subqueries used with an IN, ANY, or ALL clause.

Since it returns multiple values, the query must use the set comparison operators (IN,
ALL, ANY). If you use a multi row sub query with the equals comparison operators, the
database will return an error if more than one row is returned. The operators in the
following table can use multiple-row subqueries:

Symbol Meaning

IN equal to any member in a list

ANY returns rows that match any value on a list

ALL returns rows that match all the values in a list

IN Operator:- The IN operator return TRUE if the comparison value is contained in the
list; in this case, the results of the subquery.

Example:-

The following statement finds the employees whose salary is the same as the minimum
salary of the employees in some department.

SQL> SELECT EName,SAL FROM EMP WHERE SAL IN (SELECT MIN (SAL)

FROM EMP GROUP BY DEPTNO);

Explaination:-the inner query is executed first,producing a query result.the main query


block is then processed and uses the values returned by the inner query to complete
its search condition.in fact the main query would appear to the oracle server as follows.

List all the employees Name and Sal working at the location 'DALLAS'

Sql>select ENAME, SAL, JOB FROM EMP WHERE DEPTNO IN(SELECT


DEPTNO FROM DEPT WHERE LOC ='DALLAS');

Sql> select ename,job,sal from emp

where sal in(select max(sal) from emp group by job);

sql> select ename,sal,deptno from emp

where sal in(select min(sal) from emp

group by deptno);

whenever we are using max,min functions in child queries and also tables

having large amount of data and also comparing number of values. Those

queries performance is very low.

To overcome this problem all database systems introduced subquery special operators
they are Any and all

Any Operator:-

The ANY operators work with the equal operators. The ANY operator returns
TRUE if the comparison value matches any of the values in the list.

* Display the employees whose salary is more than the maximum salary of the
employees in any department.

* any means that the value in the column that introduces the subquery must be greater
than at least one of the values in the list returned by the subquery, for a row to satisfy
the outer query.

Note:-

= any means equal to some value

The = any operator is an existence check; it is equivalent to in.

<any/some means less than the maximum value in the list.

>any/some means more than minimum value in the list.

SQL>SELECT ENAME, SAL FROM EMP

WHERE SAL>ANY (SELECT MAX (SAL) FROM EMP


GROUP BY DEPTNO);

Explaination:-the inner query executed first,producing list of salaries.In this list of


salaries takes the minimum salary and compare the outer query ,this minimum salary
more than which salaries that all are returned from outer query.

Sql> select ename,sal,deptno from emp where sal<some(1500,2850,2450);

SQL> select ename,sal ,deptno,job,sal from emp

where sal<any(select sal from emp

where job='SALESMAN');

expalination:-the any operator compare value to each value returned by a subquery.

The inner query executed first,producing a list of salaries .In this list of salries take the
maximum salary and compare the outer query ,this maximum salary below which
salaries that all returned from outer query.

SQL> select ename,job,sal from emp

where sal=any(select sal from emp

where job='SALESMAN');

NOTE:- =any it is equivalent to in operator.

All Operator:-

The ALL operator returns TRUE only if the comparison value matches all the
values in the list. It compares a value to every value returned by a query. The condition
evaluates to true if subquery doesn't yield any row.

Note:-

>all means more than the maximum value in the list.

<all means less than the minimum value in the list.

Display the employee detail with salary less than those whose job is 'manager'.

SELECT empno, ename, job, sal FROM EMP

WHERE sal < all (SELECT sal FROM EMP

WHERE job = 'MANAGER');


Explaination:-inner query is executed first,producing a list of salaries who job is
manager and list of salaries takes the minimum salary and this minimum salary
compare the outer salaries .this minimum salary below which salaries that all are
returned from the outer query.

Sql> select ename,job,sal ,deptno from emp

where sal>all(select sal from emp

where deptno=30);

Explaination:-inner query is executed first,producing a list of salaries who deptno is 30


.in this list of salaries takes the highest salary .In this highest salary compared to the
outer salaries .this highest salary more than which salaries that all are returned from the
main query.

Co-related sub query:-

Generally in non correlated subquery child query is first where as in corelated


subquery parent queries are executed first.

In co related subquery we must create on alias name in parent query table and pass
that alias name into child query where clause.

Generally these queries are used in denormalization process.

Denormalization is we are combining normalized tables into single table

In this case we are using corelated update,correlated delete.

Syntax for correlated sub query:-

SELECT column1,--- FROM t1 AS x

WHERE x.column1 operator (SELECT column1,----- FROM t2 AS y

WHERE x.column operator x.column);

Process steps:-

Step1:-get a candidate row row from parent table.

Step2:-then control transferred into chilid query where condition.

Step3:-based on evaluation value it compares with parent query.

Example:-
sql> select *from emp e where sal>(select avg(sal) from emp where job=e.job);

Explaination:-the outer query process first .The outer query result job is matching to
inner query job that time the where condition is true ,select the average salary of
matching job This average salary more than which salaries that all returned from outer
query.this process continue upto remaining jobs all are compared.

the below one is n-1 th method of correlated sub query:-

sql> select *From emp e1 where (1-1)=(select count(*) from emp e2 where
e2.sal>e1.sal);

Using a correlated subquery in an update:-

Sql> update emp e set ename=(select dname from dept d where

e.deptno=d.deptno);

Sql>UPDATE emp a

set sal = (select avg(sal)

from emp b

where

a.deptno = b.deptno)

where sal <

(select avg(sal) from emp c

where a.deptno = c.deptno);

Using a correlated subquery in a delete:-

Sql> delete from emp a where

a.sal = (select max(sal) from emp b

where a.deptno = b.deptno);

in corelated queries child query is executed for each row of parent query.

In non corelated subquery child query is executed only once


Generally in correlated subqueries child query is executed only once for parent query
table where as in correlated subqueries child query is

Executed for each row of parent table .when parent table contain large

Amount of data generally we do not use correlated sub queries.

Subqueries with EXISTS and NOT EXISTS:-

A subquery with Exist does not really return any data; it returns TRUE or FALSE. Exists
operator used in correlated sub query,this operator always returns Boolean value
either true or false. This operator performance is very high compared to in operator.
This operator used in where clause. In this case we are not allowed to use column
name. Always exists operator start searching machanisum when child query return
true.

Syntax:-

Select *from tablename aliasname

Where exists(select *from tablename where condition using aliasname);

Example:-

Sql> select *from dept d where exists(select *from emp e

where deptno=d.deptno);

explaination:-if the inner query condition is true, the exists operator perform the
top level query is executed depending on the inner query which values return
true, that values only return from the outer quety .

sql> select *from emp where deptno=10

and exists (select count(*) from emp

where deptno=20

and job='CLERK'

having count(*)>=2);

Note:-
in the case group by clause group by clause become as dummy clause so
without using group by we can use having.

Example for NOT EXIST: This query will work exactly the opposite to above. I.e except
for the sane sales_id all other records will be returned

sql> select *from dept d where not exists(select *from emp e

where deptno=d.deptno);

Explaination:-if the inner query condition is true,the not exists operator perform the,
inner query which values false that values only return from the outer query.

sql>select p.ename from emp p

where not exists (select *from emp c

where c.empno=p.mgr);

You might also like