lecture-8 (sql_part-ii)c-3.pdf

63
Constraints SQL Query Exercise CIT-4307 Database Management Systems Abdullah Al Hasib Department of Computer Science and Information Technology (CIT) Islamic University of Technology (IUT) Gazipur - 1704, Bangladesh Email: [email protected] February 20, 2011 Abdullah Al Hasib 1 / 49 Lecture-8 (SQL: Part-II)

Upload: ahmediut

Post on 25-Dec-2015

220 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

CIT-4307Database Management Systems

Abdullah Al Hasib

Department of Computer Science and Information Technology (CIT)Islamic University of Technology (IUT)

Gazipur - 1704, BangladeshEmail: [email protected]

February 20, 2011

Abdullah Al Hasib 1 / 49 Lecture-8 (SQL: Part-II)

Page 2: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Outline

1 ConstraintsNot NullPrimary KeyUniqueForeign KeyCheck

2 SQL QueryAggregate functionsString operationsSet comparison

3 ExerciseSQL ConstraintsSQL Query

Abdullah Al Hasib 2 / 49 Lecture-8 (SQL: Part-II)

Page 3: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Not NullPrimary KeyUniqueForeign KeyCheck

Outline

1 Constraints

2 SQL Query

3 Exercise

Abdullah Al Hasib 3 / 49 Lecture-8 (SQL: Part-II)

Page 4: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Not NullPrimary KeyUniqueForeign KeyCheck

Integrity Constraint

Constraints are conditions that must be satisfied by everydatabase instance.

The constraints should be declared in Create Table

SQL checks if each modification preserves constraints

Constraints can be defined in two ways

- Column level definition

- Table level definition

Abdullah Al Hasib 4 / 49 Lecture-8 (SQL: Part-II)

Page 5: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Not NullPrimary KeyUniqueForeign KeyCheck

SQL Integrity Constraints

Not Null: Used to prevent the the entry of NULL values.

Unique: Ensures that all values in a column are different.

Primary Key: Used to uniquely identify a row in the table.

Foreign Key: Used to ensure referential integrity of thedata.

Check: Makes sure that all values in a column satisfy certaincriteria.

Abdullah Al Hasib 5 / 49 Lecture-8 (SQL: Part-II)

USER
Highlight
Page 6: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Not NullPrimary KeyUniqueForeign KeyCheck

Not Null constraint

Used to prevent the the entry of NULL values

- [Constraint <constraint name>] Not Null

Create Table Movies (mID int,title varchar2(20) Not Null,director varchar2(10),year int default 0 );

Note:

It is recommended to use constraint name so that referring toconstraint will be easier later on.

Not Null constraint can only be defined at column level

Abdullah Al Hasib 6 / 49 Lecture-8 (SQL: Part-II)

Page 7: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Not NullPrimary KeyUniqueForeign KeyCheck

Not Null constraint

Used to prevent the the entry of NULL values

- [Constraint <constraint name>] Not Null

Create Table Movies (mID int,title varchar2(20) Not Null,director varchar2(10),year int default 0 );

Note:

It is recommended to use constraint name so that referring toconstraint will be easier later on.

Not Null constraint can only be defined at column level

Abdullah Al Hasib 6 / 49 Lecture-8 (SQL: Part-II)

Page 8: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Not NullPrimary KeyUniqueForeign KeyCheck

Not Null constraint

Used to prevent the the entry of NULL values

- [Constraint <constraint name>] Not Null

Create Table Movies (mID int,title varchar2(20) Not Null,director varchar2(10),year int default 0 );

Note:

It is recommended to use constraint name so that referring toconstraint will be easier later on.

Not Null constraint can only be defined at column level

Abdullah Al Hasib 6 / 49 Lecture-8 (SQL: Part-II)

Page 9: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Not NullPrimary KeyUniqueForeign KeyCheck

Not Null constraint

Used to prevent the the entry of NULL values

- [Constraint <constraint name>] Not Null

