Best Subquery
Best Subquery
Subquery
By Vinod Sencha
What is SQL Sub query?
• department table
Employee table
• Suppose you want to find out the ename, job,sal of the
employees whose salaries are less than that of an employee
whose empno= 7876 from EMP table. Now you need to
perform two queries in order to get the desired result.
1. We will find out the salary of the employee whose
empno=7876. the query is as under:
SYMBOL MEANING
IN Equal to any member in a list.
ANY Return rows that match any value on a list.
ALL Return rows that match all the values in a list.
IN Operator
• The IN operator retirns true if the comparison value is
contained in the list.
• The following statement finds the employee whose
salary is the same as the minimum salary of the
employees in the department.
ANY Operator
• The ANY operator return true if the comparison
value matches any of the values in the list.
• Display the employees whose salary is more than the
minimum salary of the employees in any department.
ALL Operator
• Returns true only if the comparison value matches all the
values in the list.
• Display the employee detail with salary less than those whose
job is ‘MANAGER’.
MULTIPLE COLUMN SUBQUERY
• A subquery that compares more than one column
between the parent query and subquery is called the
multiple column subqueries.
• List the employees that makes the same salary as other
employee with empno=7521 with the same job also.
Nested Subqueries
SQL provides a mechanism for the nesting of subqueries.
A subquery is a select-from-where expression that is nested within another
query.
The nesting can be done in the following SQL query
as follows:
Ai can be replaced be a subquery that generates a single value.
ri can be replaced by any valid subquery
P can be replaced with an expression of the form:
B <operation> (subquery)
Where B is an attribute and <operation> to be defined later.
Subqueries in the From Clause
SQL allows a subquery expression to be used in the from clause
Find the average instructors’ salaries of those departments where the average salary
is greater than $42,000.”
select dept_name, avg_salary
from (select dept_name, avg (salary) as avg_salary
from instructor
group by dept_name)
where avg_salary > 42000;
Note that we do not need to use the having clause
Another way to write above query
select dept_name, avg_salary
from (select dept_name, avg (salary)
from instructor
group by dept_name) as dept_avg (dept_name, avg_salary)
where avg_salary > 42000;
Scalar Subquery
Scalar subquery is one which is used where a single value
is expected
List all departments along with the number of instructors
in each department
select dept_name, (select count(*) from
instructor
where department.dept_name =
instructor.dept_name)
as num_instructors
from department;
Runtime error if subquery returns more than one result
tuple
Thank you