Day 2
Day 2
Learning Objectives
After completing this module, the participant will be able to
do the following:
Page 2
HexaVarsity
Using a Sub query to Solve a Problem
Who has Salary greater than Lanson’s
salary?
Main Query
Sub Query
Page 3
HexaVarsity
Sub query
• The subquery (inner query) executes once before the main
query.
• The result of the subquery is used by the main query (outer
query).
Syntax:
SELECT select_list
FROM table
WHERE expr operator (SELECT select_list FROM table);
Example:
SELECT last_name
FROM employees
WHERE salary >(SELECT salaryFROM employees WHERE
last_name = ‘Abel’) ;
Page 4
HexaVarsity
Guidelines
Page 5
HexaVarsity
Types of Sub queries
Single-row subqueries:
Queries that return only one row from the inner
SELECT statement
Main query
Page 7
HexaVarsity
Single Row Sub query
Example 1:
Example 2:
Example:
Page 9
HexaVarsity
The HAVING Clause with Subqueries
Example:
Page 10
HexaVarsity
Multiple-Row Subqueries
Page 11
HexaVarsity
Multiple-Row Subqueries-IN Operator
Example:
SELECT last_name, salary, department_id
FROM employees
WHERE salary IN (2500, 4200, 4400, 6000, 7000, 8300, 8600, 17000);
(SELECT MIN(salary)
FROM employees
GROUP BY department_id);
Page 12
HexaVarsity
Multiple-Row Subqueries-ANY Operator
Example:
SELECT employee_id,
last_name,job_id, salary
FROM employees
WHERE salary < ANY
(SELECT salary (9000,6000,4200)
FROM employees
WHERE job_id = ’IT_PROG’)
AND job_id <> ’IT_PROG’;
Page 13
HexaVarsity
Multiple-Row Subqueries-ALL Operator
Example:
SELECT employee_id, last_name,
job_id, salary
FROM employees
WHERE salary <ALL(SELECT salary (9000,6000,4200)
FROM employees
WHERE job_id = ’IT_PROG’)
AND job_id <> ’IT_PROG’;
Page 14
HexaVarsity
Set Operators
Objectives
Page 16
HexaVarsity
Set Operators
UNION UNION ALL
INTERSECT MINUS
Page 17
HexaVarsity
Union Operator
The UNION operator returns results from both queries after
eliminating duplications.
Example:
SELECT employee_id, job_id
FROM employees
UNION
SELECT employee_id, job_id
FROM job_history;
Page 18
HexaVarsity
Union Operator
The UNION operator returns results from both queries after
eliminating duplications.
Page 19
HexaVarsity
UNION ALL operator
The UNION ALL operator returns results from
both queries, including all duplications.
Example:
Page 20
HexaVarsity
The INTERSECT Operator
Use the INTERSECT operator to return all rows common to
multiple queries.
Example:
Page 21
HexaVarsity
The MINUS Operator
Use the MINUS operator to return rows returned by the first
query that are not present in the second query (the first
SELECT statement MINUS the second SELECT statement)
Example:
SELECT employee_id,job_id
FROM employees
MINUS
SELECT employee_id,job_id
FROM job_history;
Page 22
HexaVarsity
The Oracle Server and SET Operators
Page 23
HexaVarsity
Matching the SELECT Statements
Example 1:
Example 2: