You are on page 1of 51

Topics

Views
Aggregate functions
Joins

SQL - Aggregate
functions

Used when information you want to extract from


a table has to do with the data in the entire
table taken as a set.
Aggregate functions are used in place of column
names in the SELECT statement.
The aggregate functions in SQL are:
SUM(), AVG(), MAX(),MIN(),COUNT()

Aggregate function
- MIN
Returns the smallest value that
occurs in the specified column
Column need not be numeric type
List the minimum unit price from the
item table
SELECT MIN (UnitPrice)
FROM Item;

Aggregate function
- MAX
Returns the largest value that occurs
in the specified column
Column need not be numeric type
List the Maximum unit price from the
item table
SELECT MAX (Total_Available_Balance_in_Dollars)
FROM Customer_Transaction;

Aggregate function
- AVG
Returns the average of all the values in
the
specified column
Column must be numeric data type

List the average Unit price of Class A items in the item


table.
SELECT AVG (UnitPrice)
FROM Item where Class=A;

Aggregate function
- SUM
Adds up the values in the specified column
Column must be numeric data type
Value of the sum must be within the range
of that
data type

List the minimum and Sum of all the Unit of items in


the item table.

SELECT MIN(UnitePrice),SUM (UnitPrice)


FROM Item;

Aggregate function - COUNT

Returns the number of rows in the table


List total number of items in the item table.

SELECT COUNT (*) FROM Item;


List the total number of customer who have their date of registration
information in the customer table.

SELECT COUNT (DateOfReg) FROM Costomer;

Count(*)
=
Count(ColumnName)

No of rows, regardless of NULLs


=
No. of rows that do not have NULL Value

Aggregate function - COUNT


List total number of unique dates on which Bill has been
generated.

SELECT COUNT (DISTINCT BillDate) FROM Bill;

Count(*)
= No of rows, regardless of NULLs
Count(ColumnName)
= No. of rows that do not have
NULL Value

SQL - Using GROUP BY

Related rows can be grouped together by GROUP BY


clause by specifying a column as a grouping column.

GROUP BY is associated with an aggregate function.

To retrieve the average unit price


of all class of items available in the
item table.

SELECT Class, AVG(UnitPrice)


FROM Item
GROUP BY Class;

Column name can


come along with
aggregate
function only if it
appears in Group
by clause

SQL Group By

SELECT Class, AVG(UnitPrice)


FROM Item
GROUP BY Class;
Item
ItemId
STN001
BAK003
GRO001
ELC001
ELC004
STN002

ItemNam
e
UnitPrice
Pen
30
Bread
20
Poteto
10
Mobile
5000
iPod
600
Diary
200

Class
A
A
A
C
B
B

Class

AVG(UnitPrice)

A
B
C

20
400
5000

Supplier
Id
S1
S4
S3
S2
S2
S2

Retrieval using GROUP BY


Example:
Invalid SQL statement
SELECT Class, SupplierId, COUNT(ItemId)
FROM Item
GROUP BY Class;

Valid SQL Statement


SELECT Class, SupplierId, COUNT(ItemId)
FROM Item
GROUP BY Class, SupplierId;

SQL Group By
SELECT Class, SupplierId, COUNT(ItemId)
FROM Item GROUP BY Class, SupplierId;
Item
ItemId
STN001
BAK003
GRO001
ELC001
ELC004
STN002

ItemNam
Supplier
e
UnitPrice
Class
Id
Pen
30
A
S1
Bread
20
A
S4
Poteto
10
A
S3
Mobile
5000
C
S2
iPod
600
B
S2
Diary
200
B
S2
Class
SupplierId Count(ItemId)
A
S1
1
A
S3
1
A
S4
1
B
S2
2
C
S2
1

Retrieval using HAVING

List all the classes of item whose average unit price is


greater than 500

SELECT Class, AVG( UnitPrice)


FROM Item
GROUP BY Class HAVING AVG(UnitPrice) >
400;

Retrieval using HAVING


SELECT Class, AVG( UnitPrice) FROM Item
GROUP BY Class HAVING AVG(UnitPrice) >= 400;
Item
ItemId ItemName UnitPrice
STN001
Pen
30
BAK003
Bread
20
GRO001
Poteto
10
ELC001
Mobile
5000
ELC004
iPod
600
STN002
Diary
200
After Grouping
Class
A
B
C

