0% found this document useful (0 votes)
8 views

9) SubQuery

Uploaded by

Hariom Thadke
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

9) SubQuery

Uploaded by

Hariom Thadke
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 9

SUBQUERY:

==========
- a query inside another query is called as subquery / nested query.

syntax:
=======
select * from <table name> where <condition>(select * from ......(select *
from .......));
- in the above statement we have two queries,
i) inner query
ii) outer query
- as per the execution process of a subquery statement it again classified
into
two ways,
1) non co-related subquery
First : inner query executed
Later : outer query execute

2) co-related subquery
First : outer query executed
Later : inner query execute

NOTE:
=====
- both are providing same result.

1) non co-related subquery:


========================
> Single row subquery
> Multiple row subquery
> Multiple column subquery
> inline view

Single row subquery:


=================
- when a subquery return a single value is called as "single row subquery".
- in this subquery we will use the following operators are " = , < , > , <= ,
>= ,!=".

Ex:
waq to display employee details who are earning the first highest salary?
SELECT * FROM EMP WHERE SAL=(SELECT MAX(SAL) FROM EMP);

Ex:
waq to display the senior most employee details from emp table?
SQL> SELECT * FROM EMP WHERE HIREDATE=(SELECT MIN(HIREDATE) FROM EMP);

Ex:
waq to display employees details whose job is same as the employee "martin" job?
SQL> SELECT * FROM EMP WHERE JOB=(SELECT JOB FROM EMP WHERE ENAME='MARTIN');

Ex:
waq to display employees details whose salary is more than the maximum salary of
"salesman" job?
SQL> SELECT * FROM EMP WHERE SAL>(SELECT MAX(SAL) FROM EMP WHERE JOB='SALESMAN');

Ex:
waq to display employee details who are earning the second highest salary?
SQL> SELECT * FROM EMP WHERE SAL=(SELECT MAX(SAL) FROM EMP
2 WHERE SAL<(SELECT MAX(SAL) FROM EMP));

Ex:
waq to display employee details who are earning 3rd highest salary?
SQL> SELECT * FROM EMP WHERE SAL=(SELECT MAX(SAL) FROM EMP
2 WHERE SAL<(SELECT MAX(SAL) FROM EMP WHERE SAL<(SELECT MAX(SAL) FROM EMP)));

Nth N+1
==== ====
1ST 2Q
2ND 3Q
3RD 4Q

30TH 31Q

150TH 151Q

How to overcome the above problem?


=================================

Multiple row subquery:


====================
- when a subquery returns more than one value.
- in this subquery we will use the following operators are "IN,ANY,ALL".

Ex:
waq to display employees whose employee job is same as the employee
"SMITH" ,"ALLEN" jobs ?
SQL> SELECT * FROM EMP WHERE JOB IN(SELECT JOB FROM EMP WHERE ENAME='SMITH' OR
ENAME='ALLEN');
(OR)
SQL> SELECT * FROM EMP WHERE JOB IN(SELECT JOB FROM EMP WHERE ENAME
IN('SMITH','ALLEN'));

Ex:
waq to display employees who are getting maximum and minimum salaries?
SQL> SELECT * FROM EMP WHERE SAL IN(SELECT MAX(SAL) FROM EMP UNION SELECT MIN(SAL)
FROM EMP);

Ex:
waq to display the senior most employee details from each deptno wise?
SQL> SELECT * FROM EMP WHERE HIREDATE IN(SELECT MIN(HIREDATE) FROM EMP GROUP BY
DEPTNO);

ANY :
=====
- it returns a value if any one value is satisfying from the given group of
values in the query.

Ex:
a(25) > any(10,20,30)

i) a=40 =====> true


ii) a=09=====> false
iii) a=25=====> true

ALL :
=====
- it returns a value if all values are satisfying from the given group of
values in the query.

Ex:
a(25) > all(10,20,30)

i) a=40 =====> true


ii) a=09=====> false
iii) a=25=====> FALSE

Ex:
waq to display employees whose salary is more than any "salesman" salary?
SQL> SELECT * FROM EMP WHERE SAL>ANY(SELECT SAL FROM EMP WHERE JOB='SALESMAN');

Ex:
waq to display employees whose salary is more than all "salesman" salary?
SQL> SELECT * FROM EMP WHERE SAL >ALL(SELECT SAL FROM EMP WHERE JOB='SALESMAN');

