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

Module4-AdvanceSQL

The document covers advanced SQL queries, including complex retrievals, subqueries, and the use of NULL values. It explains various types of subqueries, such as single-row and multiple-row subqueries, and how to use comparison operators like IN, ANY, and ALL. Additionally, it discusses the join operation for retrieving data from multiple tables and provides examples of SQL syntax for these concepts.

Uploaded by

kg10112005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Module4-AdvanceSQL

The document covers advanced SQL queries, including complex retrievals, subqueries, and the use of NULL values. It explains various types of subqueries, such as single-row and multiple-row subqueries, and how to use comparison operators like IN, ANY, and ALL. Additionally, it discusses the join operation for retrieving data from multiple tables and provides examples of SQL syntax for these concepts.

Uploaded by

kg10112005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 145

Module-4

Advanced Queries
CHAPTER 7

More SQL: Complex Queries,


Triggers & Views
More Complex SQL Retrieval Queries

• Additional features allow users to specify more


complex retrievals from database:
◦ Nested queries, joined tables, and outer joins (in the
FROM c.lause), aggregate functions, and grouping.
Comparisons Involving NULL and
Three-Valued Logic
• Meanings of NULL
• Unknown value.
• Unavailable or withheld value.
• Not applicable attribute.

• Each individual NULL value considered to be different from every


other NULL value.

• SQL uses a three-valued logic:


• TRUE, FALSE, and UNKNOWN (like Maybe).

• NULL = NULL comparison is avoided


Comparisons Involving NULL and
Three-Valued Logic(cont’d)
Three-Valued Logic
Comparisons Involving NULL and
Three-Valued Logic(cont’d)

• SQL allows queries that check whether an attribute value is


NULL
• IS or IS NOT NULL
Subquery to Solve a Problem

• “Who has a salary greater than Jones’s?”

Main Query

“Which employees have a salary greater


? than Jones’s salary?”

Subquery

?
“What is Jones’s salary?”
Subqueries

SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);

• The subquery (inner query) executes once


before the main query.
• The result of the subquery is used by the main
query (outer query).
Using a Subquery

SQL> SELECT ename


2 FROM employee
3 WHERE sal > 2975
4 (SELECT sal
5 FROM employee
6 WHERE ename=‘JONES’);

ENAME
----------
KING
FORD
SCOTT
Guidelines for Subqueries

• Enclose subqueries in parentheses.

• Place subqueries on the right side of the comparison


operator.

• Do not add an ORDER BY clause to a subquery.

• Use single-row operators with single-row subqueries.

• Use multiple-row operators with multiple-row subqueries.


Types of 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

• 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


Single-Row Subqueries

• Find all employees who get the same salary as emp 7876 and
has the same job as 7369

SQL> SELECT ename, job


2 FROM employee
3 WHERE job = CLERK
4 (SELECT job
5 FROM employee
6 WHERE empno = 7369)
7 AND sal > 1100
8 (SELECT sal
9 FROM employee
10 WHERE empno = 7876);

ENAME JOB
---------- ---------
MILLER CLERK
Group Functions in Subquery

• Find name, job and salary of all employees who get the
minimum salary

SQL> SELECT ename, job, sal


800
2 FROM employee
3 WHERE sal =
4 (SELECT MIN(sal)
5 FROM employee);

ENAME JOB SAL


---------- --------- ---------
SMITH CLERK 800
HAVING with Subqueries

• The Oracle Server executes subqueries first.

• Find all employees who get the more than the minimum salary in
each department

SQL> SELECT deptno, MIN(sal)


2 FROM employee
3 GROUP BY deptno
800
4 HAVING MIN(sal) >
5 (SELECT MIN(sal)
6 FROM employee
7 WHERE deptno = 20);
What Is Wrong ?

SQL> SELECT empno, ename


2 FROM employee
3 WHERE sal =
4 (SELECT MIN(sal)
5 FROM employee
6 GROUP BY deptno);

ERROR:
ORA-01427: single-row subquery returns more than
one row

no rows selected
Will This Statement Work?

SQL> SELECT ename, job


2 FROM employee
3 WHERE job =
4 (SELECT job
5 FROM employee
6 WHERE ename='SMYTHE');

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.

• Use multiple-row comparison operators

Operator Meaning

IN Equal to any member in the list

