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

SQL2

The document discusses using group functions and joins in Oracle SQL. It covers how to use aggregate functions like COUNT, AVG, SUM to operate on sets of rows and output one result per group. It also discusses how to group rows using the GROUP BY clause and restrict groups using the HAVING clause. Additionally, it covers different types of joins like natural join, join using, and join on to retrieve data from multiple tables.

Uploaded by

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

SQL2

The document discusses using group functions and joins in Oracle SQL. It covers how to use aggregate functions like COUNT, AVG, SUM to operate on sets of rows and output one result per group. It also discusses how to group rows using the GROUP BY clause and restrict groups using the HAVING clause. Additionally, it covers different types of joins like natural join, join using, and join on to retrieve data from multiple tables.

Uploaded by

Surya T
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

DBMS Using

Oracle-Day-3
DBMS USING ORACLE

OBJECTIVES
DBMS using oracle
DBMS USING ORACLE > OBJECTIVES

At the end of this Lecture, you will be able to

Explain How to use Group functions in SQL


Explain how to retrieve data from multiple tables
Understand the use to sub-queries
Apply Set Operations of tables (self Study)
DBMS USING ORACLE

CONCEPT
Reporting Aggregated
Data Using the Group
Functions
DBMS USING ORACLE > REPORTING AGGREGATED DATA USING THE GROUP
FUNCTIONS

Topics covered:
Group functions:
Types and syntax
Use AVG, SUM, MIN, MAX, COUNT
Use the DISTINCT keyword within group functions
NULL values in a group function
Grouping rows:
GROUP BY clause
HAVING clause
Nesting group functions
DBMS USING ORACLE > GROUP FUNCTIONS

Group functions operate on sets of Rows and outputs one result per group

EMPLOYEE
S

Maximum salary in
EMPLOYEES table


DBMS USING ORACLE > GROUP FUNCTIONS

SELECT group_function([DISTNCT]column), ...


FROM table
[WHERE condition];

DISTINCT makes the function consider only non-duplicate values.


The data types for the functions with an expr argument may be CHAR,
VARCHAR2, NUMBER, or DATE.
All group functions ignore null values. To substitute a value for null values,
use the NVL, NVL2, COALESCE, CASE, or DECODE functions.
DBMS USING ORACLE > TYPES OF GROUP FUNCTIONS

AVG
COUNT
MAX
Group
MIN functions
STDDEV
SUM
VARIANCE
DBMS USING ORACLE > USING GROUP FUNCTIONS

The Below query displays the average, highest, lowest, and sum of monthly
salaries for all sales representatives.
SELECT AVG(salary), MAX(salary),
MIN(salary), SUM(salary)
FROM employees
WHERE job_id LIKE '%REP%';

Below query displays the most junior and most senior employees in the
organization
SELECT MIN(hire_date), MAX(hire_date)
FROM employees;
DBMS USING ORACLE > USING COUNT FUNCTION

COUNT(*) returns the number of rows in a table:


SELECT COUNT(*)
FROM employees
WHERE department_id = 50;

COUNT(expr) returns the number of rows with non-null values for expr:

SELECT COUNT(commission_pct)
FROM employees
WHERE department_id = 50;

COUNT(DISTINCT expr) returns the number of distinct non-null values of expr.


Below query displays the number of distinct department values in the
EMPLOYEES table:
SELECT COUNT(DISTINCT department_id)
FROM employees;
DBMS USING ORACLE > GROUP FUNCTIONS AND NULL VALUES

Group functions ignore null values in the column:

SELECT AVG(commission_pct)
FROM employees;

COUNT(expr) returns the number of rows with non-null values for expr:

SELECT AVG(NVL(commission_pct, 0))


FROM employees;
DBMS USING ORACLE > GROUPING ROWS

Group by clause divides the rows into groups and summary information
of each group can be obtained

EMPLOYEES

4400 Average salary in the


EMPLOYEES table for
9500
each department

3500

6400

10033


DBMS USING ORACLE > GROUPING ROWS – GROUP BY CLAUSE
FUNCTIONS

SELECT column, group_function(column)


FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[ORDER BY column];

