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

SQL part III.docx

Sql notes

Uploaded by

royisha1509
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)
13 views

SQL part III.docx

Sql notes

Uploaded by

royisha1509
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/ 4

Structured Query Language

Sub queries
Nested sub queries
A sub query is a select statement that is nested within another select statement and which
returns intermediate results.
Select column 1, column 2, …….. from table where column = (Select column from table
where condition);
The sub query is often referred to as inner select or sub select; it generally executes first and
its output is used to complete the query condition for the main or outer query. The nested sub
query is important when we feel to select rows from a table with a condition that depends on
the data in the table itself.
Single Row sub queries
Find the employee who earns the minimum salary in the company:
Step 1: find the minimum salary: select min(sal) from emp;
Step 2: find the employee who earns the minimum salary: select ename, job, sal from emp
where sal = (result of step 1);
[The inner select is processed first producing a result. The main query block is processed then
and uses the value returned by the inner query to complete its search condition.]
Find all employees who have the same job as BLAKE:
Select ename, job from emp where job = (Select job from emp where ename = ‘BLAKE’);

Sub queries that return multiple rows:


Find all employees who earn the lowest salary in each department:
Select ename, sal, deptno from emp where sal in (select min(sal) from emp group by deptno);
[The inner query has a group by clause and so it returns more than one value. So, we use a
multi-row comparison operator. In this case the IN operator is used because it expects a list of
values.]

Comparing more than one value:


Find those employees who earn the lowest salary in their department:
Select ename, sal, deptno from emp where (sal, deptno) in (select min(sal), deptno from emp
group by deptno);
[When a sub query returns more than one row, the single row comparison operator cannot be
used].

1 | Page Dr.Anirban Goswami


Structured Query Language

Some / Any or All operator:


The Any or All operator may be used for sub queries that return more than one row. They are
used on the where or having clause in conjunction with the relational operators (=, !=, < , >,
>=,<=).
ANY (Some): It is used to compare a value to each value returned by a sub query. (IF a
condition is satisfied at some point of time then the rest will not be checked).
Example: To display employees who earn more than the lowest salary in Department 30:
Select ename, sal, job, deptno from emp where sal > some(select min(sal) from emp where
deptno =30);
ALL: It compares a value to every value returned by a sub query. [It checks every value
whether or not matching has occurred].
Example: Find employees who earn more than every employee in department 30:
Select ename, sal, job, deptno from emp where sal > all (select distinct(sal) from emp where
deptno =30) order by sal desc;
[The NOT operator can be used with IN, ANY or ALL operator].
Having clause with nested sub query:
Nested sub queries can also be used in the having clause. [Where clause refers to single rows
and having refers to group of rows in the group by clause].
Example: To display the department which have an average salary bill greater than dept. 30:
Select deptno, avg(sal), from emp having avg(sal) > (select avg(sal) from emp where deptno
= 30) group by deptno;
Example: To display the job with the highest average salary:
Select job, avg(sal) from emp group by job having avg(sal) = (Select max(avg(sal)) from emp
group by job);
[The group by clause in the main query is needed because the main query’s select list
contains both an aggregate and non-aggregate column].
Ordering data with sub queries
We may not have an order by clause in a sub query.
We can have only one order by clause for a select statement and if specified it must be the last
clause in the select statement.
Nested sub queries
Sub queries can be nested within another sub query.
Example: Display name, job, hiredate from employee whose salary is greater than the highest
salary in any SALES dept.

2 | Page Dr.Anirban Goswami


Structured Query Language

Select ename, job, hiredate, sal from emp where sal > (Select max(sal) from emp where
deptno = (select deptno from dept where dname=’SALES’));
N.B The limit on the level of nesting is upto 255.
Properties of Sub Query:
1) The inner query must be enclosed in parenthesis and must be on the right hand side of
the condition.
2) The sub query may not have an order by clause.
3) The order by clause appears at the end of the main select statement.
4) Multiple columns on the select list of the inner query must be in the same order as the
columns appearing on the condition clause of the main query.
5) Sub queries are always executed from the most deeply nested to the least deeply
nested, unless they are correlated sub queries.
6) Logical and SQL operators may be used as well as ANY and ALL.
7) Returns one or more rows.
8) Returns one or more columns.
9) Use group by or group functions.
10) Join tables.
11) Retrieve from a different table other than the outer query.
12) Correlate with an outer query.
13) Use set operators.

Correlated Sub queries


A correlated sub query is a nested sub query which is executed once for each candidate row
considered by the main query and which on execution uses a value from a column in the
outer query. This causes the correlated sub query to act differently from a normal sub query.
A correlated sub query is identified by the use of an outer query’s column in the inner query’s
predicate clause.
With a normal sub query the inner query is executed first and only once and returns values to
be used by the main query. But in a correlated sub query, the inner query executes once for
each row (candidate row) considered by the outer query. The inner query is driven by the
outer query.
Steps to execute a correlated sub query:
1) Get candidate row as fetched by the outer query.
2) Execute inner query using candidate row’s value.
3) Use value(s) resulting from inner query to qualify or disqualify candidate.
4) Repeat until no candidate row remains.
Example: display employees who earn a salary greater than the average salary for their dept.
Select empno, ename, sal, deptno from emp e where sal > (select avg(sal) from emp where
deptno = e.deptno);

3 | Page Dr.Anirban Goswami


Structured Query Language

[This is a correlated sub query because a column from the outer select is used in the where
clause of the inner select].
Operators in Correlated sub queries:
The Exist operator is frequently used with correlated sub query. It tests whether a value is
there or not. If the value exists it returns TRUE and FALSE otherwise.
Example:
Find employees who have at least one person reporting to them:
Select empno, enname, job, deptno from emp e where exists(select empno from emp where
emp.mgrno = e.empno) order by empno;
Find all employees whose department is not in the Dept table:
Select empno, ename, deptno from emp where not exists (select deptno from dept where
dept.deptno = emp.deptno);
Find the department which doesnot have any employee:
Select deptno, dname from dept d where not exists (select 1 from emp e from e.deptno =
d.deptno);

Not EXISTS vs NOT IN


NOT IN operator is as efficient as NOT Exists operator in a sub query. NOT exists is more
reliable if the sub query returns any NULL values, since a NOT IN condition evaluates to
false when NULL’s are included in the compared list.
Example:
Select ename, job from emp where empno not in (select mgr from emp);
Select ename, job from emp e where not exists (select mgr from emp mgr = e.empno);
Exercise:
1) Display ename, job, sal of employees who earn the highest salary in each job type.
Sort in descending salary order.
2) Display ename, job, sal of employees who earn the minimum salary for their job. Sort
in ascending salary order.
3) Display deptno, ename, hiredate of the most recently hired employees in each
department. Order by Hiredate.
4) Show the ename, salaray, deptno of the employees who earn a salary greater than the
average for their department. Sort in department number order.
5) List all the deptno, dname of all the departments where there are no employees.
6) Who are the top three earners of the company? Display their ename and sal.
7) In which year did most people join their company?
*************************

4 | Page Dr.Anirban Goswami

You might also like