ANY Compare value to each value returned by


the subquery

Compare value to every value returned by


ALL
the subquery
General Form of ALL, ANY, SOME

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);

Last Name First Name


------------- ---------------
Bock Douglas
Zhu Waiman
Joyner Suzanne
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.
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
ALL Operator
• Returns true only if the comparison value matches all the
values in the list.
• Display the employee detail with salary less than those whose job
is ‘MANAGER’.
ANY Operator
• The ANY operator return true if the comparison value matches any
of the values in the list.

• 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.

• Display the employees whose salary is more than the minimum


salary of the employees in any department.
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
ANY: Multiple-Row Subqueries

• Find empno, ename, job of all employees who get more salary than
that of clerks.

SQL> SELECT empno, ename, job 1300


2 FROM employee 1100
800
3 WHERE sal < ANY 950
4 (SELECT sal
5 FROM employee
6 WHERE job = 'CLERK')
7 AND job <> 'CLERK';

EMPNO ENAME JOB


--------- ---------- ---------
7654 MARTIN SALESMAN
7521 WARD SALESMAN
Multiple Column Subquery
• A subquery that compares more than one column between the
parent query and subquery is called the multiple column
subqueries.

• 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.

• For example, to find the names of employees that have male


dependents, you can use either IN or "= ANY" – both of the
queries shown below will produce an identical result table.

SELECT emp_last_name "Last Name", emp_first_name "First


Name“ FROM employee WHERE emp_ssn IN
(SELECT dep_emp_ssn
FROM dependent
WHERE dep_gender = 'M');

SELECT emp_last_name "Last Name", emp_first_name "First


Name“ FROM employee WHERE emp_ssn = ANY
(SELECT dep_emp_ssn
FROM dependent
WHERE dep_gender = 'M');
An "= ANY" (Equal Any) Example

• OUTPUT

Last Name First Name


--------------- ---------------
Bock Douglas
Zhu Waiman
Joyner Suzanne
Nested Queries,Tuples, and Set/Multiset
Comparisons

• Nested queries
• Complete select-from-where blocks within WHERE
clause of another query.

• Outer query and nested subqueries


• Comparison operator IN
• Compares value v with a set (or multiset) of values V.

• Evaluates to TRUE if v is one of the elements in V.


Nested Queries (cont’d.)
Make a list of all project numbers for projects that involve
employee Smith either as worker or as a manager of the
department that controls the project: In the first nested query
selects the project numbers of projects that have an employee
with last name ‘Smith’ involved as manager, whereas the second
nested query selects the project numbers of projects that have
an employee with last name ‘Smith’ involved as worker.
Nested Queries (cont’d.)

• Use tuples of values in comparisons and place them within


parentheses.
Nested Queries (cont’d.)
• Use other comparison operators to compare a single value v
• = ANY (or = SOME) operator [equivalent to IN]
• Returns TRUE if the value v is equal to some value in the
set.

• Other operators that can be combined with ANY (or SOME):


>, >=, <, <=, and <>

• ALL: value must exceed all values from nested query.


Nested Queries (cont’d.)

• Avoid potential errors and ambiguities


◦ Create tuple variables (aliases) for all tables referenced in
SQL query.
Understanding a nested (correlated query)

For each E tuple,


Evaluate the nested query which retrieves the Essn values of all
D tuples with the same sex and name as E tuple
If the Ssn value of E tuple is in the result, then select the E tuple.
Correlated Nested Queries

• Queries that are nested using the = or IN comparison


operator can be collapsed into one single block: E.g., Q16 can
be written as:

Q16A: SELECT E.Fname, E.Lname


FROM EMPLOYEE AS E, DEPENDENT AS D
• WHERE E.Ssn=D.Essn AND E.Sex=D.Sex AND
• E.Fname=D.Dependent_name;

• Correlated nested query


• Evaluated once for each tuple in the outer query.
The EXISTS and UNIQUE Functions in SQL for
correlating queries

• 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.

• EXISTS and NOT EXISTS


• Typically used in conjunction with a correlated nested query.

• SQL function UNIQUE(Q)


• Returns TRUE if there are no duplicate tuples in the result of
query Q.
USE of EXISTS

List the managers who have at least one dependent

Q7:

SELECT Fname, Lname