Using a WHERE clause, you can restrict rows before dividing them into groups.
You cannot use a column alias in the GROUP BY clause.
DBMS USING ORACLE > USING GROUP FUNCTIONS

All the columns in the SELECT list that are not group functions must be in
the GROUP BY clause
SELECT department_id, AVG(salary)
FROM employees
GROUP BY department_id ;

The GROUP BY column does not have to be in the SELECT list


SELECT AVG(salary)
FROM employees
GROUP BY department_id ;
DBMS USING ORACLE > GROUPING MULTIPLE COLUMNS
Find the total salary that is paid to each job title in each department
EMPLOYEE Add the salaries in the EMPLOYEES
S table for each job, grouped by
department.

SELECT department_id, job_id, sum(salary)


FROM employees
GROUP BY department_id, job_id;
DBMS USING ORACLE > ILLEGAL GROUP FUNCTIONS

Any column or expression in the SELECT list that is not an aggregate function must be
in the GROUP BY clause
SELECT department_id, job_id,
SELECT department_id, COUNT(last_name) COUNT(last_name)
FROM employees; FROM employees
GROUP BY department_id;

A GROUP BY clause must be added Either add job_id in the GROUP BY or


to count the last names for each remove the job_id column from the
department_id. SELECT list.

You cannot use the WHERE clause to restrict groups and cannot use group functions
in the WHERE clause
SELECT department_id, AVG(salary)
Cannot use the
FROM employees
WHERE clause to
WHERE AVG(salary) > 8000
restrict groups
GROUP BY department_id;
DBMS USING ORACLE > RESTRICTING GROUP ROWS – HAVING CLAUSE
HAVING clause is used to restrict groups in the same way that you use
the WHERE clause to restrict the rows that you select
EMPLOYEE
S

SELECT department_id,
The maximum salary per
MAX(salary)
department if it is
FROM employees
greater than $10,000
GROUP BY department_id
HAVING MAX(salary)>10000 ;


DBMS USING ORACLE > RESTRICTING GROUP ROWS – HAVING CLAUSE

SELECT column, group_function


FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];

When you use the HAVING clause, the Oracle server restricts groups as
follows:
Rows are grouped.
The group function is applied.
Groups matching the HAVING clause are displayed.
DBMS USING ORACLE > NESTING GROUP FUNCTIONS

Group functions can be nested to a depth of two functions, Below query


calculates the maximum average salary of all employees in each department

SELECT MAX(AVG(salary))
FROM employees
GROUP BY department_id;
DBMS USING ORACLE > REPORTING AGGREGATED DATA USING THE GROUP
FUNCTIONS

GUIDED ACTIVITY
DBMS USING ORACLE > REPORTING AGGREGATED DATA USING THE GROUP FUNCTIONS
– GUIDED ACTIVITY

Calculate the average length of all the country names. Any fractional components
must be rounded to the nearest whole number.

Analysis of staff turnover is a common reporting requirement. You are required to


create a report containing the number of employees who left their jobs, grouped
by the year in which they left. The jobs they performed are also required. The
results must be sorted in descending order based on the number of employees in
each group. The report must list the year, the JOB_ID, and the number of
employees who left a particular job in that year.

The company is planning a recruitment drive and wants to identify the days of the
week on which 20 or more staff members were hired. Your report must list the
days and the number of employees hired on each of them.
DBMS USING ORACLE

CONCEPT
Displaying Data
from Multiple Tables
Using Joins
DBMS USING ORACLE > DISPLAYING DATA FROM MULTIPLE TABLES
USING JOINS

Topics covered:
Types of JOINS and its syntax
Natural join
Join with the USING Clause
Join with the ON Clause
Self-join
Non-equijoins
OUTER join:
LEFT OUTER join
RIGHT OUTER join
FULL OUTER join
Cartesian product
Cross join
DBMS USING ORACLE > JOINING TABLES - SYNTAX

ANSI SQL 99 Syntax to retrieve data from multiple tables

SELECT table1.column, table2.column


FROM table1
[NATURAL JOIN table2] |
[JOIN table2 USING (column_name)] |
[JOIN table2
ON (table1.column_name = table2.column_name)]|
[LEFT|RIGHT|FULL OUTER JOIN table2
ON (table1.column_name = table2.column_name)]|
[CROSS JOIN table2];
DBMS USING ORACLE > NATURAL JOIN