Create Table Movies (mID int,title varchar2(20) Not Null,director varchar2(10),year int default 0 );

Note:

It is recommended to use constraint name so that referring toconstraint will be easier later on.

Not Null constraint can only be defined at column level

Abdullah Al Hasib 6 / 49 Lecture-8 (SQL: Part-II)

Page 10: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Not NullPrimary KeyUniqueForeign KeyCheck

Primary Key Constraint

Defines a column or combination of columns which uniquelyidentifies each row in the table

Syntax to define a Primary key at column level

- <Column name> <Data type> [Constraint<constraint name>] Primary Key

Syntax to define a Primary key at table level

- [Constraint <constraint name>] Primary Key (<Column name1>, <Column name2>)

Note:

You have to use table constraint to define composite primarykey.

Abdullah Al Hasib 7 / 49 Lecture-8 (SQL: Part-II)

Page 11: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Not NullPrimary KeyUniqueForeign KeyCheck

Primary Key Constraint

Defines a column or combination of columns which uniquelyidentifies each row in the table

Syntax to define a Primary key at column level

- <Column name> <Data type> [Constraint<constraint name>] Primary Key

Syntax to define a Primary key at table level

- [Constraint <constraint name>] Primary Key (<Column name1>, <Column name2>)

Note:

You have to use table constraint to define composite primarykey.

Abdullah Al Hasib 7 / 49 Lecture-8 (SQL: Part-II)

Page 12: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Not NullPrimary KeyUniqueForeign KeyCheck

Primary Key Constraint

Two equivalent ways to declare primary keys:

Create Table Movies (mID int Primary key,title varchar2(20),director varchar2(10),year int default 0 );

Create Table Movies (mID int,title varchar2(20),director varchar2(10),year int default 0,Primary key (mID));

What if we have another key, e.g., (title, director)?

- We cannot declare it as another primary key

- But we can declare it as unique

Abdullah Al Hasib 8 / 49 Lecture-8 (SQL: Part-II)

Page 13: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Not NullPrimary KeyUniqueForeign KeyCheck

Primary Key Constraint

Two equivalent ways to declare primary keys:

Create Table Movies (mID int Primary key,title varchar2(20),director varchar2(10),year int default 0 );

Create Table Movies (mID int,title varchar2(20),director varchar2(10),year int default 0,Primary key (mID));

What if we have another key, e.g., (title, director)?

- We cannot declare it as another primary key

- But we can declare it as unique

Abdullah Al Hasib 8 / 49 Lecture-8 (SQL: Part-II)

Page 14: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Not NullPrimary KeyUniqueForeign KeyCheck

Primary Key Constraint

Revised Examples (with constraint-names)

1 Create Table Movies (mID int Constraint movies mid pk Primary key,title varchar2(20),director varchar2(10),year int default 0);

2 Create Table Movies (mID int,title varchar2(20),director varchar2(10),year int default 0,Constraint movies mid pk Primary key (mID));

Abdullah Al Hasib 9 / 49 Lecture-8 (SQL: Part-II)

Page 15: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Not NullPrimary KeyUniqueForeign KeyCheck

Unique Constraint

Unique specifications are verified in the same way as primarykey(also accept NULL values)

- [Constraint <constraint name>] Unique

- [Constraint <constraint name>] Unique (<column name>)

Create Table Movies (mID int,title varchar2(20),director varchar2(10),year int default 0,Constraint movies mid pk Primary key (mID),Constraint movies tdir un Unique (title, director));

Abdullah Al Hasib 10 / 49 Lecture-8 (SQL: Part-II)

Page 16: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Not NullPrimary KeyUniqueForeign KeyCheck

Foreign key or Referential Integrity

Attributes of one relation that refer to attributes of anotherrelation

Most often this constraint references the PRIMARY KEY ofanother table

Syntax to define a Foreign key at column level

- [Constraint <constraint name>]References <referenced table name>(<column name>)