FROM Employee
WHERE EXISTS (SELECT *
FROM DEPENDENT
WHERE Ssn= Essn)

AND EXISTS (SELECT *


FROM Department
WHERE Ssn= Mgr_Ssn)
Multiple Tables:

• SQL provides a convenient operation to


retrieve information from multiple tables.
• This operation is called join.

• The join operation will combine the tables into


one large table with all possible combinations
(Math: Cartesian Product), and then it will filter
the rows of this combined table to yield useful
information.
Multiple Tables:

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

EMPNO DEPTNO LOC


----- ------- --------
7839 10 NEW YORK
7698 30 CHICAGO
7782 10 NEW YORK
7566 20 DALLAS
7654 30 CHICAGO
7499 30 CHICAGO
...
14 rows selected.
General form of Join

SELECT table1.column, table2.column


FROM table1, table2
WHERE table1.column1 = table2.column2;

• Where clause specifies the JOIN Condition.


• Ambiguous Column names are identified by the Table name.
SQL – Join
• A Join is a Query that combines data from multiple tables

◦ Multiple tables are specified in the From Clause.

◦ For two tables to be joined in a sensible manner, they need to


have data in common.

Example:
Schema: Movies (movie_title, director_id, release_date)
People(person_fname, person_lname, person_id)

Query: Select movie_title, person_fname, person_lname


From Movies, People
Where director_id = person_id
SQL – Joining Condition
• For a useful Join query, a joining condition is required.
◦ Defined in where clause as relationships between columns.
◦ Multiple conditions may be defined if multiple columns
shared.
◦ More than two tables can be joined in a query.

Example: Find people who live in same state as studio


Schema:
Studios(studio_id, studio_state, studio_name, studio_city)
People(person_fname, person_lname, person_id, person_state,
person_city)
Query:
Select person_fname, person_lname, studio_name
From Studios, People
Where studio_city = person_city
AND studio_state = person_state
Cartesian Product

• A Cartesian product is used when:


● A Join operation cannot perform.
● All rows in the first table are joined to all
rows in the second table.
Cartesian Product

EMP (14 rows) DEPT (4 rows)


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

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

• Non Equi Join

• Self Join

• Outer join

• Left outer Join

• Right outer Join

• Fulln outer Join


Natural Join

A Natural Join is a join operation that joins two


tables by their common column. This operation
is similar to the setting relation of two tables.

SELECT a.comcol, a.col1, b.col2, expr1, expr2 ;


FROM table1 a, table2 b ;
WHERE a.comcol = b.comcol
Natural Join

eg. 25 Make a list of students and the instruments they


learn. (Natural Join)
id name class id type

Same id
9801 9801

Join
Student Music

id name class type

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

class name id type


Result 1A Aaron 9812 Piano
1A Bobby 9811 Flute
1A Gigi 9824 Recorder
1A Jill 9820 Piano
1A Johnny 9803 Violin
1A Luke 9810 Piano
1A Mary 9802 Flute
: : : :
Natural Join
eg. 26 Find the number of students learning piano in
each class.

Three Parts :

(1) Natural Join.

(2) Condition: m.type="Piano"

(3) GROUP BY class


Natural Join

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.

• How do we keep dangling tuples in the result of a join?


• Use null values to indicate a no-join situation.
Here are the different types of the JOINs in SQL:

(INNER) JOIN: Returns records that have matching values in both


tables.

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.

FULL (OUTER) JOIN: Returns all records when there is a match in


either left or right table.
• Left outer-join
• R1 LOJ R2 is similar to a natural join but keep all
dangling tuples of R1.

• Right Outer-Join
• R1 ROJ R2 is similar to a natural join but keep all
dangling tuples of R2.

• Outer Join (full outer-join)


• LOJ U ROJ is similar to a natural join but keep all dangling
tuples of both R1 and R2.

• The advantages of outer join is to take the union of tuples


from two relations that are not union compatible.
Left Outer Join

• Left outer join produces a


complete set of records from
Table A, with the matching
records (where available) in
Table B. If there is no match,
the right side will contain
null.
Join sample Tables
Left Outer Join
Table Table
A PK B PK Value
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

• 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

• Right outer join produces a


complete set of records
from Table B, with the
matching records (where
available) in Table A. If
there is no match, the left
side will contain null.
Right Outer Join Note: RIGHT are not currently supported
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
NULL NULL 8 MICROSOFT
NULL NULL 9 APPLE
NULL NULL 11 SCOTCH

