if301 week10 sql

53
1 IF-301 SISTEM BASIS DATA Kuliah 10 Structured Query Language Institut Teknologi Harapan Bangsa

Upload: wan-sang-ajie

Post on 07-Apr-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 1/53

1

IF-301

SISTEM BASIS DATA

Kuliah 10

Structured Query Language

Institut Teknologi Harapan Bangsa

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 2/53

2

SQL - Structured Query Language

Originally designed and implemented by IBM research as theinterface

to a relational database. It is used by Oracle for all interactionwith the database.

 ANSI Standard SQL-92 defines three levels of compliance, Entry,Intermediate, and Full. Oracle conforms to Entry levelcompliance, and has many features that conform toIntermediate or Full level compliance. SQL-99 extended SQL-92(Core SQL-99) to a newer object relational form.

 A declarative language.The DBMS performs retrieval. A choice of access routines is made

to optimize the query.

SQL specifies syntax features for retrieval update and definition of the database.

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 3/53

3

Structured Query Language Bahasa merupakan bahasa query deklaratif 

yang mengindikasikan properti-properti daridata yang hendak diambil.

Bahasa yang terstruktur yang digunakandalam mengelola suatu sistem database:

- Data Definition Language (DDL):bahasa khusus untuk menspesifikasikan

 “database scheme” dengan sekumpulandefinisi-definisi tertentu dalam file khususyang disebut: data dictionary (directory)yang berisi “meta data”. Metadata adalah

 “data tentang data”  

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 4/53

4

Structured Query Language- Data Manipulation Language (DML):

bahasa yang digunakan untuk memanipulasi danmengakses data yang telah disusun berdasarkansuatu model data tertentu.

Manipulasi atau pengaksesan tersebut antara lainadalah:

- Mengambil informasi dari database (retrieval)

- Menambah informasi ke dalam database (insertion)- Mengurangi informasi dari database (deletion)

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 5/53

5

Data Definition (DDL)

CREATE TABLE define table

CREATE VIEW define user view of data

ALTER TABLE add new columns or modifyexisting columns

DROP TABLE delete table

DROP VIEW delete user view

Overview of SQL

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 6/53

6

Data Retrieval (DML)

SELECT retrieve data from table

Data Modification (DML)

INSERT add a single row or copy rows from other table(s)UPDATE amend column values

DELETE delete rows of data

Overview of SQL

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 7/53

7

Data Control

COMMIT commit changes to the database

ROLLBACK rollback previous changes

Data Security

GRANT grant access privileges to users

REVOKE revoke access privileges

Overview of SQL

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 8/53

8

Creating TablesCREATE TABLE EMP

(EMPNO CHAR(6), NAME CHAR(20), SALARY NUMBER(8,0),AGE NUMBER(3,0), DEPTNO CHAR(2));

A table is defined.Space is reserved.

The system catalogue is updated.Table and Column Names begin with alpha (A-Z) less than or equal to30 characters