The NATURAL JOIN clause is based on all the columns in the two tables that
have the same name.
It selects rows from the two tables that have equal values in all matched
columns.
If the columns having the same names have different data types, an error is
returned.
DBMS USING ORACLE > NATURAL JOIN

NATURN JOIN or PURE NATURAL JOIN - In the below query department and
location table is joined based on common columns(columns having same name
and same data type) between the two tables that have equal values
SELECT department_id, department_name,
location_id, city
FROM departments
NATURAL JOIN locations ;

NATURN JOIN using where clause – Below query retrieves the data from
departments and locations table based on the common columns having equal
values and restricts the data using the WHERE clause for departments 20 and 50

SELECT department_id, department_name,


location_id, city
FROM departments
NATURAL JOIN locations
WHERE department_id IN (20, 50);
DBMS USING ORACLE > NATURAL JOIN – EQUI JOIN OR INNER JOIN

To determine the location of a department, you need to compare the compare


the value in the LOCATION_ID column in the DEPARTMENTS table with the
LOCATION_ID values in the LOCATIONS table.
The relationship between the DEPARTMENTS and LOCATIONS tables is an
equijoin; that is, values in the LOCATIONS_ID column in both the tables must
be equal.
Equijoins are also called simple joins or inner joins.
DBMS USING ORACLE > NATURAL JOIN
Retrieve department_id, department_name, location_id and city

STEP1: Retrieve the department_id, STEP2: Retrieve location_id, city from


department_name from departments table locations table
Department_id Department_name Location_id Location_id City

10 Administration 1700 2400 London


20 Marketing 1800 1700 Seattle
30 Purchasing 1700 1800 Toronto
40 Human Resources 2400 2000 Whitehorse
2100 Bombay
Department_id Department_name Location_id City 2200 Sydney
10 Administration 1700 Seattle Inner Join
20 Marketing 1800 Toronto
30 Purchasing 1700 Seattle
40 Human Resources 2400 London
DBMS USING ORACLE > JOIN – USING CLAUSE

If several columns between two tables have the same names but the data
types do not match, use the USING clause to specify the columns for the
equijoin.
Use the USING clause to match only one column when more than one column
matches.
The NATURAL SELECT
JOIN and USING clauses
employee_id, are mutually exclusive.
last_name,
location_id, department_id
FROM employees JOIN departments
USING (department_id) ;
DBMS USING ORACLE > JOIN – USING CLAUSE WITH TABLE ALIASES

Do not qualify a column that is used in the USING clause.


If the same column is used elsewhere in the SQL statement, do not alias it.
SELECT l.city, d.department_name
FROM locations l JOIN departments d
USING (location_id)
WHERE d.location_id = 1400;

The columns that are common in both the tables, but not used in the USING
clause, must be prefixed with a table alias; otherwise, you get the “column
ambiguously defined” error.

SELECT first_name, d.department_name, d.manager_id


FROM employees e JOIN departments d USING (department_id)
WHERE department_id = 50;
DBMS USING ORACLE > JOIN – ON CLAUSE

The join condition for the natural join is basically an equijoin of all columns with the
same name.
Use the ON clause to specify arbitrary conditions or specify columns to join.
The join condition is separated from other search conditions.
The ON clause makes code easy to understand.
The table alias is necessary to qualify the matching column_names.
You can also use the ON clause to join columns that have different names
SELECT e.employee_id, e.last_name,
e.department_id,
d.department_id, d.location_id
FROM employees e JOIN departments d
ON (e.department_id = d.department_id);
DBMS USING ORACLE > JOIN – ON CLAUSE – THERE WAY JOIN

A three-way join is a join of three tables

SELECT employee_id, city, department_name


FROM employees e
JOIN departments d
ON d.department_id = e.department_id
JOIN locations l
ON d.location_id = l.location_id;
DBMS USING ORACLE > ADDITIONAL JOIN CONDITIONS

Use the AND clause or the WHERE clause to apply additional conditions:

SELECT e.employee_id, e.last_name,


