Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

MRS Subqueries

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 40

Subqueries

SQL SUBQUERIES:

 Queries within Queries

 When data to be filtered is known, we put the filter condition


with Where clause.

 What to do when we don’t know what the filter value is OR


we don’t want to hardcode a value into the query ?

 If the filter can be found elsewhere in the database then we


can put a subquery in the Where clause.
SUBQUERY – GENERAL RULES
 A subquery SELECT statement is very similar to the
SELECT statement used to begin a regular or outer
query.  The complete syntax of a subquery is shown
below.
create table employee ( empname varchar(20), empid int primary key,
empsal int, empdesig varchar(20)); 
insert into employee values("Kamal",629,92000,"Assistant Professor"); 
insert into employee values("Prathamesh",630,95000,"Assistant Professor"); 
insert into employee values("Abhishek",631,95000,"Assosciate Professor"); 
insert into employee values("RC",632,115000,"Assosciate Professor"); select
empdesig,max(empsal) from employee group by(empdesig); 
select empname,empsal,empdesig from employee where (empdesig,empsal)
in (select empdesig,max(empsal) from employee group by(empdesig));
RULES CONT’D
 The SELECT clause of a subquery must contain only
one expression, only one aggregate function, or only one
column name.
 The value(s) returned by a subquery must be compatible
with the WHERE clause of the outer query.
EXAMPLE
SELECT emp_last_name "Last Name",
emp_first_name "First Name",
emp_salary "Salary"
FROM employee
WHERE emp_salary =
(SELECT MIN(emp_salary)
FROM employee);
Last Name First Name Salary
--------------- --------------- --------
Markis Marcia $25,000
Amin Hyder $25,000
Prescott Sherri $25,000
EXAMPLE
SELECT emp_last_name "Last Name",
emp_first_name "First Name"
FROM employee
WHERE emp_ssn IN
(SELECT dep_emp_ssn
FROM dependent);
Last Name First Name
------------- ---------------
Bock Douglas
Zhu Waiman
Joyner Suzanne
SUBQUERIES AND THE IN OPERATOR
 Conceptually, this statement is evaluated in two
steps.
 First, the inner query returns the identification
numbers of those employees that have male
dependents.
SELECT dep_emp_ssn
FROM dependent
WHERE dep_gender = 'M';
DEP_EMP_S
---------
999444444
999555555
999111111
SUBQUERIES AND THE IN OPERATOR
 Next, these social security number values are
substituted into the outer query as the listing that
is the object of the IN operator. So, from a
conceptual perspective, the outer query now
looks like the following.
SELECT emp_last_name "Last Name",
emp_first_name "First Name"
FROM employee
WHERE emp_ssn IN (999444444, 999555555, 999111111);
Last Name First Name
--------------- ---------------
Joyner Suzanne
Zhu Waiman
Bock Douglas
THE NOT IN OPERATOR
 Like the IN operator, the NOT IN operator can take the
result of a subquery as the operator object.

SELECT emp_last_name "Last Name", emp_first_name "First Name"


FROM employee
WHERE emp_ssn NOT IN
(SELECT dep_emp_ssn
FROM dependent);
Last Name First Name
--------------- ---------------
Bordoloi Bijoy
Markis Marcia
Amin Hyder
more rows are displayed . . .
THE NOT IN OPERATOR
 The subquery shown above produces an
intermediate result table containing the social
security numbers of employees who have
dependents in the dependent table.
 Conceptually, the outer query compares each row
of the employee table against the result table. If
the employee social security number is NOT
found in the result table produced by the inner
query, then it is included in the final result table.
MULTIPLE LEVELS OF NESTING
 Subqueries may themselves contain subqueries.
 When the WHERE clause of a subquery has as its
object another subquery, these are termed nested
subqueries.
 Consider the problem of producing a listing of
employees that worked more than 10 hours on the
project named Order Entry.
EXAMPLE

SELECT emp_last_name "Last Name",


emp_first_name "First Name"
FROM employee
WHERE emp_ssn IN
(SELECT work_emp_ssn
FROM assignment
WHERE work_hours > 10 AND work_pro_number IN
(SELECT pro_number
FROM project
WHERE pro_name = 'Order Entry') );
Last Name First Name
--------------- ---------------
Bock Douglas
Prescott Sherri
UNDERSTANDING SUBQUERIES
 Inorder to understand how this query executes, we
begin our examination with the lowest subquery.
 We will execute it independently of the outer
queries.
SELECT pro_number
FROM project
WHERE pro_name = 'Order Entry';
PRO_NUMBER
----------
1
UNDERSTANDING SUBQUERIES
 Now, let's substitute the project number into the IN
operator list for the intermediate subquery and
execute it.
 The intermediate result table lists two employee