Syntax to define a Foreign key at table level

- [Constraint <constraint name>]Foreign Key (<column name>)References <referenced table name>(<column name>)

Abdullah Al Hasib 11 / 49 Lecture-8 (SQL: Part-II)

Page 17: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Not NullPrimary KeyUniqueForeign KeyCheck

Foreign key or Referential Integrity

* Referenced Table Schema:Product(product id, product name, unit price)

Create Table order details (order id number(5) Not Null,product id number(5),quantity number(5),order date date,delivery date date,Constraint order oid pk Primary key (order id),Constraint order pid fkForeign Key (product id)References Product(product id) );

Abdullah Al Hasib 12 / 49 Lecture-8 (SQL: Part-II)

USER
Highlight
Page 18: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Not NullPrimary KeyUniqueForeign KeyCheck

More on referential integrity constraints

It is possible to associate reaction policies to the violations ofreferential integrity constraints.

Violations arise from

- updates on referred attribute, or

- tuple deletions

Reactions operate on referencing table, after changes to themaster(referenced) table. They are:

* No Action: reject the change on the master table;* Restrict: reject the change on the master table;* Cascade: propagate the change;* Set Null: nullify the referring attribute;* Set Default: assign default value to the referring attribute.

Abdullah Al Hasib 13 / 49 Lecture-8 (SQL: Part-II)

Page 19: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Not NullPrimary KeyUniqueForeign KeyCheck

More on referential integrity constraints

* Revised Example* Referenced Table Schema:

Product(product id, product name, unit price)Create Table order details (order id number(5) Not Null,product id number(5),quantity number(5),order date date,delivery date date,Constraint order oid pk Primary key (order id),Constraint order pid fkForeign Key (product id)References Product(product id)On Update Cascade On Delete Restrict );

Abdullah Al Hasib 14 / 49 Lecture-8 (SQL: Part-II)

Page 20: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Not NullPrimary KeyUniqueForeign KeyCheck

Check Constraints

The most generic constraint type

It allows you to specify that the value of an attribute mustsatisfy some condition

- [Constraint <constraint name>]

Check (<column name> <condition>)