e.department_id,
d.department_id, d.location_id
FROM employees e JOIN departments d
ON (e.department_id = d.department_id)
AND e.manager_id = 149 ;
O
SELECT e.employee_id,r e.last_name,
e.department_id,
d.department_id, d.location_id
FROM employees e JOIN departments d
ON (e.department_id = d.department_id)
WHERE e.manager_id = 149 ;
DBMS USING ORACLE > SELF JOIN
To find the name of each employees manager, you need to join the
EMPLOYEES table to itself – perform a self join
To find who is the of the manager of employee Ernst:
Find Ernst in the EMPLOYEES table by looking at the LAST_NAME column
Find the manager ID for Ernst by looking at the MANAGER_ID column.
Ernst’s manager IDis 103
Find the name of the manager with EMPLOYEE_ID 103 by looking at the
LAST_NAME column. Hunold’s employee number is 103, so Hunold is
Ernst’s manager.
EMPLOYEES (WORKER) EMPLOYEES (MANAGER)
DBMS USING ORACLE > SELF JOIN

Below query lists the employee last name and their manager’s last_name
For employees who do not have managers, NULL would be displayed for their
managers last_name

SELECT worker.last_name emp, manager.last_name mgr


FROM employees worker JOIN employees manager
ON (worker.manager_id = manager.employee_id);
DBMS USING ORACLE > NON- EQUI JOINS

A non-equijoin is a join condition containing something other than an equality


operator.
EMPLOYEES JOB_GRADES

The JOB_GRADES table defines the


LOWEST_SAL and HIGHEST_SAL range
… of values for each GRADE_LEVEL.
Therefore, the GRADE_LEVEL column can
be used to assign grades to each
employee.
DBMS USING ORACLE > NON EQUI JOINS

The below query creates a non-equijoin to evaluate an employee’s salary


grade. The salary must be between any pair of the low and high salary ranges.

SELECT e.last_name, e.salary, j.grade_level


FROM employees e JOIN job_grades j
ON e.salary
BETWEEN j.lowest_sal AND j.highest_sal;
DBMS USING ORACLE > CROSS JOINS

A Cartesian product is generated if a join condition is omitted

EMPLOYEES (20 rows) DEPARTMENTS (8 rows)

Cartesian product:
20 x 8 = 160 rows


DBMS USING ORACLE > CROSS JOINS

The CROSS JOIN clause produces the cross-product of two tables.


This is also called a Cartesian product between the two tables.

SELECT last_name, department_name


FROM employees
CROSS JOIN departments ;
DBMS USING ORACLE > OUTER JOINS

DEPARTMENTS Equijoin with EMPLOYEES

There are no employees …


in department 190.

Employee “Grant” has


not been assigned a
department ID.
DBMS USING ORACLE > INNER JOINS VS OUTER JOINS

In SQL:1999, the join of two tables returning only matched rows is called an
INNER join.
A join between two tables that returns the results of the INNER join as well as the
unmatched rows from the left (or right) table is called a left (or right) OUTER join.
DBMS USING ORACLE > LEFT OUTER JOINS

Left outer join retunes the results of the INNER join between two tables as well as
the unmatched rows from the left table

SELECT e.last_name, e.department_id, d.department_name


FROM employees e LEFT OUTER JOIN departments d
ON (e.department_id = d.department_id) ;


DBMS USING ORACLE > RIGHT OUTER JOINS

Right outer join retunes the results of the INNER join between two tables as well as
the unmatched rows from the right table

SELECT e.last_name, d.department_id, d.department_name


FROM employees e RIGHT OUTER JOIN departments d
ON (e.department_id = d.department_id) ;


DBMS USING ORACLE > FULL OUTER JOINS

Full outer join retunes the results of the INNER join between two tables as well as
the unmatched rows from both the tables

SELECT e.last_name, d.department_id, d.department_name


FROM employees e FULL OUTER JOIN departments d
ON (e.department_id = d.department_id) ;


DBMS USING ORACLE > DISPLAYING DATA FROM MULTIPLE TABLES USING JOINS

GUIDED ACTIVITY
DBMS USING ORACLE > DISPLAYING DATA FROM MULTIPLE TABLES USING JOINS -
GUIDED ACTIVITY