Table names and Column names contain (A-Z,0-9,$,#, __)

Data Definition (DDL): Create Table

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 9/53

9

This example modifies the BAL column of the ACCOUNTS table

so that it has a default value of 0:

ALTER TABLE accounts

MODIFY (bal DEFAULT 0)

If you subsequently add a new row to the ACCOUNTS table and

do not specify a value for the BAL column, the value of the BAL

column is automatically 0.The Alter command lets you add a column, add an integrity

constraint, redefine a column (datatype, size, default value),

enable, disable, or drop an integrity constraint or trigger.

Data Definition (DDL): Alter Table

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 10/53

10

- it is a mini-database that stores data that describes the application

data held in the database. It is sometimes referred to as the system

catalog and the data it stores is also called

METADATA (data about data)

An example of metadataEMPLOYEE table - Catalog Entries

Object Object Key Data Nulls

Name Type Type Type AllowedEMP# attribute PK Char(9)

EMP_AGE attribute Int Not Null

DEPT_NO attribute FK Char(9) Not Null

The Data Dictionary

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 11/53

11

Describe - base-tables

- attributes

- views

- domains

- primary-keys

- foreign-keys

- integrity constraints

- security information

The description of the above objects will include owner and

creation information and information concerning the above objects

that is of use to the DBMS.

System Catalogs for Relational Systems

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 12/53

12

Design

IEmethodology

Project ID &selection

Projectinitiation &

planning

TraditionalSDLC

LogicalDesign

PhysicalDesign

Implemen-tation

Maintenance

ISA

EDM

Methodologies  Database developmentprocess 

Conceptual datamodeling

(Conceptual schema)

Logical databasedesign

Physical databasedesign

Databaseimplementation

Databasemaintenance

CASE supportfor Databases 

   U

  p  p  e  r   C   A   S   E

   L  o  w  e  r   C   A   S   E

   I  n   t  e  g  r  a   t  e   d  -   C   A   S   E

   (   I  -   C   A   S   E   )

Zachmanframework  

DataProcess

Network PeopleEventsReasons

DataProcessNetwork PeopleEventsReasons

DataProcessNetwork PeopleEventsReasons

DataProcessNetwork PeopleEventsReasons

Enterprisemodeling

3-schemaarchitecturefor database 

   C  o  n  c  e  p   t  u  a   l

   (   L  o  g   i  c  a   l   )  s  c   h  e  m  a

   E  x   t  e  r  n  a   l

  s  c   h  e  m  a

   (  u  s  e  r  v   i  e  w   )

   P   h  y  s   i  c  a   l

  s  c   h  e  m  a

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 13/53

13

PNAME

NUT

BOLT

CARAVAN

PARTNO

P1

P2

P3

PRICE

$0.20

$1.00

$5000.00

QOH

20

40

3

PART

SELECT pname, price*qoh AS pvalue

FROM PART

WHERE price > 0.20 AND price * qoh > 30.0ORDER BY pname desc;

pname

CARAVAN

BOLT

pvalue

$15,000.00

$40.00

Example of a Simple SELECT

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 14/53

14

Further Examples of SELECT

SELECT * FROM PART;

Selects all column values for all rows

SELECT PARTNO, PNAME FROM PART WHERE PRICE BETWEEN 0.2 AND 1.0;

Selects rows where price ge .2 and le 1.0

SELECT PARTNO, PNAME FROM PART

WHERE PNAME IN ('NUT','BOLT');

Selects rows where pname has a value in the following list

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 15/53

15

SQL SELECT Statement

SELECT [ALL|DISTINCT]

expression[AS result_column]

{,expression[AS result_column]}

FROM tablename[t_alias] {,tablename[t_alias]}

[WHERE search_condition]

[GROUP BY colname {,colname}]

[HAVING search_condition]

Nb: This is the syntax of a subselect 

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 16/53

16

The full syntax is then:

subselect

{UNION [ALL] subselect} [ORDER BY colname[ASC|DESC]

{,colname [ASC|DESC] } ]

Nb: that the search condition in a subselect

may be a subselect

a emen

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 17/53

17

SQL - Sample DB Schema

PM_NAME BIRTH_YR YRS_SERVED DEATH_AGE STATE_BORN STATE_REP

PRIME _MINISTER

MARRIAGE

PM_NAME SPOUSE_NAME MAR_YR PM_AGE NR_CHILDREN

MINISTRYMIN_NR PM_NAME PARTY DAY_COMM MTH_COMM YR_COMM

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 18/53

18

Expressions in SELECT

 Arithmetic operators are + - ** * /

Comparison operators are = != <> ^= > < >=<=

Logical operators are AND OR NOT Parentheses may be used to alter order of evaluation -

unary, **, * /, + -

Wildcard % = any string of zero or more character

_ = any one character

[ ] = any of the characters enclosed inbrackets

 A range of numeric, string, date and other functions are

available.

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 19/53

19

Arithmetic Operators in a SELECT

List the name, birth year and year of death of each prime minister who

was born in New South Wales. List in order of birth year.

SELECT PM_NAME, BIRTH_YR, BIRTH_YR + DEATH_AGE

FROM PRIME_MINISTER

WHERE STATE_BORN = „NSW‟ 

ORDER BY BIRTH_YR

PM_NAME BIRTH_YR BIRTH_YR + DEATH_AGE

Barton E 1849 1920Page E C G 1880 1961

Chifley J 1885 1951

Holt H E 1908 1967

McMahon W 1908 ?

Whitlam E G 1916 ?

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 20/53

20

Using the Logical Operators

Which prime ministers were born in Victoria before the turn of the

century?

SELECT PM_NAME, BIRTH_YR, STATE_BORN

FROM PRIME_MINISTER

WHERE STATE_BORN=‘VIC’ AND BIRTH_YR < 1900 

PM_NAME BIRTH_YR STATE_BORN

Deakin A 1856 VIC

Bruce S M 1883 VIC

Scullin J H 1876 VIC

Menzies R G 1894 VIC

Curtin J 1885 VIC

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 21/53

21

Combining Logical Operators

Which prime ministers were born in NSW and then represented

Victoria or have simply not served less than two years?

SELECT PM_NAME, STATE_BORN, STATE_REP, YRS_SERVED

FROM PRIME _MINISTERWHERE STATE_REP = ‘VIC’ 

AND STATE_BORN = ‘NSW’ 

OR NOT YRS_SERVED < 2

PM_NAME STATE_BORN STATE_REP YRS_SERVED

Holt H E NSW VIC 1.88

Gorton J G VIC VIC 3.17

Whitlam E G NSW NSW 2.92

Fraser J M VIC VIC 7.33

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 22/53

22

Further Examples of SELECT

SELECT PNAME FROM PART

WHERE QOH IS NULL;

Selects those rows where qoh has a null

value

SELECT * FROM PART

WHERE PNAME LIKE '_ _T' or PNAME LIKE

'%LT';

Selects rows where pname has three lettersthe last of which is a T or PNAME ends in LT

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 23/53

23

Use of COUNT with DISTINCT

How many liberal prime ministers were commisioned between 1970

and 1980?

SELECT ‘Liberal PMs’, COUNT(*), COUNT(DISTINCT PM_NAME) 

FROM MINISTRY

WHERE PARTY = ‘Liberal’ 

AND YR_COMM BETWEEN 1970 AND 1980

COUNT(*) COUNT(DISTINCT PM_NAME)Liberal PMs 5 2

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 24/53

24

UNION

PNAME

NUT

BOLT

CARAVAN

PARTNO

P1

P2

P3

PRICE

$0.20

$1.00

$5000.00

QOH

21

40

3

PART

SELECT pname, 'q1' AS Query FROM PARTWHERE QOH < 22

UNION SELECT pname, 'q2' AS Query FROM PART

WHERE QOH > 20;NUT

CARAVAN

NUT

BOLT

q1

q1

q2

q2

pname Query

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 25/53

25

DELETE FROM tablename[t_alias]

[ WHERE search-condition ]

Delete one or many rows ina table.

DELETE

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 26/53

26

UPDATE

UPDATE tablename [t_alias]

SET colname = expression { ,

colname = expression} [ WHERE search_condition ]

Replaces values of the specified columns

with expression values for all rowssatisfying the search-condition.

Expressions in the set clause may be

constants, column values or subqueries.

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 27/53

27

Set Functions in SELECT

PNAME

NUT

BOLT

CARAVAN

PARTNO

P1

P2

P3

PRICE

$1.00

$1.00

$5000.00

QOH

20

20

3

PART

Part_count

3

Av_price

$1667.33

Set functions supported = avg count max min sum

Set functions may not be used directly in a search condition

Price_count

2

SELECT count(partno) AS Part_count, avg(price) AS Av_price,

count(distinct price) AS Price_count

FROM part

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 28/53

28

Use of GROUP BY

List the number of prime ministers from each party.

SELECT PARTY, COUNT(*)

FROM MINISTRY

GROUP BY PARTY

PARTY COUNT(*)

Country 3

Free Trade 1

Labor 15Liberal 17

National Labor 1

Nationalist 3

Proctectionist 4

United Australia 5

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 29/53

29

Grouping by More Than One Column

Group prime ministers by their state born and the state they represented.Give the number of prime ministers and the total of years served.

SELECT STATE_BORN, STATE_REP, COUNT(*),

SUM(YRS_SERVED)

FROM PRIME_MINISTER

GROUP BY STATE_BORN, STATE_REPSTATE_BORN STATE_REP COUNT(*) SUM(YRS_SERVED)

? NSW 4 9.67

? QLD 1 4.81NSW NSW 5 11.83

NSW VIC 1 1.88

QLD QLD 2 0.13

TAS TAS 1 7.25

VIC VIC 7 42.69

VIC WA 1 3.75

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 30/53

30

Grouping With the WHERE Clause

For prime ministers born after 1900, list the number of prime ministers

born in each state and the total number of years served.

SELECT STATE_BORN, COUNT(*), SUM(YRS_SERVED)

FROM PRIME_MINISTERWHERE BIRTH_YR > 1900

GROUP BY STATE_BORN

STATE_BORN COUNT(*) SUM(YRS_SERVED)WA 1 ?

VIC 2 10.50

NSW 3 6.52

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 31/53

31

Grouping With the HAVING Clause

For each state where the total years served by prime ministers born inthat state is less than 10 years, give the number of prime ministers

born in that state and the total number of years served.

SELECT STATE_BORN, COUNT(*), SUM(YRS_SERVED)FROM PRIME_MINISTER

GROUP BY STATE_BORN

HAVING SUM(YRS_SERVED) < 10

STATE_BORN COUNT(*) SUM(YRS_SERVED)

TAS 1 7.25

QLD 2 0.13

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 32/53

32

SELECTpartno,Count(suppno) ASSupp_count,Sum(qty_supp) AS Total_qty

FROM art su lier

PARTNO

P1

SUPP_COUNT

2

TOTAL_QTY

40

PARTNO

P1

P2

P1P3

SUPPNO

S1

S1

S2S2

QTY_SUPP

20

30

2010

PART_SUPPLIER

Grouping With the HAVING Clause

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 33/53

33

Subqueries

Give the name and death age for each prime minister who diedat an age less than the average death age of prime ministers.List in ascending order of death age.

SELECT PM_NAME, DEATH_AGEFROM PRIME_MINISTER

WHERE DEATH_AGE < (SELECT AVG(DEATH_AGE)

FROM PRIME_MINISTER)

ORDER BY DEATH AGE

PM_NAME DEATH_AGEHolt H E 59Lyons J A 60Curtin J 60Deakin A 63

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 34/53

34

Subqueries

Which prime minister died the oldest? Give his name and thatage.

SELECT PM_NAME, DEATH_AGE

FROM PRIME_MINISTERWHERE DEATH_AGE = (SELECT MAX(DEATH_AGE)

FROM PRIME_MINISTER)

PM_NAME DEATH_AGEForde F M 93

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 35/53

35

Subquery With IN Operator

SELECT DISTINCT DEPUTY_NAME, PARTY

FROM DEPUTY_PM

WHERE DEPUTY_NAME IN (SELECT PM_NAME

FROM PRIME_MINISTER)

DEPUTY_NAME PARTY

Chifley J B LaborCook J Free Trade

Deakin A Protectionist

List the name and party of each deputy prime minister who wasalso prime minister.

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 36/53

36

The ANY Operator

PARTNO

P1

P2

P1P3

SUPPNO

S1

S1

S2S2

QTY_SUPP

20

30

2510

PART_SUPPLIER

SELECT partno, suppno, qty_suppFROM Part_supplier

WHERE qty_supp > ANY 

(SELECT avg(qty_supp) FROM

Part-supplier)

PARTNO

P2

P1

SUPPNO

S1

S2

QTY_SUPP

30

25

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 37/53

37

Multiple Nested Subqueries

Give the name and birth year of each prime minister who wascommisioned after Bob Hawke had turned 21. Order by birth year.

SELECT PM_NAME, BIRTH_YR

FROM PRIME_MINISTER

WHERE PM_NAME = ANY(SELECT PM_NAME

FROM MINISTRY

WHERE YR_COMM >

(SELECT BIRTH_YR + 21FROM PRIME_MINISTER

WHERE PM_NAME = „Hawke R J L‟)) 

AND PM_NAME <> „Hawke R J L‟ 

ORDER BY BIRTH_YR

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 38/53

38

Subqueries

SELECT partno, suppno, qty_supp FROMPart_supplier

WHERE qty_supp > ANY 

(SELECT avg(qty_supp) FROMPart-supplier)

Subqueries may be used in a number of 

SQL statements. select, update, insert, delete, create

table,

create view, create permit, create

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 39/53

39

Correlated Subqueries

PARTNO

P1

P2

P1

P2P3

SUPPNO

S1

S1

S2

S2S2

QTY_SUPP

20

30

25

2010

PART_SUPPLIER

SELECT partno, suppno, qty_suppFROM Part_supplier PS1

WHERE qty_supp > ANY 

(SELECT avg(qty_supp) FROMPart-supplier PS2

=

PARTNO

P1

P2

SUPPNO

S2

S1

QTY_SUPP

25

30

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 40/53

40

Correlated Subqueries

SELECT partno, suppno, qty_supp FROM

Part_supplier PS1 WHERE qty_supp > ANY 

(SELECT avg(qty_supp) FROM

Part-supplier PS2 WHERE PS2.partno =

PS1.partno)

· Subselects (inner queries) are generally

Which suppliers are supplying more than the average for a

part and how much of that part do they supply?

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 41/53

41

Joining

TablesEMPNO

E1

E2

E3

ENAME

RED

BLUE

BROWN

MGRNO

E1

E1

E1

DEPTNO

D1

D1

D2

DEPTNO

D1

D2

D3

DNAME

TAX

PAY

LEAVE

EMP DEP

SELECT e.empno AS Number,

e.ename AS Name,d.dname AS Department

FROM emp e, dep d

WHERE e.deptno = d.deptno

Number

E1

E2

E3

Name

RED

BLUE

BROWN

Department

TAX

TAX

PAY

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 42/53

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 43/53

43

Multiple Joins

Give the name, birth year, party and the year of marriage of prime

ministers born in or after 1900.

SELECT DISTINCT P.PM_NAME, BIRTH_YR, MAR_YR, PARTY

FROM PRIME_MINISTER P,PM_MARRIAGE W,MINISTRY MWHERE P.PM_NAME = W.PM_NAME

AND P.PM_NAME = M.PM_NAME

AND BIRTH_YR >= 1900PM_NAME BIRTH_YR MAR_YR PARTY

Fraser J M 1930 1956 LiberalGorton J G 1911 1935 Liberal

Hawke R J L 1929 1956 Labor

Holt H E 1908 1946 Liberal

McEwen J 1900 1921 Country

McEwen J 1900 1968 Country

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 44/53

44

EMPNO

E1

E2

E3

ENAME

RED

BLUE

BROWN

MGRNO

E1

E1

E1

DEPTNO

D1

D1

D2

EMP

SELECT X.empno AS Number, X.ename AS Name, Y.ename ASManager

FROM emp X, emp Y 

WHERE X.mgrno = Y.empnoNumber

E1

E2

E3

Name

RED

BLUE

BROWN

Manager

RED

RED

RED

Joining a Table To Itself 

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 45/53

45

The EXISTS Operator

List the name, birth year and state represented of prime ministers who

were also deputy prime ministers.

SELECT PM_NAME, BIRTH_YR, STATE_REP

FROM PRIME_MINISTERWHERE EXISTS (SELECT *

FROM DEPUTY_PM

WHERE DEPUTY_NAME = PM_NAME)

 Nb: The subquery always uses “SELECT *” and here the correlation column is PM_NAME. The condition is satisfied if at least one row

exists. PM_NAME BIRTH_YR STATE_REP

Deakin A 1856 VIC

Cook J 1860 NSW

Hughes W M 1862 NSW

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 46/53

46

The NOT EXISTS Operator

Give the name, state represented and death age of each prime ministerwho has no recreations.

SELECT PM_NAME, BIRTH_YR, DEATH_AGE

FROM PRIME_MINISTER PWHERE NOT EXISTS (SELECT *

FROM PM_RECREATION

WHERE PM_NAME = P.PM_NAME)

Nb: The subquery returns rows from PM_RECREATION and here thecorrelation column is PM_NAME. The condition is satisfied if no row

exists. PM_NAME STATE_REP DEATH_AGE

Reid G H NSW 73

Fisher A QLD 66

Cook J NSW 87

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 47/53

47

- Virtual tables because they look and behave like a base table - but

contain no data

Views act as a window through which you cansee data that is stored in one or many base

tables

Consider a base table EMP

EMPNO ENAME JOB DEPTNO

7369 SMITH MANAGER 207568 JONES ANALYST 20

7788 SCOTT CLERK 20

7469 ALLEN ANALYST 30

7521 WARD SALESMAN 30

Views or Virtual Tables

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 48/53

48

CREATE VIEW EMP20 AS

SELECT EMPNO,ENAME,JOB

FROM EMP

WHERE DEPTNO = 20;

VIEW EMP20EMPNO ENAME JOB

7369 SMITH MANAGER

7568 JONES ANALYST

7788 SCOTT CLERK

EMP20 data is stored in the EMP base table

Columns used in views inherit the data type and domain of the base

table attributes

An SQL View Statement

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 49/53

49

Emp (empno,empname,

salary_pa, deptno) Dept (deptno, dname)

CREATE VIEW empdetails(empno, empname,

dname, salary_fn) AS

A View Involving Two Tables

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 50/53

50

. Updates via views will be reflected in base tables unless the WITH

CHECK OPTION is used when the view is created which prevent

inserts and updates from creating rows that the view itself cannot

select.

UPDATE EMP20SET DEPTNO = 30

WHERE EMPNO = 7369

- the above query would not be allowed if the WITH CHECK

OPTION is used as it would remove the row from the view.

. Views can be used to provide security and to simplify queries.

View EMP20 - a user who only has access to this view is not able to

look at Employees from other Departments.

The WITH CHECK OPTION

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 51/53

51

You cannot update a view if the view's defining query contains oneof the following constructs:

 join

set operator

GROUP BY clause

group function

DISTINCT operator

Restrictions on Updating via Views

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 52/53

52

. Views do not contain any data of their own or occupy storage space

. Views theoretically can be handled the same as base tables

. View definitions are stored in the Catalog

. A view can be defined on top of another view

. Views are created and dropped using SQL Data Definition

statements

. Views can be created using any valid SELECT statement

Notes Concerning Views

8/3/2019 If301 Week10 SQL

http://slidepdf.com/reader/full/if301-week10-sql 53/53

Example of NOT EXISTS

From page 161 of Database Systems byC.J.Date 5th edition

Get Supplier names for suppliers whosupply all parts.

SELECT SNAME FROM S

WHERE NOT EXISTS

(SELECT * FROM P