Create Table Students (sID int,name varchar2(20),gender char(1),department varchar2(10),Constraint std gdr chk Check(gender in (’M’,’F’))

Abdullah Al Hasib 15 / 49 Lecture-8 (SQL: Part-II)

USER
Highlight
Page 21: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Not NullPrimary KeyUniqueForeign KeyCheck

Adding/Romoving Constraint using Alter Table

Adding a constraint using Alter table

- Alter Table <table name>Add Constraint <constraint name>Check(<column name> <condition>) [Disable]

- Alter Table StudentsAdd Constraint std gdr chkCheck(gender in (’M’,’F’))

Dropping a constraint using Alter table

- Alter Table <table name>Drop Constraint <constraint name>

- Alter Table StudentsDrop Constraint std gdr chk

Abdullah Al Hasib 16 / 49 Lecture-8 (SQL: Part-II)

Page 22: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Not NullPrimary KeyUniqueForeign KeyCheck

To enable/disable a Constraint

To enable a constraint

- Alter Table <table name>Enable Constraint <constraint name>

To disable a constraint

- Alter Table <table name>Disable Constraint <constraint name>

Abdullah Al Hasib 17 / 49 Lecture-8 (SQL: Part-II)

Page 23: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

Outline

1 Constraints

2 SQL Query

3 Exercise

Abdullah Al Hasib 18 / 49 Lecture-8 (SQL: Part-II)

Page 24: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

SQL Query: Basic structure

A typical SQL query has the form:Select [Dinstinct] <a1, a2, ...., an>From <r1, r2, ...., rn>[Where <condition>][ Order By <attributes> [asc|desc] ]

- Distinct eliminates the duplicate tuples.

- From clause produces Cartesian product of listed relations.

- Where clause selects the tuples that satisfy the givencondition(s).

- Simple conditions can be combined using the logicalconnectives And, Or, Not.

- Order By clause specifies a sorting order in which thetuples of a query are displayed.

Abdullah Al Hasib 19 / 49 Lecture-8 (SQL: Part-II)

Page 25: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

Sample Database schema for query

Consider the Movie schema below, consisting of three relations.The key attributes are underlined.

Movies(mID, title, director, year, length)That is, the ID, the title, the director of a movie, the yearwhen it was released and its length.

Artists(aID, aName, nat)That is, the ID and the name of an artist and his/hersnationality.

Roles(mID, aID, character)That is, the ID of a movie in which an artist (aID) played acharacter.

Abdullah Al Hasib 20 / 49 Lecture-8 (SQL: Part-II)

USER
Highlight
Page 26: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

More on the SELECT clause

An asterisk in the SELECT clause denotes ”all attributes”

Select *From Movies

- Result:

mID title director year length

1 Shining Kubrick 1980 1462 Player Altman 1982 1463 Chinatown Polanski 1974 1314 Repulsion Polanski 1965 143

Abdullah Al Hasib 21 / 49 Lecture-8 (SQL: Part-II)

USER
Highlight
Page 27: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

More on the SELECT clause

The SELECT clause can contain arithmetic expressionsinvolving the operators +, -, *, and /, and operating onconstants or attributes of tuples.

- Select mID, title, director, 2010 – year As numOfYearsFrom Movies

Result:

mID title director noOfYears

1 Shining Kubrick 302 Player Altman 283 Chinatown Polanski 364 Repulsion Polanski 34

Abdullah Al Hasib 22 / 49 Lecture-8 (SQL: Part-II)

USER
Highlight
Page 28: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

More on the SELECT clause

To force the elimination of duplicates, use the keywordDistinct after Select.

Query: Find the names of directors who directed at least onemovie

- Select Distinct directorFrom Movies

Result

director

KubrickAltmanPolanski

Abdullah Al Hasib 23 / 49 Lecture-8 (SQL: Part-II)

Page 29: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

More on the SELECT clause

To force the elimination of duplicates, use the keywordDistinct after Select.

Query: Find the names of directors who directed at least onemovie

- Select Distinct directorFrom Movies

Result

director

KubrickAltmanPolanski

Abdullah Al Hasib 23 / 49 Lecture-8 (SQL: Part-II)

USER
Highlight
Page 30: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

Join queries

Query: Find actors playing in movies directed by Lucas:

Select A.aNameFrom Artists A, Roles R, Movies MWhere M.director = ’Lucas’ And

R.mID = M.mID AndA.aID = R.aID

Evaluation strategy

[-] From clause produces Cartesian product of listed relations;[-] Where clause:

Selection condition M.director = ’Lucas’eliminates irrelevant tuples;

Join conditions R.mID = M.mID And A.aID = R.aIDrelates facts to each other;

[-] Select clause retains only the listed attributes.

Abdullah Al Hasib 24 / 49 Lecture-8 (SQL: Part-II)

Page 31: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

Join queries

Query: Find actors playing in movies directed by Lucas:

Select A.aNameFrom Artists A, Roles R, Movies MWhere M.director = ’Lucas’

AndR.mID = M.mID AndA.aID = R.aID

Evaluation strategy

[-] From clause produces Cartesian product of listed relations;[-] Where clause:

Selection condition M.director = ’Lucas’eliminates irrelevant tuples;

Join conditions R.mID = M.mID And A.aID = R.aIDrelates facts to each other;

[-] Select clause retains only the listed attributes.

Abdullah Al Hasib 24 / 49 Lecture-8 (SQL: Part-II)

Page 32: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

Join queries

Query: Find actors playing in movies directed by Lucas:

Select A.aNameFrom Artists A, Roles R, Movies MWhere M.director = ’Lucas’ And

R.mID = M.mID

AndA.aID = R.aID

Evaluation strategy

[-] From clause produces Cartesian product of listed relations;[-] Where clause:

Selection condition M.director = ’Lucas’eliminates irrelevant tuples;

Join conditions R.mID = M.mID And A.aID = R.aIDrelates facts to each other;

[-] Select clause retains only the listed attributes.

Abdullah Al Hasib 24 / 49 Lecture-8 (SQL: Part-II)

Page 33: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

Join queries

Query: Find actors playing in movies directed by Lucas:

Select A.aNameFrom Artists A, Roles R, Movies MWhere M.director = ’Lucas’ And

R.mID = M.mID AndA.aID = R.aID

Evaluation strategy

[-] From clause produces Cartesian product of listed relations;[-] Where clause:

Selection condition M.director = ’Lucas’eliminates irrelevant tuples;

Join conditions R.mID = M.mID And A.aID = R.aIDrelates facts to each other;

[-] Select clause retains only the listed attributes.

Abdullah Al Hasib 24 / 49 Lecture-8 (SQL: Part-II)

USER
Highlight
Page 34: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

Nested subqueries

SQL provides a mechanism for the nesting of subqueries.

A subquery is a Select-From-Where expression that isnested within another query.

In general, a Where clause could contain another query,and test some relationship between an attribute and theresult of that query.

A common use of subqueries is to perform tests for

Set-valued subqueries- <expression> [Not] In ( subquery )- <expression> <comparison operator> In ( subquery )

Test for non-existence- [Not] Exists ( subquery )

Abdullah Al Hasib 25 / 49 Lecture-8 (SQL: Part-II)

Page 35: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

Nested subqueries cont’d

Query: Find actors(name) playing in movies directed by Lucas:

Select A.aNameFrom Artists AWhere A.aID In

(Select Distinct R.aIDFrom Roles R, Movies MWhere M.director = Lucas ANDR.mID = M.mID)

Abdullah Al Hasib 26 / 49 Lecture-8 (SQL: Part-II)

Page 36: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

Nested subqueries cont’d

Evaluation strategy:

The subquery is evaluated once to produce theset of aID’s of actors who played in movies ofLucas

aID

24

Each tuple (as A) is tested against this set

aName

Harrison FordCarrie Fisher

Abdullah Al Hasib 27 / 49 Lecture-8 (SQL: Part-II)

Page 37: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

Nested subqueries cont’d

Evaluation strategy:

The subquery is evaluated once to produce theset of aID’s of actors who played in movies ofLucas

aID

24

Each tuple (as A) is tested against this set

aName

Harrison FordCarrie Fisher

Abdullah Al Hasib 27 / 49 Lecture-8 (SQL: Part-II)

Page 38: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

Aggregate functions

These functions operate on the values of a column of a relation,and return a value.

Avg: average value

Min: minimum value

Max: maximum value

Sum: sum of the values

Count: number of values

Stddev: standard deviation of the values

Var: variance of the values

Abdullah Al Hasib 28 / 49 Lecture-8 (SQL: Part-II)

USER
Highlight
Page 39: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

Aggregate functions cont’d

mID title director year length

1 Shining Kubrick 1980 1462 Player Altman 1982 1463 Chinatown Polanski 1974 1314 Repulsion Polanski 1965 1435 Star Wars IV Lucas 1977 1266 American Graffiti Lucas 1973 1107 Full Metal Jacket Kubrick 1987 156

Query: Count the no of tuples in Movies

- Select Count(*) As noTuplesFrom Movies

- Result:noTuples

7

Abdullah Al Hasib 29 / 49 Lecture-8 (SQL: Part-II)

Page 40: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

Aggregate functions cont’d

mID title director year length

1 Shining Kubrick 1980 1462 Player Altman 1982 1463 Chinatown Polanski 1974 1314 Repulsion Polanski 1965 1435 Star Wars IV Lucas 1977 1266 American Graffiti Lucas 1973 1107 Full Metal Jacket Kubrick 1987 156

Query: Count the no of tuples in Movies

- Select Count(*) As noTuplesFrom Movies

- Result:noTuples

7

Abdullah Al Hasib 29 / 49 Lecture-8 (SQL: Part-II)

USER
Highlight
Page 41: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

Aggregate functions cont’d

mID title director year length

1 Shining Kubrick 1980 1462 Player Altman 1982 1463 Chinatown Polanski 1974 1314 Repulsion Polanski 1965 1435 Star Wars IV Lucas 1977 1266 American Graffiti Lucas 1973 1107 Full Metal Jacket Kubrick 1987 156

Query: Count the no of tuples in Movies

- Select Count(*) As noTuplesFrom Movies

- Result:noTuples

7

Abdullah Al Hasib 29 / 49 Lecture-8 (SQL: Part-II)

Page 42: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

Aggregate functions cont’d

Query: Find the number of directors

Select Count(Distinct director)As noDirectors

From Movies

Result:noDirectors

4

Query: Find the average length of Lucas’smovies.

Select Avg(length) As AvglFrom MoviesWhere Director = ’Lucas’

Result:Avgl

118

Abdullah Al Hasib 30 / 49 Lecture-8 (SQL: Part-II)

Page 43: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

Aggregate functions cont’d

Query: Find the number of directors

Select Count(Distinct director)As noDirectors

From Movies

Result:noDirectors

4

Query: Find the average length of Lucas’smovies.

Select Avg(length) As AvglFrom MoviesWhere Director = ’Lucas’

Result:Avgl

118

Abdullah Al Hasib 30 / 49 Lecture-8 (SQL: Part-II)

Page 44: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

Aggregate functions cont’d

Query: Find the number of directors

Select Count(Distinct director)As noDirectors

From Movies

Result:noDirectors

4

Query: Find the average length of Lucas’smovies.

Select Avg(length) As AvglFrom MoviesWhere Director = ’Lucas’

Result:Avgl

118

Abdullah Al Hasib 30 / 49 Lecture-8 (SQL: Part-II)

USER
Highlight
Page 45: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

Aggregation and grouping

Query: For each director, return the average running time ofhis/her movies.

Select director, AVG(Length) As AlengthFrom MoviesGroup By director

First, create groups based on the values of the director attribute.

mID title director year length

1 Player Altman 1982 1462 Shining Kubrick 1980 1463 Full Metal Jacket Kubrick 1987 1564 Chinatown Polanski 1974 1315 Repulsion Polanski 1965 1436 Star Wars IV Lucas 1977 1267 American Graffiti Lucas 1973 110

Then, for each group, compute the averagelength of the movies in it.Result:

Director Alength

Altman 146Kubrick 151Polanski 137

Lucas 118

Abdullah Al Hasib 31 / 49 Lecture-8 (SQL: Part-II)

Page 46: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

Selection based on aggregation results

Query: Find directors and average length of their movies,provided they made at least two movies

Idea:

from all the groups of directors, consider only those for whomCOUNT(mID) >= 2;for those directors, compute AVG(Length)

SQL has a special syntax for it: HAVING.

Select director, AVG(Length)From MoviesGroup By directorHaving Count(mID) >= 2

Abdullah Al Hasib 32 / 49 Lecture-8 (SQL: Part-II)

USER
Highlight
Page 47: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

Important considerations for Where and Having clause

Where clause can be used to check for conditions based onvalues of columns and expressions related to individual rows.It cannot be used with conditions related to groups.

- Select director, AVG(Length) From MoviesWhere Count(mID) >= 2Group By director

Having clause is specially designed to evaluate the conditionsthat are based on group functions such as Sum and Count.Having clause cannot be used for conditions that are notrelated to groups.

- Select aNameFrom ArtistsHaving nat = ’USA’

Abdullah Al Hasib 33 / 49 Lecture-8 (SQL: Part-II)

Page 48: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

Selection based on aggregation results

Results of aggregates can be used for comparisons not only inthe HAVING clause.

Query: Find the director and the title of the longest movie

Select M.director, M.titleFrom Movies MWhere M.length =

( Select Max (M1.length) As maxLenFrom Movies M1)

Abdullah Al Hasib 34 / 49 Lecture-8 (SQL: Part-II)

Page 49: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

String operations

SQL includes a string-matching operator for comparisons oncharacter strings e.g Like operator)