social security numbers for employees that worked
more than 10 hours on project #1.
SELECT work_emp_ssn
FROM assignment
WHERE work_hours > 10 AND work_pro_number IN (1);
WORK_EMP_SSN
-----------------------
999111111
999888888
UNDERSTANDING SUBQUERIES
 Finally,we will substitute these two social security
numbers into the IN operator listing for the outer
query in place of the subquery.
SELECT emp_last_name "Last Name",
emp_first_name "First Name"
FROM employee
WHERE emp_ssn IN (999111111, 999888888);
Last Name First Name
--------------- ---------------
Bock Douglas
Prescott Sherri
AGGREGATE FUNCTIONS AND COMPARISON
OPERATORS

 The aggregate functions (AVG, SUM, MAX, MIN,


and COUNT) always return a scalar result table.
 Thus, a subquery with an aggregate function as the
object of a comparison operator will always
execute provided you have formulated the query
properly.
AGGREGATE FUNCTIONS AND COMPARISON
OPERATORS

SELECT emp_last_name "Last Name",


emp_first_name "First Name",
emp_salary "Salary"
FROM employee
WHERE emp_salary >
(SELECT AVG(emp_salary)
FROM employee);

Last Name First Name Salary


--------------- --------------- ----------
Bordoloi Bijoy $55,000
Joyner Suzanne $43,000
Zhu Waiman $43,000
Joshi Dinesh $38,000
COMPARISON OPERATORS MODIFIED WITH THE ALL
OR ANY KEYWORDS

 The ALL and ANY keywords can modify a comparison operator


to allow an outer query to accept multiple values from a
subquery.
 The general form of the WHERE clause for this type of query is
shown here.
WHERE <expression> <comparison_operator> [ALL |
ANY] (subquery)
 Subqueries that use these keywords may also include GROUP
BY and HAVING clauses.
THE ALL KEYWORD
 The ALL keyword modifies the greater than comparison
operator to mean greater than all values.

SELECT emp_last_name "Last Name",


emp_first_name "First Name",
emp_salary "Salary"
FROM employee
WHERE emp_salary > ALL
(SELECT emp_salary
FROM employee
WHERE emp_dpt_number = 7);
Last Name First Name Salary
--------------- --------------- --------
Bordoloi Bijoy $55,000
THE ANY KEYWORD
 The ANY keyword is not as restrictive as the ALL keyword.
 When used with the greater than comparison operator, "> ANY"
means greater than some value.
EXAMPLE
SELECT emp_last_name "Last Name",
emp_first_name "First Name",
emp_salary "Salary"
FROM employee
WHERE emp_salary > ANY
(SELECT emp_salary
FROM employee
WHERE emp_salary > 30000);

Last Name First Name Salary


--------------- --------------- --------
Bordoloi Bijoy $55,000
Joyner Suzanne $43,000
Zhu Waiman $43,000
EXAMPLE(S):

Enlist the names of students who have secured marks


more than the average of all students in maths.
Q: select names from student where maths> (select avg(maths) from
student);

  Find the employees who have the same position as ‘Ritesh’


Q:select * from emp  where position = ( select position from emp
where ename = ‘Ritesh’);
TYPES OF SUBQUERIES:

 Single Row:
Sub query which returns single row output. Single row comparison
operators i.e. >,= are used with WHERE conditions.

 Multiple Row:
The subquery returns more than one row. Multiple row comparison
operators like IN, ANY, ALL are used in the comparisons.
SINGLE ROW SUBQUERY EXAMPLES:

 Display the details of employees to whom the company


is paying minimum salary.

SELECT first_name, salary, department_id FROM employees


WHERE salary = (SELECT MIN (salary) FROM employees);

 Enlist the names of students who are older than the


average student.
SELECT stuname FROM student WHERE age > (SELECT
AVG(age) FROM student);
MULTIPLE ROWS SUBQUERY EXAMPLES:

  Find the employees whose salary is equal to the salary


of at least one employee in department of id 5?

SELECT employee_id, salary FROM employees WHERE salary


IN ( SELECT salary FROM employees WHERE department_id = 5
)

 Enlist the any employee who belongs to the department


located at ‘Mumbai’.
SELECT employee_id, emp_name FROM employees WHERE
dept_no =ANY ( SELECT dept_no FROM department WHERE
dept_location = ‘Mumbai’ )
EXECUTION ORDER OF SUBQUERIES:

The basic concept is to pass a single value or many


values from the innermost subquery to the next (one
level up) query and so on.

4
3
2
1

When reading or writing SQL subqueries, you should start


from the bottom upwards, working out which data is to be
passed to the next query up.
UNIVERSITY DATABASE:

1. Student names are held in the STUDENT table


2. Student marks are recorded in the MARKS table but
marks are allocated against the STUDENTID

Question:
List the names of the students who have failed in the
subject ‘COMP1011’.
SINGLE QUERIES:
To identify the students who have failed in subject COMP1011