• 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

• SELECT * FROM TableA FULL OUTER JOIN TableB ON


TableA.PK= TableB.PK
SQL Joins….. Example
SELECT S.name, E.classid
FROM Students S FULL 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
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;

This is the same as doing


SELECT *
FROM TableA, TableB
WHERE TableA.PK = TableB.PK;
Inner Join (continued)
TableA TableB
PK Value PK Value
2 COP 1 TROT
3 TAXI 1 TROT
SELECT * 3 TAXI 2 CAR
FROM TableA 4 LINCOLN 1 TROT
INNER JOIN TableB
ON TableA.PK > TableB.PK; 4 LINCOLN 2 CAR
4 LINCOLN 3 CAB
5 ARIZONA 1 TROT
5 ARIZONA 2 CAR
5 ARIZONA 3 CAB
… More… Rows…
Equi Join
• An Equi Join is a type of SQL join that combines rows from two or
more tables based on a condition that checks for equality between
specified columns.

• This join uses the equality operator = to match column values


across tables. Equijoins are also called joins or inner joins.
• Syntax:
SELECT * FROM TableName1, TableName2
WHERE TableName1.ColumnName =
TableName2.ColumnName;

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-

SELECT * FROM state, city WHERE state.State_Id =


city.City_Id;

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

SELECT column, group_function(column)


FROM table
[WHERE condition]
[ORDER BY column];
Using Group Functions

SQL> SELECT COUNT(*)


2 FROM emp
3 WHERE deptno = 30;
COUNT(*)
---------
6
Using Group Functions

• COUNT(expr) returns the number of nonnull values in the given


column.

SQL> SELECT COUNT(comm)


2 FROM emp
3 WHERE deptno = 30;

COUNT(COMM)
-----------
4
Group Functions & Null Values
• Group functions ignore null values in the column.

SQL> SELECT AVG(comm)


2 FROM emp;

AVG(COMM)
---------
550
• Query 15: Find the maximum salary, the minimum salary,
and the average salary among all employees.

Q15: SELECT MAX(SALARY),


MIN(SALARY),AVG(SALARY)
FROM EMPLOYEE

• Some SQL implementations may not allow more than one


function in the SELECT-clause.
• Query 16: Find the maximum salary, the minimum
salary, and the average salary among employees who
work for the 'Research' department.

Q16: SELECT MAX(SALARY),


MIN(SALARY), AVG(SALARY)
FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER AND
DNAME='Research'
• Queries 17 and 18: Retrieve the total number of employees in
the company (Q17), and the number of employees in the
'Research' department (Q18).

Q17: SELECT COUNT (*)


FROM EMPLOYEE

Q18: SELECT COUNT (*)


FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER AND
DNAME='Research’
GROUPING
• In many cases, we want to apply the aggregate functions to
subgroups of tuples in a relation.

• Each subgroup of tuples consists of the set of tuples that have


the same value for the grouping attribute(s).

• The function is applied to each subgroup independently.

• SQL has a GROUP BY-clause for specifying the grouping


attributes, which must also appear in the SELECT-clause.
GROUPING
• Query 20: For each department, retrieve the department number,
the number of employees in the department, and their average
salary.

Q20: SELECT DNO,COUNT(*), AVG(SALARY)


FROM EMPLOYEE
GROUP BY DNO

In Q20, the EMPLOYEE tuples are divided into groups-


● Each group having the same value for the grouping
attribute DNO.
◦ The COUNT and AVG functions are applied to each such
group of tuples separately.
◦ The SELECT-clause includes only the grouping attribute and
the functions to be applied on each group of tuples.
◦ A join condition can be used in conjunction with grouping.
GROUPING
• Query 21: For each project, retrieve the project number, project
name, and the number of employees who work on that project.

Q21: SELECT PNUMBER, PNAME, COUNT (*)


FROM PROJECT, WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNUMBER, PNAME;

◦ In this case, the grouping and functions are applied after


the joining of the two relations.
THE HAVING-CLAUSE
• Sometimes we want to retrieve the values of these functions
for only those groups that satisfy certain conditions.

• The HAVING-clause is used for specifying a selection


condition on groups (rather than on individual tuples).
Segregating Group Results

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