Syntax: match expression [Not] Like pattern

Patterns are described using two special characters:

Wildcard Description Example

underscore ( ) Any single character ’ a b ’ matches cacbc, aabba etcpercent (%) Any string of zero or ’%a%b’ matches ab, ccaccbc,

more characters aaaabcbcbbd, aba, etc

Abdullah Al Hasib 35 / 49 Lecture-8 (SQL: Part-II)

Page 50: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

String operations cont’d

Find the list of movies containing the word ”War”.

Select TitleFrom MoviesWhere title Like ’%War%’

Is Polanski spelled with a ”y” or with an ”i”?

Select Title, DirectorFrom MoviesWhere director Like ’Polansk ’

Abdullah Al Hasib 36 / 49 Lecture-8 (SQL: Part-II)

USER
Highlight
USER
Highlight
Page 51: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

String operations cont’d

SQL supports a variety of string operations such as

Function Description

CONCAT(x, y) Appends y to xINITCAP(x) Converts the initial letter of each word in x to

uppercaseLENGTH(x) Returns the number of characters in xLOWER(x) Converts the letters in x to lowercaseREPLACE(x, str1, str2) Searches x for str1 and replaces it with str2SUBSTR(x, start[, length]) Returns a substring of x that begins at the

position specified by start. You can supplyan optional length for the substring