Multiple column subquery:


======================
- when we are comparing multiple columns values of inner query with
multiple columns values of outer join is called as "multiple column subquery".

syntax:
=======
select * from <tn> where(column name1,column nam2,....) in(select * from
<tn> .............);

Ex:
waq to display employees whose job,mgr are same as the job,mgr of the employee
"scott"?
SQL> SELECT * FROM EMP WHERE(JOB,MGR) IN(SELECT JOB,MGR FROM EMP WHERE
ENAME='SCOTT');

PSEUDO COLUMNS:
================
- pseudo columns are just like a table columns.
i) ROWID
ii) ROWNUM

i) ROWID:
=======
- When we insert a new row into a table internally system will generate a
unique identification address
for each row wise automatically.

EX:
SQL> SELECT ROWID,ENAME FROM EMP;

HOW TO DELETE MULTIPLE DUPLICATE ROWS EXCEPT ONE DUPLICATE ROW IN A TABLE:
=========================================================================
EX:
SQL> SELECT * FROM TEST;

SNO NAME
---------- ----------
1 A
1 A
1 A
2 B
3 C
3 C
3 C
3 C
4 D
4 D

SOLUTION:
==========
SQL> DELETE FROM TEST WHERE ROWID NOT IN(SELECT MAX(ROWID) FROM TEST GROUP BY
SNO,NAME);

OUTPUT:
=======
SQL> SELECT * FROM TEST;

SNO NAME
---------- ----------
1 A
2 B
3 C
4 D

ii) ROWNUM:
==========
- It is used to generate the sequence numbers to each row wise automatically.

Ex:
SQL> SELECT ROWNUM,ENAME FROM EMP;
SQL> SELECT ROWNUM,ENAME,DEPTNO FROM EMP WHERE DEPTNO=30;

Inline view:
==========
- Providing a select query in place of table name in select statement is
called as "Inline view".
(or)
- Providing a select query under FROM clause.

syntax:
======
SELECT * FROM (<SELECT QUERY>);

NOTE:
=====
- In Inline view subquery,the result of inner query will act as a table for
the outer query.

EX:
waq to display all employees annual salaries?
SQL> SELECT EMPNO,ENAME,SAL,SAL*12 AS ANNUAL_SALARY FROM EMP;
Ex:
waq to display employees whose annual salary is more than 25000?
SQL> SELECT EMPNO,ENAME,SAL,SAL*12 AS ANNUAL_SALARY FROM EMP WHERE
ANNUAL_SALARY>25000

ERROR at line 1:
ORA-00904: "ANNUAL_SALARY": invalid identifier

- in the above example we used a column alias name under "where" clause
condition but it is not allowed and raise an error is
"Invalid identifier".
- to overcome the above problem we should use "inline view" mechanism.

SOLUTION:
=========
SQL> SELECT * FROM(SELECT EMPNO,ENAME,SAL,SAL*12 AS ANNUAL_SALARY FROM EMP) WHERE
ANNUAL_SALARY>25000;

CO-RELATED SUQUERY:
=====================
How to find out "Nth" high / low salary:
=================================
SELECT * FROM <TN> <TABLE ALIAS NAME1> WHERE N-1=(SELECT * FROM <TN>
<TABLE ALIAS NAME2> WHERE <TABLE ALIAS NAME2>.<COLUMN NAME> < / >
<TABLE ALIAS NAME1>.<COLUMN NAME>);

Here,
< - LOW SALARY
> - HIGH SALARY

EX:
waq to find out the 1st highest salary employee details by uisng co-related
subquery?

SOLUTION:
==========
- IF N=1
- N-1 ===> 1-1 ====> 0

DEMO_TABLE:
============
SQL> SELECT * FROM TEST;

EID ENAME SAL


---------- ---------- ----------
1 SMITH 85000
2 WARD 34000
3 ALLEN 72000
4 MILLER 85000
5 ADAMS 25000

SQL> SELECT * FROM TEST T1 WHERE 0=(SELECT COUNT(DISTINCT SAL)


FROM TEST T2 WHERE T2.SAL>T1.SAL);

EX:
waq to find out 4th highest salary employee details by using co-related subquery?
solution:
=======
IF N=4
= N-1 ===> 4-1 ====> 3