AVG(UnitPri
ce)
20
400
5000

After
Having

Class
A
A
A
C
B
B

SupplierI
d
S1
S4
S3
S2
S2
S2

Class
B
C

AVG(UnitPr
ice)
400
5000

JOINS
Cartesian Product
Self join
Inner join
Equi join
Outer join

Left-outer join
Right-outer join

JOINS
JOIN
INNER
THET
EQUI
A

OUTER

SELF
NATUR
AL

LEFT

RIGH
T

FUL
L

Cartesian Product Or Cross Join

Returns All rows from first table, Each row


from the first table is combined with all
rows from the second table
SELECT

FROM Table1,Table2;

Self join-Joining a table


with itself

o list all the Employees along with their Managers


SELECT
Emp.Employee_ID
as
Employee ID,
Emp.Employee_Last_Name
as Employee Last
Name,
Emp.Manager_Id
as Manager ID,
Manager.Employee_Last_Name as
Manager
Last Name,
FROM employee_Manager Emp,
employee_Manager Manager WHERE
Emp.Manager_ID = Manager.Employee_ID;

Self Join (Contd)

Inner Joins

Common type of join

An inner join between two (or more) tables is


the Cartesian product that satisfies the
join condition in the WHERE clause

Retrieval from Multiple tables-Equi join

Get all combinations of Emp and Cust information such that the
Emp and Cust are co-located.
SELECT Table1.Emp_ID, Table1.City, Table2.Cust_ID,
Table2.City
FROM Table1, Table2
WHERE Table1.City = Table2.City;

Retrieval from Multiple tables- Equi join

Display the Employee number, Employee name and


department name of the employees who are working
for some department.

SELECT EmpNo, EName,DName


FROM Emp E, Dept D
WHERE E.DeptNo = D.DeptNo;

Retrieval from Multiple tables- Equi join

Display the details of the customers who have


purchased items
SELECT a.CustomerId,a.CustomerName
FROM Customer a, CustomerPurchase b
WHERE a.CustomerId = b.CustomerId;
Display the details of suppliers whose delivery status is
Not Delivered.

SELECT s.SupplierId,s.SupplierName
FROM Supplier s, ItemOrder io
WHERE s.SupplierId = io.SupplierId AND
io.DeleviryStatus=Not Delivered;

Retrieval from Multiple tables- Equi join

Display the details of Supplier who has delivered more than one item

SELECT s.SupplierId,s.SupplierName
FROM Supplier s, ItemOrder io
WHERE s.SupplierId = io.SupplierId
Group By s.SupplierId,s.SupplierName
having count(*)>1;

Retrieval from Multiple tables- Equi join

Display the name of the item, name of the supplier, and quantity supplied
if the supplier has supplied that item.

SELECT i.ItemId,s.SupplierId,io.QtyOfOrder
FROM Item i, Supplier s, ItemOrder io
WHERE s.SupplierId = io.SupplierId
AND i.ItemId=io.ItemId;

Retrieval from Multiple tables- Equi join

Display the id and name of the customer and the total amount of
purchasing done so far from the retail shop.

SELECT c.CustomerId,c.CustomerName,Sum(cp.NetPrice)
FROM Customer c, CustomerPurchase cp
WHERE c.CustomerId=cp.CustomerId
Group by
c.CustomerId,c.CustomerName;

Retrieval from Multiple tables- Equi join

Display the id and name of the customer and the total amount of
purchasing done along with bill id.
Note: A customer may have paid several bills

SELECT
c.CustomerId,c.CustomerName,cp.BillId,Sum(cp.NetPri
ce)
FROM Customer c, CustomerPurchase cp
WHERE c.CustomerId=cp.CustomerId
Group by c.CustomerId, c.CustomerName, cp.BillId;

Retrieval from Multiple tables- Equi join

Display the id and name of the customer along with


the bill id and bill date if the total amount of the bill
is more than 1000;
SELECT c.CustomerId,c.CustomerName,
b.BillId,b.BillDate,Sum(cp.NetPrice)
FROM Customer c, CustomerPurchase cp,Bill b
WHERE c.CustomerId=cp.CustomerId AND
cp.BillId=b.billId
Group by c.CustomerId, c.CustomerName,
b.BillId,b.BillDate
HAVING Sum(cp.NetPrice)>1000;