UPPER(x) Converts the letters in x to uppercase

Abdullah Al Hasib 37 / 49 Lecture-8 (SQL: Part-II)

Page 52: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

String operations cont’d

Find out the full name of all customers

Select Concat(first name, last name)From Customers

Find out the length of the titles of all the movies

Select Title, Length(title)From Movies

Abdullah Al Hasib 38 / 49 Lecture-8 (SQL: Part-II)

Page 53: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

Set comparison

< value >< condition > ALL(< query >)Is true if either

< Query > evaluates the empty setfor every < value1 > in the result of < query >,< value >< condition >< value1 > is true.

where < condition > can be <,≤, >,≥, 6=,=

For example

5 > ALL(∅) is true;5 > ALL(1, 2, 3) is true;5 > ALL(1, 2, 3, 4, 5, 6) is false.5 6= ALL(1, 2, 3, 4) is true.5 = ALL(4, 5) is false.

6= ALL is equivalent to NOT IN

But, = ALL is not equivalent to IN

Abdullah Al Hasib 39 / 49 Lecture-8 (SQL: Part-II)

Page 54: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

Set comparison cont’d

Query: Find directors whose all movies have been completedbefore 1980

Select Distinct M.directorFrom Movies MWhere 1980 > ALL

(Select M1.yearFrom Movies M1Where M1.director = M.director)