Fetch the EMPLOYEE_ID, JOB_ID, DEPARTMENT_ID, LAST_NAME, HIRE_DATE,


and END_DATE values for all rows retrieved using a pure natural join. Alias the
EMPLOYEES table

Produce a report with one column aliased as Managers. with each ach row
containing a sentence of the format FIRST_NAME LAST_NAME is manager of the
DEPARTMENT_NAME

You are required to retrieve the employee’s LAST_NAME, EMPLOYEE_ID,


manager’s LAST_NAME, and employee’s DEPARTMENT_ID for the rows with
DEPARMENT_ID values of 10, 20, or 30. Alias the EMPLOYEES table as E and the
second instance of the EMPLOYEES table as M. Sort the results based on the
DEPARTMENT_ID column
DBMS USING ORACLE > DISPLAYING DATA FROM MULTIPLE TABLES USING JOINS -
GUIDED ACTIVITY

Retrieve the DEPARTMENT_NAME and DEPARTMENT_ID values for those


departments to which no employees are currently assigned
DBMS USING ORACLE

CONCEPT
Using Subqueries to
Solve Queries
DBMS USING ORACLE > USING SUBQUERIES TO SOLVE QUERIES

Topics covered:
Subquery: Types, syntax, and guidelines
Single-row subqueries:
Group functions in a subquery
HAVING clause with subqueries
Multiple-row subqueries
Use ALL or ANY operator
Using the EXISTS operator
Null values in a subquery
DBMS USING ORACLE > USING SUBQUERIES TO SOLVE A PROBLEM

A subquery is a SELECT statement that is embedded within another


SELECT statement
Suppose to find out all employees, Who has a salary greater than
Smith?Main query:

Which employees have salaries greater than Smith’s


salary?

Subquery:

What is Smith’s salary?


DBMS USING ORACLE > SUBQUERY SYNTAX

SELECT select_list
Outer Query FROM table
WHERE expr cmp opr
(SELECT select_list Inner Query
FROM table);

The subquery (inner query) executes before the main query (outer query)
The result of the subquery is used by the main query to restrict the rows
Comparison operator can be any of >, =, >=, <, <>, <= (Single row operators) and
IN, ANY, ALL, EXISTS (Multiple row operators)
The subquery generally executes first, and its output is used to complete the
query condition for the main (or outer) query
DBMS USING ORACLE > SUBQUERY - EXAMPLE

SELECT last_name, salary


FROM employees
WHERE salary > 11000
(SELECT salary
FROM employees
WHERE last_name = 'Abel');

Enclose subqueries in parentheses


Place subqueries on the right side of the comparison condition for readability.
(However, the subquery can appear on either side of the comparison
operator.)
Use single-row operators with single-row subqueries and multiple-row
operators with multiple-row subqueries
DBMS USING ORACLE > SUBQUERY - TYPES

Single-row subquery : Queries that return only one row from the inner SELECT
statement
Main query
returns
Subquery ST_CLERK

Multiple-row subquery -:Queries that return more than one row from the inner
SELECT statement Main query
returns ST_CLERK
Subquery
SA_MAN
DBMS USING ORACLE > SINGLE ROW SUBQUERIES

Return only one row


Use single-row comparison operators
Operator Meaning
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
<> Not equal to
DBMS USING ORACLE > SINGLE ROW SUBQUERIES - EXAMPLE

SELECT last_name, job_id, salary


FROM employees
WHERE job_id = SA_REP
(SELECT job_id
FROM employees
WHERE last_name = 'Taylor')
AND salary > 8600
(SELECT salary
FROM employees
WHERE last_name = 'Taylor');
DBMS USING ORACLE > GROUP FUNCTIONS IN SUBQUERY

SELECT last_name, job_id, salary


FROM employees
2500
WHERE salary =
(SELECT MIN(salary)
FROM employees);
DBMS USING ORACLE > GROUP FUNCTIONS IN SUBQUERY

The Oracle server executes the subqueries first.


The Oracle server returns results into the HAVING clause of the main
query.
SELECT department_id, MIN(salary)
FROM employees
GROUP BY department_id 2500
HAVING MIN(salary) >
(SELECT MIN(salary)
FROM employees
WHERE department_id = 50);