Select stu_id
From marks
Where sub_id = ‘COMP1011’
And grade < 40;

To retrieve a name based on a student id

Select stu_name
From student
Where stu_id = 9292145;
NESTED QUERY (SUBQUERY):

Select stu_name
From Student
Where stu_id in ( select stu_id
From marks
Where sub_id =
‘COMP1011’
And grade < 40);

Retrieve a list of Retrieve the


student id’s who name of the
have mark < 40 studentid’s in
for COMP1011 this list.
RULES FOR SUBQUERIES:

1.The data types must match. i.e.if the stu_id expects a


number then the subquery must return a number.

2.Remember = means that it is expecting a single value, you


must therefore be sure that the subquery returns only 1
result, if there is any doubt you should use the IN keyword.

3.You can nest / use as many subqueries as you like.

4.This is not a very efficient way of coding or pulling data


from multiple tables, and you may be able to generate the
required result using joins (covered later in the syllabus)
COMPARATORS:

= equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to
<> not equal to

and other keywords ……

IN
NOT IN
ANY
ALL
MULTIPLE ROW SUBQUERIES:

Consider the following tables:


Agents( agent_code,
agent_name,work_area,phone,commission,country)

Orders(ord_no,ord_amt,advance_amt,ord_date,cust_code,agen
t_code,ord_description)

 IN: IN operator is used to check a value within a set of


values. The list of values may come from the results returned by
a subquery.
Example: SELECT ord_no,ord_amt,ord_date,
cust_code, agent_code FROM orders WHERE agent_code
IN(SELECT agent_code FROM agents WHERE
working_area='Bangalore');
MULTIPLE ROW SUBQUERIES:
 NOT IN: Opposite of IN operator

SELECT ord_num,ord_amount,ord_date, cust_code, agent_code


FROM orders WHERE agent_code NOT IN( SELECT agent_code FROM agents
WHERE working_area='Bangalore');

 ANY: You can use the ANY operator to compare a value with any
value in a list. You must place an =, <>, >, <, <= or >= operator
before ANY in your query.
Q: Enlist if any of the agent who belongs to the country 'UK'

SELECT agent_code,agent_name,working_area,commission
FROM agents WHERE agent_code = ANY( SELECT agent_code
FROM customer WHERE cust_country='UK');
MULTIPLE ROW SUBQUERIES:
 ALL:Compares a value to every value in a list or returned by a
query. Must be preceded by =, !=, >, <, <=, >=. Evaluates to TRUE
if the query returns no rows.

Q: Select employees whose salary is greater than every salesman’s


salary:

select ename from emp where sal > all ( select sal
from emp where job = 'SALESMAN');
GROUP BY AND HAVING CLAUSE:
 GROUP BY:Groups rows based on distinct values which exists for
specified column.

Q: Retrieve the product numbers and total quantity ordered for each
product from the sales_order_details table.

Sales_order_details(p_no,qty,qty_dis,description)

A: select p_no,sum(qty) “Total Qty Ordered” from


sales_order_details GROUP BY p_no;
GROUP BY AND HAVING CLAUSE:
 HAVING:Used in conjunction with GROUP BY clause. It imposes
a condition on GROUP BY clause which further filters the groups
created by the GROUP BY clause.

Q: Retrieve the product numbers and total quantity ordered for


products ‘P001’, ‘P005’ from the sales_order_details. table.

A: select p_no,sum(qty) “Total Qty Ordered” from


sales_order_details GROUP BY p_no
HAVING p_no=‘P001’ OR p_no=‘P005’;
MULTIPLE COLUMN SUBQUERIES:
 You can write subqueries that return multiple columns. The
following example retrieves the order amount with lowest price,
group by agent.

select ord_num, agent_code, ord_date, ord_amount  
from orders  where(agent_code, ord_amount) IN  
(SELECT agent_code, MIN(ord_amount)  
FROM orders GROUP BY agent_code);  
VIEWS IN SQL
• A view is a virtual table contains rows and columns, just like a
real table. The fields in a view are fields from one or more real
tables in the database.
Syntax:
CREATE VIEW view_name AS SELECT column_name(s) FROM
table_name WHERE condition
For Example:
Create View product_vw AS select description from product
where city = ‘Mumbai’ Order by city

Create View product_vw AS select description, QTY from


product where city = ‘Mumbai’ Group BY description;
RETRIEVING RECORDS FROM VIEW
Syntax:
Select column(s) from VIEW;
For Example:
Select description from product_vw;

To Delete VIEW:
Drop View <View Name>

NOTE– Update and Delete commands in view work same as work


on table only difference is that use view name rather than table
name
EXAMPLE
 find the employee id, first_name, last_name, and salaries
for employees whose salary is greater than the average
salary throughout the company.

You might also like