sql overview , oracle data type , ddl and constraints · (ddl) load data (dml) tables in the...
TRANSCRIPT
LECTURE9-PART2:
DATA MANIPULATION IN SQL , ADVANCED
SQL QUERIES AND VIEW
11
Ref. Chapter5 and 6
Coll
ege
of
Com
pute
r an
d I
nfo
rmat
ion S
cien
ces
-In
form
atio
n S
yst
ems
Dep
t.
I S220 / IS 422 : Dat abase Fundam ent a l s
from
“Database Systems: A Practical Approach to Design, Implementation and Management.”
Thomas Connolly, Carolyn Begg.
The Process of Database Design22
Conceptual Design (ERD)
Logical Design
(Relational Model)
Physical Design
Create schema
(DDL)
Load Data
(DML)
Tables in the Examples
Customer(custNo, custName, custSt, custCity, age)
Product(prodNo, prodName, prodDes, price)
Orders(ordNo, ordDate, custNo, prodNo, quantity)
Where
custName, custSt, custCity, prodName, prodDes are strings
ordDate is date
Others are numbers
Lecture9
33
Sample Data in Customer Table
Lecture9
44
custNo custName custSt custCity age
1 C1 Olaya St Jeddah 20
2 C2 Mains St Riyadh 30
3 C3 Mains Rd Riyadh 25
4 C4 Mains Rd Dammam
5 C5 Mains Rd Riyadh
Sample Data in Product Table
Lecture9
55
prodNo prodName prodDes price
100 P0 Food 100
101 P1 healthy food 100
102 P2 200
103 P3 self_raising
flour,80%wheat
300
104 P4 network 80x 300
Sample Data in Orders Table
Lecture9
66
ordNo ordDate custNo prodNo quantity
1 01-jan-2003 1 100 2
2 02-jan-2003 1 101 1
3 01-jan-2003 2 102 1
4 01-jan-2003 3 100 2
5 03-jan-2003 1 101 1
6 06-mar-2003 2 100 10
Aggregate Functions
COUNT - returns the number of selected values
SUM - returns the sum of selected (numeric) values
AVG - returns the average of selected (numeric)
values
MIN - returns the minimum of selected values
MAX - returns the maximum of selected values
Lecture9
77
Use of COUNT(column_name)
The COUNT(column_name) function returns the
number of values (NULL values will not be
counted) of the specified column
Syntax
Lecture9
88
SELECT COUNT(column_name)
FROM table_name;
SELECT COUNT(column_name)
FROM table_name;
Use of COUNT(column_name)
Example 1: List the number of products in the product table
SELECT count(prodNo) FROM product;
Example 2: List the number of product descriptions in the product table
SELECT count(prodDes) FROM product;
Note: count(prodDes) does not count rows that have NULL value for prodDes.
Lecture9
99
COUNT(PRODNO)
-------------------------
5
COUNT(PRODDES)
------------------------
4
Use of COUNT(*)
The COUNT(*) function returns the number of
records in a table (NULL values will be counted)
Syntax
Lecture9
1010
SELECT COUNT(*)
FROM table_name;
SELECT COUNT(*)
FROM table_name;
Use of COUNT (*)
Example 1: How many products are there in the product table?
SELECT count(*) FROM product;
Example 2: How many products are priced at 300?
SELECT count(*)
FROM product
WHERE price =300;
Note: count(*) also count rows that have NULL values
Lecture9
1111
prod
No
prodNam
e
prodDes price
100 P0 Food 100
101 P1 healthy food 100
102 P2 200
103 P3 self_raising
flour,80%wh
eat
300
104 P4 network 80x 300
COUNT(*)
-------------------------
5
COUNT(*)
---------------
2
Use of COUNT(DISTINCT column_name)
The COUNT(DISTINCT column_name) function
returns the number of distinct values of the
specified column:
Syntax
Lecture9
1212
SELECT COUNT(DISTINCT column_name)
FROM table_name;
SELECT COUNT(DISTINCT column_name)
FROM table_name;
Use of COUNT(DISTINCT column_name)
Example1: How many cities are the customers
located in ?
SELECT count(distinct custCity) from customer;
Example 2: How many customers ordered products
since 01/01/2003?
SELECT count(distinct custNo)
FROM orders
WHERE ordDate >= '01-jan-2003';
Lecture9
1313
ordNo ordDate cust
No
prodNo quantit
y
1 01-jan-2003 1 100 2
2 02-jan-2003 1 101 1
3 01-jan-2003 2 102 1
4 01-jan-2003 3 100 2
5 03-jan-2003 1 101 1
6 06-mar-2003 2 100 10
COUNT(DISTINCT CUSTCITY)
-----------------------------------------
3
COUNT(DISTINCT CUSTNO)
------------------------------------
3
custNo custNam
e
custSt custCity age
1 C1 Olaya St Jeddah 20
2 C2 Mains St Riyadh 30
3 C3 Mains Rd Riyadh 25
4 C4 Mains Rd Dammam
5 C5 Mains Rd Riyadh
Use of SUM
The SUM() function returns the total sum of a
numeric column.
The MIN() function returns the smallest value of
the selected column.
The MAX() function returns the largest value of
the selected column.
The AVG() function returns the average value of
a numeric column.
Syntax
Lecture9
1414
SELECT
SUM(column_name),MIN(column_name),MAX(column_name),AVG(column_name)
FROM table_name;
SELECT
SUM(column_name),MIN(column_name),MAX(column_name),AVG(column_name)
FROM table_name;
Use of SUM Example
Example 1: How many products pieces were ordered by customer 1?
SELECT SUM(quantity)
FROM orders
WHERE custNo =1;
Example 2: How many orders were made by customer 1 and how many products pieces did he order?
SELECT count(ordNo), SUM(quantity)
FROM orders
WHERE custNo =1; Lecture9
1515
ordNo ordDate cust
No
prodNo quantit
y
1 01-jan-2003 1 100 2
2 02-jan-2003 1 101 1
3 01-jan-2003 2 102 1
4 01-jan-2003 3 100 2
5 03-jan-2003 1 101 1
6 06-mar-2003 2 100 10
SUM(QUANTITY)
-----------------------
4
COUNT(ORDNO) SUM(QUANTITY)
--------------------- ----------------------
3 4
Example Use of AVG, MIN and MAX
Example: list the minimum, maximum and average price
of all products.
SELECT MIN(price), MAX(price), AVG(price)
FROM product;
Note: if some product's price are NULLs, then SUM and
AVG do not take those products into consideration. Lecture9
1616
prodNo prodNam
e
prodDes price
100 P0 Food 100
101 P1 healthy food 100
102 P2 200
103 P3 self_raising
flour,80%wh
eat
300
104 P4 network 80x 300
MIN(PRICE) MAX(PRICE) AVG(PRICE)
---------------- ---------------- ----------------
100 300 200
Lecture91717
Advanced queries (GROUP BY)
General Syntax of SELECT command
SELECT [DISTINCT]
{* | [columnExpression, ……. }
FROM TableName
[WHERE condition]
[GROUP BY columnList]
[HAVING condition]
[ORDER BYcolumnList]
Order of the clauses cannot be changed.
Only SELECT and FROM are mandatory
Lecture9
1818
The GROUP BY Statement
The GROUP BY statement is used in conjunction with
the aggregate functions to group the result-set by
one or more columns.
Syntax
Lecture9
1919
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE condition
GROUP BY column_name;
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE condition
GROUP BY column_name;
Use of GROUP BY
Use GROUP BY clause to get sub-totals.
SELECT and GROUP BY closely integrated: each
item in SELECT list must be single-valued per group,
and SELECT clause may only contain:
Column names in the group by clause
Aggregate functions
Constants
Expression involving combinations of the above
If WHERE is used with GROUP BY, WHERE is
applied first, then groups are formed from rows
satisfying condition.Lecture9
2020
Example 1 ( use of group by )
Orders
find the total (total order) of each customer.
use the GROUP BY statement to group the
customers.SELECT Customer, SUM(OrderPrice)
FROM Orders
GROUP BY Customer;Lecture9
2121
O_Id OrderDate OrderPrice Customer
1 2008/11/12 1000 Nora
2 2008/10/23 1600 Sara
3 2008/09/02 700 Nora
4 2008/09/03 300 Nora
5 2008/08/30 2000 Yara
6 2008/10/04 100 Sara
Nora
Sara
Yara
Example 1
The result ( output ):
what happens if we omit the GROUP BY statement
SELECT Customer,SUM(OrderPrice) FROM
Orders;
The result
Lecture9
2222
Customer SUM(OrderPrice)
Nora 2000
Sara 1700
Yara 2000
Customer SUM(OrderPrice)
Nora 5700
Sara 5700
Nora 5700
Nora 5700
Yara 5700
Sara 5700
Example 2
List the quantity of each product ordered during
Jan 2003.
SELECT prodNo, sum(quantity)
FROM orders
WHERE ordDate>='01-jan-2003' AND
ordDate<'01-Feb-2003'
GROUP BY prodNo;
Lecture9
2323
ordNo ordDate custNo prodNo quantity
1 01-jan-2003 1 100 2
2 02-jan-2003 1 101 1
3 01-jan-2003 2 102 1
4 01-jan-2003 3 100 2
5 03-jan-2003 1 101 1
6 06-mar-2003 2 100 10
PRODNO SUM(QUANTITY)
-------------- --------------------
100 4
102 1
101 2
Example 3
return the minimum and maximum salaries for each
department in the employees table
SELECT deptNumber, MIN(salary), MAX (salary)
FROM employees
GROUP BY deptNumber
ORDER BY deptNumber;
Lecture9
2424
Employee No. First Name Last Name Dept Number Salary
E1 Mandy Smith D1 50000
E2 Daniel Hodges D2 45000
E3 Shaskia Ramanthan D2 58000
E4 Graham Burke D1 44000
E5 Annie Nguyen D1 60000D1
D2
DEPTNUMBER MIN(SALARY) MAX(SALARY)
--------------------- ------------------ -------------------
D1 44000 60000
D2 45000 58000
SELECT count(*)
FROM EMPLOYEE;
Example 1 : no grouping
Employee No. First Name Last Name Dept Number Salary
E1 Mandy Smith D1 50000
E2 Daniel Hodges D2 45000
E3 Shaskia Ramanthan D2 58000
E4 Graham Burke D1 44000
E5 Annie Nguyen D1 60000
Without group by COUNT(*) returns the number of rows in the table
COUNT(*)
-------------
5
Example 4Grouping Output from Queries
Lecture9
2525
DEPTNUMBER COUNT(*)
---------------- -------------
D1 3
D2 2
Employee No. First Name Last Name Dept Number Salary
E1 Mandy Smith D1 50000
E4 Graham Burke D1 44000
E5 Annie Nguyen D1 60000
E2 Daniel Hodges D2 45000
E3 Shaskia Ramanthan D2 58000
Example 2 : group by
SELECT deptNumber, count(*)
FROM EMPLOYEE
GROUP BY deptNumber
ORDER BY deptNumber;
Grouping Output from Queries
Lecture9
2626
Use of HAVING
HAVING clause is designed for use with GROUP BY to restrict
groups that appear in final result table.
Similar to WHERE, but WHERE filters individual rows whereas
HAVING filters groups.
Column names in HAVING clause must also appear in the
GROUP BY list or be contained within an aggregate function.
SYNTAX
Lecture9
2727
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value
;
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value
;
EXAMPLE 1
find if any of the customers have a total order of less
than 2000
SELECT Customer,SUM(OrderPrice)
FROM Orders
GROUP BY Customer
HAVING SUM(OrderPrice)<2000;
- Without Having
Lecture9
2828
O_Id OrderDate OrderPrice Customer
1 2008/11/12 1000 Nora
2 2008/10/23 1600 Sara
3 2008/09/02 700 Nora
4 2008/09/03 300 Nora
5 2008/08/30 2000 Yara
6 2008/10/04 100 Sara
CUSTOMER SUM(ORDERPRICE)
----------------- -------------------------
SARA 1700CUSTOMER SUM(ORDERPRICE)
----------------- -------------------------
NORA 2000
SARA 1700
YARA 2000
Example 2
find if the customers “Nora" or “Yara" have a total
order of more than 1500
SELECT Customer,SUM(OrderPrice)
FROM Orders
WHERE Customer=‘Nora' OR Customer=‘Yara'
GROUP BY Customer
HAVING SUM(OrderPrice)>1500 ;
Lecture9
2929
O_Id OrderDate OrderPrice Customer
1 2008/11/12 1000 Nora
2 2008/10/23 1600 Sara
3 2008/09/02 700 Nora
4 2008/09/03 300 Nora
5 2008/08/30 2000 Yara
6 2008/10/04 100 Sara
CUSTOMER SUM(ORDERPRICE)
----------------- -------------------------
NORA 2000
YARA 2000
Example 3
List the product number and the quantity ordered for each
product which has a total quantity of more than 2 during Jan
2003.
SELECT prodNo, sum(quantity)
FROM orders
WHERE ordDate>='01-jan-2003' AND ordDate<'01-Feb-2003'
GROUP BY prodNo
HAVING sum(quantity)>2;
Lecture9
3030
ordNo ordDate custNo prodNo quantity
1 01-jan-2003 1 100 2
2 02-jan-2003 1 101 1
3 01-jan-2003 2 102 1
4 01-jan-2003 3 100 2
5 03-jan-2003 1 101 1
6 06-mar-2003 2 100 10
100= 4
101=2
102 = 1
PRODNO SUM(QUANTITY)
------------- ----------------------
100 4
Example 4
List the department number and the total number of employee in that
department for each department that has more than two employees
SELECT deptNumber, count(*)
FROM EMPLOYEE
GROUP BY deptNumber
HAVING count(*)>2
ORDER BY deptNumber;
Lect
ure9
3131DEPTNUMBER COUNT(*)
---------------- --------------
D1 3
DEPTNUMBER COUNT(*)
---------------- -------------
D1 3
D2 2
Employee No. First Name Last Name Dept Number Salary
E1 Mandy Smith D1 50000
E4 Graham Burke D1 44000
E5 Annie Nguyen D1 60000
E2 Daniel Hodges D2 45000
E3 Shaskia Ramanthan D2 58000
Lecture9
3232
Lecture93333
Views
Dynamic result of one or more relational operations operating on base relations to produce another relation.
Virtual relation that does not necessarily actually exist in the database but is produced upon request, at time of request.
Contents of a view are defined as a query on one or more base relations.
With view resolution, any operations on view are automatically translated into operations on relations from which it is derived.
With view materialization, the view is stored as a temporary table,
which is maintained as the underlying base tables are updated.
3434
Pearson Education © 2009
SQL - CREATE VIEW
Syntax:
Can assign a name to each column in view.
If list of column names is specified, it must have same number of items as number of columns produced by subselect.
If omitted, each column takes name of corresponding column in subselect.
List must be specified if there is any ambiguity in a column name.
The subselect is known as the defining query.
WITH CHECK OPTION ensures that if a row fails to satisfy WHERE clause of defining query, it is not added to underlying base table.
3535
Pearson Education © 2009
CREATE VIEW ViewName [ (newColumnName [,...]) ]AS subselect
[WITH [CASCADED | LOCAL] CHECK OPTION]
CREATE VIEW ViewName [ (newColumnName [,...]) ]AS subselect
[WITH [CASCADED | LOCAL] CHECK OPTION]
Example 7.3 - Create Horizontal View
Create view so that manager at branch B003 can only see
details for staff who work in his or her office.
CREATE VIEW Manager3Staff
AS SELECT *
FROM Staff
WHERE branchNo = ‘B003’;
3636
Pearson Education © 2009
Example 7.4 - Create Vertical View
Create view of staff details at branch B003 excluding salaries.
CREATE VIEW Staff3
AS SELECT staffNo, fName, lName, position, sex
FROM Staff
WHERE branchNo = ‘B003’;
3737
Pearson Education © 2009
SQL - DROP VIEW
Syntax:
With CASCADE, all related dependent objects are deleted; i.e. any views defined on view being dropped.
With RESTRICT (default), if any other objects depend for their existence on continued existence of view being dropped, command is rejected.
For example:
DROP VIEW Manager3Staff;
3838
Pearson Education © 2009
DROP VIEW ViewName [RESTRICT | CASCADE]DROP VIEW ViewName [RESTRICT | CASCADE]
View Updatability
All updates to base table reflected in all views that
encompass base table.
Similarly, may expect that if view is updated then
base table(s) will reflect change.
3939
Pearson Education © 2009
View Updatability
ISO specifies that a view is updatable if and only if:
- DISTINCT is not specified.
- Every element in SELECT list of defining query is acolumn name and no column appears more thanonce.
- FROM clause specifies only one table, excludingany views based on a join, union, intersection ordifference.
- No nested SELECT referencing outer table.
- No GROUP BY or HAVING clause.
- Also, every row added through view must notviolate integrity constraints of base table.
4040
Pearson Education © 2009
WITH CHECK OPTION
Rows exist in a view because they satisfy WHEREcondition of defining query.
If a row changes and no longer satisfies condition, itdisappears from the view.
New rows appear within view when insert/updateon view cause them to satisfy WHERE condition.
Rows that enter or leave a view are calledmigrating rows.
WITH CHECK OPTION prohibits a row migrating out of the view.
4141
Pearson Education © 2009
WITH CHECK OPTION
LOCAL/CASCADED apply to view hierarchies.
With LOCAL, any row insert/update on view and any view directly or indirectly defined on this view must not cause row to disappear from view unless row also disappears from derived view/table.
With CASCADED (default), any row insert/ update on this view and on any view directly or indirectly defined on this view must not cause row to disappear from the view.
4242
Pearson Education © 2009
Example 7.6 - WITH CHECK OPTION
CREATE VIEW Manager3Staff
AS SELECT *
FROM Staff
WHERE branchNo = ‘B003’
WITH CHECK OPTION;
Cannot update branch number of row B003 to B002as this would cause row to migrate from view.
Also cannot insert a row into view with a branchnumber that does not equal B003.
4343
Pearson Education © 2009
Example 7.6 - WITH CHECK OPTION
Now consider the following:
CREATE VIEW LowSalaryAS SELECT * FROM Staff WHERE salary > 9000;
CREATE VIEW HighSalaryAS SELECT * FROM LowSalary
WHERE salary > 10000
WITH LOCAL CHECK OPTION;
CREATE VIEW Manager3StaffAS SELECT * FROM HighSalary
WHERE branchNo = ‘B003’;
4444
Pearson Education © 2009
Example 7.6 - WITH CHECK OPTION
UPDATE Manager3Staff
SET salary = 9500
WHERE staffNo = ‘SG37’;
This update would fail: although update would cause row todisappear from HighSalary, row would not disappear fromLowSalary.
However, if update tried to set salary to 8000, update wouldsucceed as row would no longer be part of LowSalary.
If HighSalary had specified WITH CASCADED CHECK OPTION,setting salary to 9500 or 8000 would be rejected because rowwould disappear from HighSalary.
To prevent anomalies like this, each view should be created usingWITH CASCADED CHECK OPTION.
4545
Pearson Education © 2009