SELECT employee_id, last_name


FROM employees
WHERE salary =
(SELECT MIN(salary) Single-row operator
FROM employees with multiple-row
GROUP BY department_id); subquery
DBMS USING ORACLE > SUBQUERIES RETURNING NO ROWS

SELECT last_name, job_id


FROM employees
WHERE job_id =
(SELECT job_id
FROM employees
WHERE last_name = 'Haas');

Subquery returns no rows because


there is no employee named
“Haas.”
DBMS USING ORACLE > MULTIPLE ROW SUBQUERIES

Return more than one row


Use multiple-row comparison operators
Operator Meaning
IN Equal to any member in the list
ANY Must be preceded by =, !=, >, <, <=, >=. Returns
TRUE if at least one element exists in the
result-set of the Subquery for which the relation
ALL isTRUE.
Must be preceded by =, !=, >, <, <=, >=. Returns
TRUE if the relation is TRUE for all elements in the
result set of the Subquery.
DBMS USING ORACLE > MULTIPLE ROW SUBQUERIES – ANY OPERATOR

The ANY operator compares a value to each value returned by a subquery

SELECT employee_id, last_name, job_id, salary


FROM employees 9000, 6000, 4200

WHERE salary < ANY


(SELECT salary
FROM employees
WHERE job_id = 'IT_PROG')
AND job_id <> 'IT_PROG';

<ANY means less than the


maximum.

… >ANY means more than the


minimum.
=ANY is equivalent to IN.
DBMS USING ORACLE > MULTIPLE ROW SUBQUERIES – ALL OPERATOR

The ALL operator compares a value to every value returned by a subquery.

SELECT employee_id, last_name, job_id, salary


FROM employees 9000, 6000, 4200

WHERE salary < ALL


(SELECT salary
FROM employees
WHERE job_id = 'IT_PROG')
AND job_id <> 'IT_PROG';

<ALL means less than the


minimum.
>ALL means more than the
maximum.
DBMS USING ORACLE > EXISTS OPERATOR

The EXISTS operator is used in queries where the query result depends on whether
or not certain rows exist in a table.
It evaluates to TRUE if the subquery returns at least one row.

SELECT employee_id,salary,last_name FROM employees M


WHERE EXISTS
(SELECT employee_id FROM employees W
WHERE (W.manager_id=M.employee_id)
AND W.salary > 10000);

SELECT * FROM departments d


WHERE NOT EXISTS
(SELECT * FROM employees e
WHERE
e.department_id=d.department_id);
DBMS USING ORACLE > NULL VALUES IN SUBQUERY

Display all the employees who do not have any subordinates

SELECT emp.last_name
FROM employees emp
WHERE emp.employee_id NOT IN
(SELECT
mgr.manager_id
FROM employees Subquery returns no rows because
mgr) one of the values returned by a
subquery is Null.
DBMS USING ORACLE > USING SUBQUERIES TO SOLVE QUERIES

GUIDED ACTIVITY
DBMS USING ORACLE > USING SUBQUERIES TO SOLVE QUERIES - GUIDED ACTIVITY

A query that uses subqueries in the column projection list. – Write a query to
retrieve todays date, No. of departments aliased as dept_count and no of
employees aliased as Emp_count. This query should report on the current
numbers of departments and staff as on date

Write a query that uses sub-queries to identify all the employees who are
managers

Write a query that uses sub-queries to identify the highest salary paid in each
country.

Write a query that uses sub-queries, to identify all employees who work in
departments located in the United Kingdom.
DBMS USING ORACLE > USING SUBQUERIES TO SOLVE QUERIES - GUIDED ACTIVITY

Write a query that uses sub-queries to identify all the employees who earn more than
the average and who work in any of the IT departments.

Write a query that uses sub-queries to determine who earns more than Mr. Tobias:

Write a query that uses sub-queries to determine who earns more than Mr. Taylor
DBMS USING ORACLE

CONCEPT
Using set operators
(self study)
DBMS USING ORACLE > USING SET OPERATORS (SELF STUDY)