Outer join

Retrieve all rows that match the WHERE


clause and also those that have a NULL
value in the column used for join.

Left / Right-Outer join

Left outer joins include all records from the


first (left) of two tables,
A = B (+)

Right outer joins include all records from


the second (right) of two tables,
A (+) = B

Example of left-join
List all cities of Table1 if there is match in cities in Table2 & also
unmatched Cities from Table1
SELECT Table1.Emp_ID, Table1.City, Table2.Cust_ID, Table2.City
FROM Table1, Table2
WHERE Table1.City = Table2.City (+);

Example of Left Outer Join


List all customer details and loan details if they have availed loans.

SELECT
Customer_details.Cust_id,Cust_Last_name,Loan_no,
Amount_in_dollars
FROM Customer_Account_details,Customer_loan
WHERE
Customer_Account_details.Cust_id =
Customer_loan.Cust_id (+);

Example of right outer join


SELECT Table1.Emp_ID, Table1.City, Table2.Cust_ID, Table2.City
FROM Table1, Table2
WHERE Table1.City (+) = Table2.City;

Summary
The need of join operations between tables in
the database.
The different types of JOIN operations.
Applying Self Join, Inner join, and Outer Join.

What is a view?

A view is a kind of
virtual table

Contents are defined by


a query like:
Select Empno, Name,
age from Employee
Where
designation=developer
;
As shown in the figure

What is a view to the DBMS

We can use views


in select
statements like
Select * from
view_employees
where age > 23;
DBMS translates
the request to an
equivalent request
to the source table

Create a view

CREATE VIEW ViewCustomerDetails


AS SELECT *
FROM Customer_Details;

Assigning names to columns

CREATE VIEW vwCustDetails


(CustCode,CustLname,CustFName)
AS SELECT
Cust_Id,Cust_Last_Name,Cust_First_Name
FROM Customer_details;

Types of views
Horizontal views
Vertical views
Row/column subset views
Grouped views
Joined views

Horizontal views
Horizontal view restricts a users access
to only selected rows of a table.

Vertical views
A view which selects only few columns of a
table:
Vertical view restricts a users access to
only certain columns of a table.

Row/column subset views

CREATE VIEW View_Cust_VertHor


AS SELECT Cust_Id,Account_No,Account_Type
FROM Customer_Details
WHERE CUST_ID IN (101,102,103);

Views with Group By clause

The query contains a group by clause

CREATE VIEW View_GroupBY(Dept,NoofEmp)


AS SELECT Department, COUNT(Employee_ID)
FROM Employee_Manager
GROUP BY Department;

Views with Joins

Created by specifying a two-table or threetable query in the view creation command

CREATE VIEW View_Cust_Join


AS SELECT
a.Cust_Id,b.Cust_First_Name,b.Cust_Last_Name,
Amount_in_dollars
FROM Customer_loan a, customer_details b
WHERE a.cust_id = b.cust_id;

Updating a VIEW
CREATE VIEW View_Cust
AS SELECT *
FROM Customer_Details
WHERE CUST_ID IN (101,102,103);
--Insert Statement
INSERT INTO view_cust
VALUES (103,'Langer','G.','Justin',3421,'Savings', Global Commerce
Bank', 'Langer_Justin@Yahoo.com');
--Delete Statement
DELETE view_cust WHERE cust_id = 103;
--Update Statament
UPDATE view_cust
SET Cust_last_name = 'Smyth'
WHERE cust_id = 101;

Updating View
A view can be updated if the query that defines the view
meets all of these restrictions:

DISTINCT must not be specified; that is, duplicate rows must


not be eliminated from the query results.

The FROM clause must specify only one updateable table;


the view must have a single underlying source table.

The SELECT list cannot contain expressions, calculated


columns, or column functions.

The WHERE clause must not include a sub-query; only


simple row-by-row search conditions may appear.

Dropping Views
Views are dropped similar to the way in which the tables are
dropped. However, you must own a view in order to drop it.

DROP VIEW

<view name>;

DROP VIEW View_Cust;

Checking View Updates: Check Option

Will it prevent insertion into Customer_details ?

Checking View Updates: Check Option

Solution is :

Advantages of
views

Security

Query simplicity

Structural simplicity

Disadvantages of views

Performance

Restrictions

You might also like