Abdullah Al Hasib 40 / 49 Lecture-8 (SQL: Part-II)

Page 55: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

Set comparison cont’d

< value >< condition > ANY (< query >)Is true if

for some < value1 > in the result of < query >,< value >< condition >< value1 > is true.

where < condition > can be <,≤, >,≥, 6=,=

For example

5 < ANY (∅) is false;5 < ANY(1, 2, 3) is false;5 < ANY(1, 2, 3, 4, 5, 6) is true.5 6= ANY(1, 2, 3, 4) is true.5 = ANY(4, 5) is true.

= ANY is equivalent to IN

6= ANY is not equivalent to NOT IN

Abdullah Al Hasib 41 / 49 Lecture-8 (SQL: Part-II)

Page 56: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

Set comparison cont’d

Query: Find directors who completed some movies after 1980

Select Distinct M.directorFrom Movies MWhere 1980 < ANY

(Select M1.yearFrom Movies M1Where M1.director = M.director)

Abdullah Al Hasib 42 / 49 Lecture-8 (SQL: Part-II)

Page 57: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

Aggregate functionsString operationsSet comparison

Set operations

The set operations UNION, INTERSECT, and EXCEPToperate on relations and correspond to the relational algebraoperations ∪,∩,−Each of the above operations automatically eliminatesduplicates; to retain all duplicates use UNION ALL,INTERSECT ALL, and EXCEPT ALL.