Topics covered:
Set Operators: Types and guidelines
Tables used in this lesson
UNION and UNION ALL operator
INTERSECT operator
MINUS operator
Matching the SELECT statements
Using the ORDER BY clause in set operations
DBMS USING ORACLE > USING SET OPERATORS

A B A B

UNION/UNION ALL

A B

INTERSECT

A B

MINUS
DBMS USING ORACLE > UNION OPERATOR

A B

The UNION operator returns rows from both queries after eliminating
duplications.
DBMS USING ORACLE > USING THE UNION OPERATOR

Display the current and previous job details of all employees. Display each
employee only once.

SELECT employee_id, job_id


FROM employees
UNION
SELECT employee_id, job_id
FROM job_history;


DBMS USING ORACLE > UNION ALL OPERATOR

A B

The UNION ALL operator returns rows from both queries, including all
duplications.
DBMS USING ORACLE > USING THE UNION ALL OPERATOR

Display the current and previous departments of all employees.

SELECT employee_id, job_id, department_id


FROM employees
UNION ALL
SELECT employee_id, job_id, department_id
FROM job_history
ORDER BY employee_id;


DBMS USING ORACLE > INTERSECT OPERATOR

A B

The INTERSECT operator returns rows that are common to both queries.
DBMS USING ORACLE > USING THE INTERSECT OPERATOR

Display the employee IDs and job IDs of those employees who currently have a
job title that is the same as their previous one (that is, they changed jobs but
have now gone back to doing the same job they did previously).

SELECT employee_id, job_id


FROM employees
INTERSECT
SELECT employee_id, job_id
FROM job_history;
DBMS USING ORACLE > MINUS OPERATOR

A B

The MINUS operator returns all the distinct rows selected by the first query, but
not present in the second query result set.
DBMS USING ORACLE > USING THE MINUS OPERATOR

Display the employee IDs of those employees who have not changed their
jobs even once.
SELECT employee_id
FROM employees
MINUS
SELECT employee_id
FROM job_history;


DBMS USING ORACLE > MATCHING SELECT STATEMENTS IN SET
OPERATIONS

Using the UNION operator, display the location ID, department name, and the
state where it is located.

You must match the data type (using the TO_CHAR function or any other
conversion functions) when columns do not exist in one or the other table.

SELECT location_id, department_name


"Department",
TO_CHAR(NULL) "Warehouse location"
FROM departments
UNION
SELECT location_id, TO_CHAR(NULL) "Department",
state_province
FROM locations;
DBMS USING ORACLE > MATCHING SELECT STATEMENTS IN SET OPERATIONS -
EXAMPLE

Using the UNION operator, display the employee ID, job ID, and salary of all

employees.

SELECT employee_id, job_id,salary


FROM employees
UNION
SELECT employee_id, job_id,0
FROM job_history;


DBMS USING ORACLE > USING ORDER BY CLAUSE IN SET OPERATIONS

The ORDER BY clause can appear only once at the end of the compound query.

Component queries cannot have individual ORDER BY clauses.

The ORDER BY clause recognizes only the columns of the first SELECT query.

By default, the first column of the first SELECT query is used to sort the output
in an ascending order.
DBMS USING ORACLE

SUMMARY
DBMS USING ORACLE
DBMS USING ORACLE > SUMMARY

Key points discussed in this Lecture:

Group functions are used to group the data in a table

Joins are used to retrieve data from multiple tables

A subquery is a SELECT statement that is embedded within


another SELECT statement
THANK
YOU
Copyright Manipal Global Education Services Pvt. Ltd. All Rights
Reserved.
All product and company names used or referred to in this work are trademarks or registered trademarks of their respective holders. Use of them in this
work does not imply any affiliation with or endorsement by them.

This work contains a variety of copyrighted material. Some of this is the intellectual property of Manipal Global Education, some material is owned by others
which is clearly indicated, and other material may be in the public domain. Except for material which is unambiguously and unarguably in the public domain,
permission is not given for any commercial use or sale of this work or any portion or component hereof. No part of this work (except as legally allowed for
private use and study) may be reproduced, adapted, or further disseminated without the express and written permission of Manipal Global Education or the
legal holder of copyright, as the case may be.

You might also like