SQL> SELECT * FROM TEST T1 WHERE 3=(SELECT COUNT(DISTINCT SAL)


FROM TEST T2 WHERE T2.SAL>T1.SAL);

How to find out "Top n" high / low salaries:


=================================
SELECT * FROM <TN> <TABLE ALIAS NAME1> WHERE N>(SELECT * FROM <TN>
<TABLE ALIAS NAME2> WHERE <TABLE ALIAS NAME2>.<COLUMN NAME> < / >
<TABLE ALIAS NAME1>.<COLUMN NAME>);

Here,
< - LOW SALARY
> - HIGH SALARY

EX:
waq to display top 3 highest salaries employees details by using co-related
subquery?

solution:
=======
IF N=3 ======> N> ====> 3>

SQL> SELECT * FROM TEST T1 WHERE 3>(SELECT


2 COUNT(DISTINCT SAL) FROM TEST T2
3 WHERE T2.SAL > T1.SAL);

EXISTS OPERATOR:
================
- It special operator which is used in "co-related subquery" only.
- this operator is used to check the required row is exists in a table or
not.
- if a row is exists in a table then it return "true".
- if a row is not exists in a table then it return "false".

Ex:
waq to display department details in which department the employees are working?
SQL> SELECT * FROM DEPT D WHERE EXISTS(SELECT DEPTNO
2 FROM EMP E WHERE E.DEPTNO=D.DEPTNO);

Ex:
waq to display department details in which department the employees are not
working?
SQL> SELECT * FROM DEPT D WHERE NOT EXISTS(SELECT DEPTNO
2 FROM EMP E WHERE E.DEPTNO=D.DEPTNO);

SCALAR SUBQUERY:
==================
- providing a subquery inplace of column name in select statement is called
as
"scalar subquery".
(or)
- providing a subquery under select statement is called as "scalar subquery".

syntax:
=======
SELECT (SUBQUERY1),(SUBQUERY2),....... FROM <TABLE NAME>;

Ex:
SQL> SELECT(SELECT COUNT(*) FROM EMP),(SELECT COUNT(*) FROM DEPT) FROM DUAL;

(SELECTCOUNT(*)FROMEMP) (SELECTCOUNT(*)FROMDEPT)
---------------------------------------------
-----------------------------------------------
14 4

Ex:
SQL> SELECT (SELECT SUM(SAL) FROM EMP WHERE DEPTNO=10) AS "10",
2 (SELECT SUM(SAL) FROM EMP WHERE DEPTNO=20) AS "20",
3 (SELECT SUM(SAL) FROM EMP WHERE DEPTNO=30) AS "30"
4 FROM DUAL;

10 20 30
---------- ---------- ----------
8750 10875 9400
==============================================================================
INDEXES:
========
- it is db object which is used to retrieve the required row / rows from a
table
fastly.
- by using indexes we can reduce the searching time and improve the
performance
of database.
- all databases are supporting the following two types of searching
mechanisms,
1. table scan
2. index scan

1. table scan :
============
- it is a default scan of database.in this scan oracle server is scanning the
entire
table for the required data purpose.

Ex:
SQL> SELECT * FROM EMP WHERE SAL=3000;
- In this table scan,oracle server is searching complete table i.e 14 rows
for
the above required data.(for example 1 row = 1 sec ===> 14 secs time taken by
oracle)

2. index scan:
============
- when we create an index object on a particular column / columns in a table
those column / columns are called as "indexed key column" and based on an indexed
key column
only our oracle server is searching for required data purpose.

types of indexes:
===============
1. B-tree indexes
2. Bitmap indexes
1. B-tree indexes:
================
> simple index
> composite index
> unique index
> functional based index

simple index:
===========
- when we created an index object based on a single column is called as
"simple index".

syntax:
=======
create index <index name> on <tn>(column name);

Ex:
SQL> CREATE INDEX I1 ON EMP(SAL);

NOTE:
=====
- to view column name along with index name of a particular table then we
follow the following syntax is,
SQL> SELECT COLUMN_NAME,INDEX_NAME FROM USER_IND_COLUMNS
WHERE TABLE_NAME='EMP';

COLUMN_NAME INDEX_NAME
------------------------------------------------- -----------------------------
--------------------------------------------------
SAL I1

You might also like