Abdullah Al Hasib 43 / 49 Lecture-8 (SQL: Part-II)

Page 58: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

SQL ConstraintsSQL Query

Outline

1 Constraints

2 SQL Query

3 Exercise

Abdullah Al Hasib 44 / 49 Lecture-8 (SQL: Part-II)

Page 59: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

SQL ConstraintsSQL Query

Exercise

Create a client master table as described below

Column Name Data Type Size Attributes

client no char 6 Primary Key

name varchar2 10 Not Null, *

address varchar2 10 *

city varchar2 10

pincode float

state varchar2 15

bal due number 10,2 Cannot be negative

*(Name & address) uniquely identify each row

Abdullah Al Hasib 45 / 49 Lecture-8 (SQL: Part-II)

Page 60: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

SQL ConstraintsSQL Query

Exercise

Create a order details table as described below

Column Name Data Type Size Attributes

order no char 6 Primary Keyorder date dateclient no char 6 Foreign Key references

client no of client master table;if a row in master table is deletedcorresponding row in child is alsodeleted

delivery date date Can’t be less than order date

Abdullah Al Hasib 46 / 49 Lecture-8 (SQL: Part-II)

Page 61: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

SQL ConstraintsSQL Query

Sample Database schema for query

Consider the Shipment schema below, consisting of fourrelations. The key attributes are underlined.

Customer(cid, cname, address, city, state)Product(pid, pname, price, inventory)Shipment(sid, cid, shipdate)ShippedProduct(sid, pid, amount)

Write down the sql statements for the following queries:1 Return the product names and inventory value of each product

(price*inventory) ordered by product name.2 For all customers in California (’CA’) list the customer name,

product name, and amount for all shipments3 Return total value of products in inventory.

Abdullah Al Hasib 47 / 49 Lecture-8 (SQL: Part-II)

Page 62: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

SQL ConstraintsSQL Query

Sample Database schema for query

Consider the Shipment schema below, consisting of fourrelations. The key attributes are underlined.

Customer(cid, cname, address, city, state)Product(pid, pname, price, inventory)Shipment(sid, cid, shipdate)ShippedProduct(sid, pid, amount)

Write down the sql statements for the following queries:4 Return product names and total amount shipped

(price*amount) for products shipping over $1,000.5 Return the shipment id and total value of the entire shipment

(price*amount) ordered by the shipment values.6 Return the products (name) whose name contains ’RAM’ with

a price more than the average price.

Abdullah Al Hasib 48 / 49 Lecture-8 (SQL: Part-II)

Page 63: Lecture-8 (SQL_Part-II)C-3.pdf

ConstraintsSQL Query

Exercise

SQL ConstraintsSQL Query

Sample Database schema for query

Consider the Shipment schema below, consisting of fourrelations. The key attributes are underlined.

Customer(cid, cname, address, city, state)Product(pid, pname, price, inventory)Shipment(sid, cid, shipdate)ShippedProduct(sid, pid, amount)

Write down the sql statements for the following queries:7 Return customer names and total sales of products shipped to

each customer. Only show customers with total sales of over$200 with the results ordered in descending order of total sales.

8 Return the number of shipments to customers with first nameScott.

9 Return the list of customers (no duplicates) that have neverreceived a shipment.

10 Return all customers and their states that share a state withanother customer.

Abdullah Al Hasib 49 / 49 Lecture-8 (SQL: Part-II)