• HAVING clause is to restrict groups Groups satisfying the


HAVING condition are displayed.

SELECT column, group_function


FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];
Using ‘HAVING’ Clause

SQL> SELECT deptno, max(sal)


2 FROM emp
3 GROUP BY deptno
4 HAVING max(sal)>2900;

DEPTNO MAX(SAL)
--------- ---------
10 5000
20 3000
Using ‘HAVING’ Clause

SQL> SELECT job, SUM(sal) PAYROLL


2 FROM emp
3 WHERE job NOT LIKE 'SALES%'
4 GROUP BY job
5 HAVING SUM(sal)>5000
6 ORDER BY SUM(sal);

JOB PAYROLL
--------- ---------
ANALYST 6000
MANAGER 8275
Nesting Group Functions

• Display the maximum average salary.

SQL> SELECT max(avg(sal))


2 FROM emp
3 GROUP BY deptno;

MAX(AVG(SAL))
-------------
2916.6667
THE HAVING-CLAUSE (contd.)

• Query 22: For each project on which more than two


employees work, retrieve the project number, project
name, and the number of employees who work on that
project.
Q22: SELECT PNUMBER, PNAME, COUNT(*)
FROM PROJECT, WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNUMBER, PNAME
HAVING COUNT (*) > 2;
For each department that has more than five
employees, retrieve the department number and the
number of its employees who are making more than
$40,000.

SELECT Dno, COUNT (*)


FROM EMPLOYEE
WHERE Salary>40000 AND Dno IN 5
( SELECT Dno FROM EMPLOYEE
GROUP BY Dno
HAVING COUNT (*) > 5)
GROUP BY Dno;
For each project, retrieve the project no,project
name and no of employees from dept no 5 who work
on the project..
Select pno,pname,count(*)
From project,works_on,employee
Where pnumber=pno and
Ssn=essn and dno=5
Group By pno,pname;
Views
• Views in SQL are considered as a virtual table.
• A view also contains rows and columns.
• To create the view, we can select the fields from one or more
tables present in the database.
• A view can either have specific rows based on certain
condition or all the rows of a table.
• You can think of a view as a virtual table environment that's
created from one or more tables so that it's easier to work
with data.
Views
Why Use Views?

• To restrict database access.

• To make complex queries easy.

• To allow data independence.

• To present different views of the same data.


Advantages of views

• Security Each user can be given permission to access the database


only through a small set of views that contain the specific data the
user is authorized to see.

• 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.

• Structural simplicity Views can give a user a "personalized" view


of the database structure, presenting the database as a set of virtual
tables that make sense for that user.
• Consistency A view can present a consistent, unchanged image
of the structure of the database, even if the source tables are split,
restructured, or renamed.

• Data Integrity If data is accessed and entered through a view,


the DBMS can automatically check the data to ensure that it
meets the specified integrity constraints.
Simple & Complex Views

• Feature Simple Complex

• Number of tables One One or more

• Contain functions No Yes

• Contain groups of data No Yes

• DML through view Yes Not always


Creating a View

• You embed a subquery within the CREATE VIEW statement.

CREATE VIEW VIEW_NAME AS


SELECT COLUMN1,COLUMN2….
FROM TABLE_NAME
WHERE CONDITION;
• The subquery can contain complex SELECT syntax.
• The subquery cannot contain an ORDER BY clause.
Creating a View
• Create a view, EMPVU10, that contains details of employees
in department 10.

SQL>CREATE VIEW employee2


2 AS SELECT empno, ename, job
3 FROM employee
4 WHERE deptno = 10;
View created.

• Describe the structure of the view by using the DESC


command.

SQL> DESC employee2;


Creating a View

• Create a view by using column aliases in the subquery.

SQL> CREATE VIEW employee2


AS SELECT empno EMPLOYEE_NUMBER,
ename NAME, sal SALARY
FROM employee
WHERE deptno = 30;
View created.

• Select the columns from this view by the given alias names.
Retrieving Data from a View

SQL> SELECT *
2 FROM salvu30;

EMPLOYEE_NO. NAME SALARY


--------------- ---------- ---------
7698 BLAKE 2850
7654 MARTIN 1250
7499 ALLEN 1600
7844 TURNER 1500
7900 JAMES 950
7521 WARD 1250

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:

CREATE VIEW WORKS_ON1


AS SELECT Fname, Lname, Pname, Hours
FROM EMPLOYEE, PROJECT, WORKS_ON
WHERE Ssn = Essn AND Pno = Pnumber;
? WORKS_ON1

Fname Lname Pname Hours

Select fname,lname from works_on1 where


Pname=‘productx’;
Modifying a View

• Modify the EMPVU10 view by using CREATE OR REPLACE


VIEW clause. Add an alias for each column name.

SQL> CREATE OR REPLACE VIEW empvu10


2 (employee_number, employee_name, job_title)
3 AS SELECT empno, ename, job
4 FROM employee
5 WHERE deptno = 10;
View created.

• 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.

SQL> CREATE VIEW dept_sum_vu


2 (name, minsal, maxsal, avgsal)
3 AS SELECT d.dname, MIN(e.sal), MAX(e.sal), AVG(e.sal)
5 FROM employee e, department d
6 WHERE e.deptno = d.deptno
7 GROUP BY d.dname;
View created.
DML Operations on a View

Rules for Performing DML Operations on a View

• You can perform DML operations on SIMPLE VIEWS.

• You cannot remove a row if the view contains the following:


● Group functions
● A GROUP BY clause
● The DISTINCT keyword
DML Operations on a View

Rules for Performing DML Operations on a View


• You cannot modify data in a view if it contains:
● Any of the conditions mentioned in the previous slide.

● Columns defined by expressions.

● The ROWNUM pseudo column.

• You cannot add data if:


● The view contains any of the conditions mentioned above or in the
previous slide.

● 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

Dept_name No_of_emps Total_sal


Removing a View

• Remove a view without losing data because a view is


based on underlying tables in the database.

DROP VIEW view;

SQL> DROP VIEW empvu10;


View dropped.
View Implementation& View Update,

• The problem of how a DBMS can efficiently implement a


view for efficient querying is complex.

Two approaches for implementing a View

1.Query Modification

2.View Materialization
1.Query Modification

• It involves modifying or transforming the view query


(submitted by the user) into a query on the underlying base
tables.
• For example, the query QV1 would be automatically modified
to the following query by the DBMS:
SELECT Fname, Lname
FROM EMPLOYEE, PROJECT, WORKS_ON
WHERE Ssn = Essn AND Pno = Pnumber
AND Pname = ‘ProductX’;
The disadvantage of this approach is that it is inefficient for
views defined via complex queries that are time-consuming to
execute, especially if multiple view queries are going to be
applied to the same view within a short period of time.
2.View Materialization
• A view is an SQL statement stored on the database.

• No data is stored with this view, only the query.

• Every time we query the view, the view’s query is then run on
the underlying tables.

• However, there are times where it would be useful to have data


stored along with the view.

• For example, if you want to find totals of orders over a time


period, you would have to run a query that maybe looks at
several tables, and performs some aggregate functions, and
maybe with some WHERE clauses.
• This query could get expensive and take a long time to run
each time you wanted to get this data.

• There is a way to store this data that is returned by the view.

• This is what a materialized view does.

• A materialized view is a view that stores the results of the


view’s query.

• Whenever you query the materialized view, it returns the


data stored with the view itself. It doesn’t run the view’s
query against the underlying tables. It’s a lot like a table.
• Following is an example to update the age of Ramesh:
1. SQL > UPDATE CUSTOMERS_VIEW
SET AGE = 35
WHERE name='Ramesh';

2. SQL > DELETE FROM CUSTOMERS_VIEW


WHERE age = 22;

3. You need a way to drop the view if it is no longer needed.


DROP VIEW CUSTOMERS_VIEW;
In Views query result is not stored in Materialized view allow to store query
the disk or database result in disk or table.

when we create view using any in case of Materialized view rowid is


table, rowid of view is same as original different.
table
Performance of View is less More

In case of View we always get latest data Materialized view we need to refresh the
view for getting latest data.

No need any methods In case of Materialized view we need


some automatic method so that we can
keep MV refreshed,

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.

• When an event occurs, a database trigger is


