SQL2
SQL2
Oracle-Day-3
DBMS USING ORACLE
OBJECTIVES
DBMS using oracle
DBMS USING ORACLE > OBJECTIVES
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
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(expr) returns the number of rows with non-null values for expr:
SELECT COUNT(commission_pct)
FROM employees
WHERE department_id = 50;
SELECT AVG(commission_pct)
FROM employees;
COUNT(expr) returns the number of rows with non-null values for expr:
Group by clause divides the rows into groups and summary information
of each group can be obtained
EMPLOYEES
3500
6400
10033
…
DBMS USING ORACLE > GROUPING ROWS – GROUP BY CLAUSE
FUNCTIONS
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 ;
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;
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
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
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.
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
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
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
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.
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
Use the AND clause or the WHERE clause to apply additional conditions:
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
Cartesian product:
20 x 8 = 160 rows
…
…
DBMS USING ORACLE > CROSS 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
…
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
…
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
…
DBMS USING ORACLE > DISPLAYING DATA FROM MULTIPLE TABLES USING JOINS
GUIDED ACTIVITY
DBMS USING ORACLE > DISPLAYING DATA FROM MULTIPLE TABLES USING JOINS -
GUIDED ACTIVITY
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
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
Subquery:
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
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
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 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.
…
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
…
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).
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.
Using the UNION operator, display the employee ID, job ID, and salary of all
employees.
…
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.
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
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.