Module4-AdvanceSQL
Module4-AdvanceSQL
Advanced Queries
CHAPTER 7
Main Query
Subquery
?
“What is Jones’s salary?”
Subqueries
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);
ENAME
----------
KING
FORD
SCOTT
Guidelines for Subqueries
• Single-row subquery
Main query
returns
Subquery CLERK
• Multiple-row subquery
Main query
returns CLERK
Subquery
MANAGER
• Inline Views
From Clause of Main Query
returns Single-row
Subquery Multiple-row
• Multiple-column subquery Multiple-column
Main query
returns CLERK 7900
Subquery
MANAGER 7698
Single-Row Subqueries
Operator Meaning
= Equal to
• Find all employees who get the same salary as emp 7876 and
has the same job as 7369
ENAME JOB
---------- ---------
MILLER CLERK
Group Functions in Subquery
• Find name, job and salary of all employees who get the
minimum salary
• Find all employees who get the more than the minimum salary in
each department
ERROR:
ORA-01427: single-row subquery returns more than
one row
no rows selected
Will This Statement Work?
no rows selected
Multiple-Row Subqueries
• Return more than one row.
• You may use the IN, ANY, or ALL operator in outer query to
handle a subquery that returns multiple rows.
Operator Meaning
SELECT [column_name ]
FROM [table_name]
WHERE expression operator
{ALL | ANY | SOME} ( subquery )
IN Operator: The IN operator returns 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.
Example
SELECT emp_last_name "Last Name",
emp_first_name "First Name"
FROM employee
WHERE emp_ssn IN
(SELECT dep_emp_ssn
FROM dependent);
• The general form of the WHERE clause for this type of query
is shown here.
• When used with the greater than comparison operator, "> ANY"
means greater than some value.
• Find empno, ename, job of all employees who get more salary than
that of clerks.
• List the employees that makes the same salary as other employee
with empno=7521 with the same job also.
An "= ANY" (Equal Any) Example
• The "= ANY" operator is exactly equivalent to the IN operator.
• OUTPUT
• Nested queries
• Complete select-from-where blocks within WHERE
clause of another query.
• EXISTS function
• Check whether the result of a correlated nested query is
empty or not. They are Boolean functions that return a TRUE
or FALSE result.
Q7:
field1 field2
A 1
field1 field2
A 2
A 1
A 3
B 2
B 1
3
B 2
B 3
Data from Multiple Tables
EMP DEPT
EMPNO ENAME ... DEPTNO DEPTNO DNAME LOC
------ ----- ... ------ ------ ---------- --------
7839 KING ... 10 10 ACCOUNTING NEW YORK
7698 BLAKE ... 30 20 RESEARCH DALLAS
... 30 SALES CHICAGO
7934 MILLER ... 10 40 OPERATIONS BOSTON
Example:
Schema: Movies (movie_title, director_id, release_date)
People(person_fname, person_lname, person_id)
ENAME DNAME
------ ----------
KING ACCOUNTING
“Cartesian BLAKE ACCOUNTING
product: ...
KING RESEARCH
14*4=56 rows” BLAKE RESEARCH
...
56 rows selected.
Types of Joins
•Natural Join
•Inner Join
• Equi Join
• Self Join
• Outer join
Same id
9801 9801
Join
Student Music
9801
Product
Natural Join
eg. 25 Make a list of students and the instruments they
learn. (Natural Join)
SELECT s.class, s.name, s.id, m.type ;
FROM student s, music m ;
WHERE s.id=m.id ORDER BY class, name
Three Parts :
eg. 26
Student Join
Condition Group By
m.type= "Piano" class
Product
Music
Natural Join
eg. 26 Find the number of students learning piano in
each class.
SELECT s.class, COUNT(*) ;
FROM student s, music m ;
WHERE s.id=m.id AND m.type="Piano" ;
GROUP BY class ORDER BY class
class cnt
Result
1A 4
1B 2
1C 1
• Dangling tuples in Join
• Usually, only a subset of tuples of each relation will actually
participate in a join, i.e. only tuples that match with the joining
attributes.
• Tuples of a relation not participating in a join are called
dangling tuples.
LEFT (OUTER) JOIN: Returns all records from the left table, and the
matched records from the right table.
RIGHT (OUTER) JOIN: Returns all records from the right table, and
the matched records from the left table.
• Right Outer-Join
• R1 ROJ R2 is similar to a natural join but keep all
dangling tuples of R2.
• SELECT *
• FROM TableA LEFT OUTER JOIN TableB
• ON TableA.PK = TableB.PK
SQL Joins…Example
SELECT S.name, E.classid
FROM Students S LEFT OUTER JOIN Enrolled E
ON S.sid=E.sid
E.sid E.classid
S S.name S.sid E
Jones 11111 11111 History105
Smith 22222 11111 DataScience19
4
Brown 33333
22222 French150
44444 English10
S.name E.classid
Jones History105
Jones DataScience19
4
Smith French150
Brown NULL
Right Outer Join
• SELECT *
• FROM TableA RIGHT OUTER JOIN TableB
• ON TableA.PK = TableB.PK
SQL Joins…..example
SELECT S.name, E.classid
FROM Students S RIGHT OUTER JOIN Enrolled E
ON S.sid=E.sid
E.sid E.classid
S S.name S.sid E
Jones 11111 11111 History105
Smith 22222 11111 DataScience19
4
Brown 33333
22222 French150
S.name E.classid 44444 English10
Jones History105
Jones DataScience19
4
Smith French150
NULL English10
Full Outer Join
• Full outer join produces the
set of all records in Table A
and Table B, with matching
records from both sides
where available. If there is
no match, the missing side
will contain null.
Full Outer Join
TableA TableB
Value PK PK Value
FOX 1 1 TROT
COP 2 2 CAR
TAXI 3 3 CAB
LINCOLN 4 NULL NULL
ARIZONA 5 NULL NULL
WASHINGTON 6 6 MONUMENT
DELL 7 7 PC
LUCENT 10 NULL NULL
NULL NULL 8 MICROSOFT
NULL NULL 9 APPLE
NULL NULL 11 SCOTCH
E.sid E.classid
S S.name S.sid E
Jones 11111 11111 History105
Smith 22222 11111 DataScience19
4
Brown 33333
22222 French150
S.name E.classid 44444 English10
Jones History105
Jones DataScience19
4
Smith French150
NULL English10
Brown NULL
Inner Join
• Inner join produces only the
set of records that match in
both Table A and Table B
• Most commonly used, best
understood join
• Note:
INNER JOIN Syntax
• Inner Joins do not have to
use equality to join the
SELECT column_name(s) fields
FROM table1 • Can use <, >, <>
INNER JOIN table2
ON table1.column_name =
table2.column_name;
Inner Join sample Tables
Inner Join
TableA TableB
Value PK PK Value
FOX 1 1 TROT
COP 2 2 CAR
TAXI 3 3 CAB
WASHINGTON 6 6 MONUMENT
DELL 7 7 PC
SELECT *
FROM TableA INNER JOIN TableB
ON TableA.PK = TableB.PK;
OR
SELECT *FROM TableName1
JOIN TableName2
ON TableName1.ColumnName =
TableName2.ColumnName;
Example:
Suppose we have two tables, namely state and city, which contain the
name of the states and the name of the cities, respectively.
In this example, we will map the cities with the states in which they
are present.
State_ID State_Name
1 Uttar Pradesh
2 Uttarakhand
3 Madhya Pradesh
The table city is shown below:
City_ID City_Name
1 Lucknow
1 Gorakhpur
1 Noida
2 Dehradun
2 Rishikesh
3 Gwalior
Now, if we execute a query of Equi-join using the equality operation
and the WHERE clause, then-
Output:
Person Table
Apartment Table
SELECT first_name, last_name, price, city FROM person JOIN
apartment ON apartment.id = person.apartment_id ;
SELECT first_name, last_name, min_price, max_price, price, city
FROM person
JOIN apartment ON apartment.id != person.apartment_id
AND price BETWEEN min_price AND max_price
ORDER BY last_name;
AGGREGATE Functions
GROUP BY clause
HAVING Clause
What Are AGGREGATE Functions?
• Operate on sets of rows to give one result per group.
EMP
DEPTNO SAL
--------- ---------
10 2450
10 5000
10 1300
20 800
20 1100
20 3000 “maximum MAX(SAL)
20 3000 salary in ---------
20 2975 the EMP table” 5000
30 1600
30 2850
30 1250
30 950
30 1500
30 1250
Common Group Functions
◦ AVG
◦ COUNT
◦ MAX
◦ MIN
◦ SUM
Using Group Functions
COUNT(COMM)
-----------
4
Group Functions & Null Values
• Group functions ignore null values in the column.
AVG(COMM)
---------
550
• Query 15: Find the maximum salary, the minimum salary,
and the average salary among all employees.
EMP
DEPTNO SAL
--------- ---------
10 2450
10 5000 5000
10 1300
20 800
“maximum DEPTNO MAX(SAL)
20 1100
salary
20 3000 3000 per department --------- ---------
20 3000 greater than 10 5000
20 2975 $2900” 20 3000
30 1600
30 2850
30 1250 2850
30 950
30 1500
30 1250
Using ‘HAVING’ Clause
DEPTNO MAX(SAL)
--------- ---------
10 5000
20 3000
Using ‘HAVING’ Clause
JOB PAYROLL
--------- ---------
ANALYST 6000
MANAGER 8275
Nesting Group Functions
MAX(AVG(SAL))
-------------
2916.6667
THE HAVING-CLAUSE (contd.)
• Query Simplicity A view can draw data from several different tables
and present it as a single table, turning multi-table queries into
single-table queries against the view.
• Select the columns from this view by the given alias names.
Retrieving Data from a View
SQL> SELECT *
2 FROM salvu30;
6 rows selected.
Querying a View
SQL*Plus
USER_VIEWS
SELECT *
FROM empvu10; EMPVU10
SELECT empno, ename, job
FROM employee
WHERE deptno = 10;
7839 KING PRESIDENT
7782 CLARK MANAGER EMP
7934 MILLER CLERK
Example1:
• Column aliases in the CREATE VIEW clause are listed in the same
order as the columns in the subquery.
Creating a Complex View
• Create a complex view that contains group functions to display
values from two tables.
● There are NOT NULL columns in the base tables that are not
selected by the view.
CREATE VIEW DEPT_INFO(Dept_name,
No_of_emps, Total_sal)
AS SELECT Dname, COUNT (*), SUM (Salary)
FROM DEPARTMENT, EMPLOYEE
WHERE Dnumber = Dno
GROUP BY Dname;
DEPT_INFO
1.Query Modification
2.View Materialization
1.Query Modification
• Every time we query the view, the view’s query is then run on
the underlying tables.
In case of View we always get latest data Materialized view we need to refresh the
view for getting latest data.
In case of view its only the logical view of in case of Materialized view we get
table no separate copy of table physically separate copy of table
A database trigger is a stored PL/SQL program unit
associated with a specific database table. ORACLE
executes (fires) a database trigger automatically when a
given SQL operation (like INSERT, UPDATE or
DELETE) affects the table. Unlike a procedure, or a
function, which must be invoked explicitly, database
triggers are invoked implicitly.
Database triggers can be used to perform any of the following:
• Audit data modification.
• Log events transparently.
• Enforce complex business rules.
• Derive column values automatically.
• Implement complex security authorizations.
• Maintain replicate tables.
• You can associate up to 12 database triggers with
a given table. A database trigger has three parts:
a triggering event, an optional trigger
constraint, and a trigger action.