fired, and a predefined PL/SQL block will
perform the necessary action.
SYNTAX:
CREATE [OR REPLACE] TRIGGER trigger_name
{BEFORE|AFTER} triggering_event ON table_name
[FOR EACH ROW]
[WHEN condition]
DECLARE
Declaration statements
BEGIN
Executable statements
EXCEPTION
Exception-handling statements
END;
The trigger_name references the name of the trigger.
BEFORE or AFTER specify when the trigger is fired (before or
after the triggering event).
The triggering_event references a DML statement issued
against the table (e.g., INSERT, DELETE, UPDATE).
The table_name is the name of the table associated with the
trigger.
The clause, FOR EACH ROW, specifies a trigger is a row
trigger and fires once for each modified row.
A WHEN clause specifies the condition for a trigger to be
fired.
Bear in mind that if you drop a table, all the associated
triggers for the table are dropped as well.
Triggers may be called BEFORE or AFTER the following
events:
INSERT, UPDATE and DELETE.
The before/after options can be used to specify when the
trigger body should be fired with respect to the
triggering statement.
If the user indicates a BEFORE option, then Oracle fires the
trigger before executing the triggering statement. On the
other hand,
If an AFTER is used, Oracle fires the trigger after executing
the triggering statement.
• A trigger may be a ROW or STATEMENT type.

• If the statement FOR EACH ROW is present in the


CREATE TRIGGER clause of a trigger, the trigger is a row
trigger. A row trigger is fired for each row affected by a
triggering statement.

• A statement trigger, however, is fired only once for the


triggering statement, regardless of the number of rows
affected by the triggering statement
Example: statement trigger
CREATE OR REPLACE TRIGGER mytrig1 BEFORE DELETE OR INSERT OR
UPDATE ON employee
BEGIN
IF (TO_CHAR(SYSDATE, 'day') IN ('sat', 'sun')) OR
(TO_CHAR(SYSDATE,'hh:mi') NOT BETWEEN '08:30' AND '18:30')
THEN RAISE_APPLICATION_ERROR(-20500, 'table is secured');
END IF;
END;
/
The above example shows a trigger that limits the DML
actions to the employee table to weekdays from 8.30am to
6.30pm. If a user tries to insert/update/delete a row in the
EMPLOYEE table, a warning message will be prompted.
CREATE OR REPLACE TRIGGER mytrig2
AFTER DELETE OR INSERT OR UPDATE ON employee
FOR EACH ROW
BEGIN
IF DELETING THEN
INSERT INTO xemployee (emp_ssn, emp_last_name,emp_first_name,
deldate)
VALUES(:old.emp_ssn,:old.emp_last_name,:old.emp_first_name, sysdate);
ELSIF INSERTING THEN
INSERT INTO nemployee (emp_ssn, emp_last_name,emp_first_name,
adddate)
VALUES (:new.emp_ssn, :new.emp_last_name,:new.emp_first_name,
sysdate);
ELSIF UPDATING('emp_salary') THEN
INSERT INTO cemployee (emp_ssn, oldsalary, newsalary, up_date)
VALUES (:old.emp_ssn,:old.emp_salary, :new.emp_salary, sysdate); ELSE
INSERT INTO uemployee (emp_ssn, emp_address, up_date)
VALUES (:old.emp_ssn, :new.emp_address, sysdate);
END IF; END; /
Example: ROW Trigger

• The previous trigger is used to keep track of all the


transactions performed on the employee table. If any
employee is deleted, a new row containing the details of
this employee is stored in a table called xemployee.

• Similarly, if a new employee is inserted, a new row is


created in another table called nemployee, and so on.

• Note that we can specify the old and new values of an


updated row by prefixing the column names with the
:OLD and :NEW qualifiers.
SQL> DELETE FROM employee WHERE emp_last_name =
'Joshi';
1 row deleted.
SQL> SELECT * FROM xemployee;

EMP_SSN EMP_LAST_NAME EMP_FIRST_NAME DELDATE


------------- ----------------------- -------------------------- -----------------
999333333 Joshi Dinesh 02-MAY-03
SQL>ALTER TRIGGER trigger_name DISABLE;
SQL>ALTER TABLE table_name DISABLE ALL TRIGGERS;

To enable a trigger, which is disabled, we can use the


following syntax:
SQL>ALTER TABLE table_name ENABLE trigger_name;

All triggers can be enabled for a specific table by using


the following command
SQL> ALTER TABLE table_name ENABLE ALL TRIGGERS;

SQL> DROP TRIGGER trigger_name

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy