Sie sind auf Seite 1von 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: hasib@iut-dhaka.edu

February 20, 2011

Abdullah Al Hasib

1 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Outline
1

Constraints
Not Null
Primary Key
Unique
Foreign Key
Check

SQL Query
Aggregate functions
String operations
Set comparison

Exercise
SQL Constraints
SQL Query

Abdullah Al Hasib

2 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Not Null
Primary Key
Unique
Foreign Key
Check

Outline

Constraints

SQL Query

Exercise

Abdullah Al Hasib

3 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Not Null
Primary Key
Unique
Foreign Key
Check

Integrity Constraint

Constraints are conditions that must be satisfied by every


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

Constraints
SQL Query
Exercise

Not Null
Primary Key
Unique
Foreign Key
Check

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 the
data.
Check: Makes sure that all values in a column satisfy certain
criteria.

Abdullah Al Hasib

5 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Not Null
Primary Key
Unique
Foreign Key
Check

Not Null constraint


Used to prevent the the entry of NULL values
- [Constraint <constraint name>] Not Null

Abdullah Al Hasib

6 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Not Null
Primary Key
Unique
Foreign Key
Check

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

Abdullah Al Hasib

6 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Not Null
Primary Key
Unique
Foreign Key
Check

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 to
constraint will be easier later on.

Abdullah Al Hasib

6 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Not Null
Primary Key
Unique
Foreign Key
Check

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 to
constraint 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)

Constraints
SQL Query
Exercise

Not Null
Primary Key
Unique
Foreign Key
Check

Primary Key Constraint


Defines a column or combination of columns which uniquely
identifies 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>)

Abdullah Al Hasib

7 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Not Null
Primary Key
Unique
Foreign Key
Check

Primary Key Constraint


Defines a column or combination of columns which uniquely
identifies 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 primary
key.
Abdullah Al Hasib

7 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Not Null
Primary Key
Unique
Foreign Key
Check

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

Abdullah Al Hasib

8 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Not Null
Primary Key
Unique
Foreign Key
Check

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)

Constraints
SQL Query
Exercise

Not Null
Primary Key
Unique
Foreign Key
Check

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

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)

Constraints
SQL Query
Exercise

Not Null
Primary Key
Unique
Foreign Key
Check

Unique Constraint
Unique specifications are verified in the same way as primary
key(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)

Constraints
SQL Query
Exercise

Not Null
Primary Key
Unique
Foreign Key
Check

Foreign key or Referential Integrity


Attributes of one relation that refer to attributes of another
relation
Most often this constraint references the PRIMARY KEY of
another 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)

Constraints
SQL Query
Exercise

Not Null
Primary Key
Unique
Foreign Key
Check

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 fk
Foreign Key (product id)
References Product(product id) );
Abdullah Al Hasib

12 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Not Null
Primary Key
Unique
Foreign Key
Check

More on referential integrity constraints


It is possible to associate reaction policies to the violations of
referential integrity constraints.
Violations arise from
- updates on referred attribute, or
- tuple deletions
Reactions operate on referencing table, after changes to the
master(referenced) table. They are:
*
*
*
*
*
Abdullah Al Hasib

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.
13 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Not Null
Primary Key
Unique
Foreign Key
Check

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 fk
Foreign Key (product id)
References Product(product id)
On Update Cascade On Delete Restrict );
Abdullah Al Hasib

14 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Not Null
Primary Key
Unique
Foreign Key
Check

Check Constraints
The most generic constraint type
It allows you to specify that the value of an attribute must
satisfy 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)

Constraints
SQL Query
Exercise

Not Null
Primary Key
Unique
Foreign Key
Check

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 Students
Add Constraint std gdr chk
Check(gender in (M,F))
Dropping a constraint using Alter table
- Alter Table <table name>
Drop Constraint <constraint name>
- Alter Table Students
Drop Constraint std gdr chk
Abdullah Al Hasib

16 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Not Null
Primary Key
Unique
Foreign Key
Check

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)

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

Outline

Constraints

SQL Query

Exercise

Abdullah Al Hasib

18 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set 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 given
condition(s).
Simple conditions can be combined using the logical
connectives And, Or, Not.
Order By clause specifies a sorting order in which the
tuples of a query are displayed.

Abdullah Al Hasib

19 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set 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 year
when it was released and its length.
Artists(aID, aName, nat)
That is, the ID and the name of an artist and his/hers
nationality.
Roles(mID, aID, character)
That is, the ID of a movie in which an artist (aID) played a
character.

Abdullah Al Hasib

20 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

More on the SELECT clause


An asterisk in the SELECT clause denotes all attributes
Select *
From Movies
- Result:
mID
1
2
3
4

Abdullah Al Hasib

title
Shining
Player
Chinatown
Repulsion

21 / 49

director
Kubrick
Altman
Polanski
Polanski

year
1980
1982
1974
1965

Lecture-8 (SQL: Part-II)

length
146
146
131
143

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

More on the SELECT clause


The SELECT clause can contain arithmetic expressions
involving the operators +, -, *, and /, and operating on
constants or attributes of tuples.
- Select mID, title, director, 2010 year As numOfYears
From Movies
Result:
mID
1
2
3
4
Abdullah Al Hasib

title
Shining
Player
Chinatown
Repulsion
22 / 49

director
Kubrick
Altman
Polanski
Polanski

noOfYears
30
28
36
34

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

More on the SELECT clause


To force the elimination of duplicates, use the keyword
Distinct after Select.
Query: Find the names of directors who directed at least one
movie

Abdullah Al Hasib

23 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

More on the SELECT clause


To force the elimination of duplicates, use the keyword
Distinct after Select.
Query: Find the names of directors who directed at least one
movie
- Select Distinct director
From Movies
Result
director
Kubrick
Altman
Polanski

Abdullah Al Hasib

23 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

Join queries
Query: Find actors playing in movies directed by Lucas:

Abdullah Al Hasib

24 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

Join queries
Query: Find actors playing in movies directed by Lucas:
Select A.aName
From Artists A, Roles R, Movies M
Where M.director = Lucas

Abdullah Al Hasib

24 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

Join queries
Query: Find actors playing in movies directed by Lucas:
Select A.aName
From Artists A, Roles R, Movies M
Where M.director = Lucas And
R.mID = M.mID

Abdullah Al Hasib

24 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

Join queries
Query: Find actors playing in movies directed by Lucas:
Select A.aName
From Artists A, Roles R, Movies M
Where M.director = Lucas And
R.mID = M.mID And
A.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.aID
relates facts to each other;
[-] Select clause retains only the listed attributes.
Abdullah Al Hasib

24 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

Nested subqueries
SQL provides a mechanism for the nesting of subqueries.
A subquery is a Select-From-Where expression that is
nested within another query.
In general, a Where clause could contain another query,
and test some relationship between an attribute and the
result 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)

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

Nested subqueries contd

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


Select A.aName
From Artists A
Where A.aID In
(Select Distinct R.aID
From Roles R, Movies M
Where M.director = Lucas AND
R.mID = M.mID)

Abdullah Al Hasib

26 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

Nested subqueries contd

Evaluation strategy:
The subquery is evaluated once to produce the
set of aIDs of actors who played in movies of
Lucas

Abdullah Al Hasib

27 / 49

Lecture-8 (SQL: Part-II)

aID
2
4

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

Nested subqueries contd

Evaluation strategy:
The subquery is evaluated once to produce the
set of aIDs of actors who played in movies of
Lucas
Each tuple (as A) is tested against this set

Abdullah Al Hasib

27 / 49

Lecture-8 (SQL: Part-II)

aID
2
4
aName
Harrison Ford
Carrie Fisher

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set 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)

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

Aggregate functions contd


mID
1
2
3
4
5
6
7

title
Shining
Player
Chinatown
Repulsion
Star Wars IV
American Graffiti
Full Metal Jacket

director
Kubrick
Altman
Polanski
Polanski
Lucas
Lucas
Kubrick

year
1980
1982
1974
1965
1977
1973
1987

Query: Count the no of tuples in Movies

Abdullah Al Hasib

29 / 49

Lecture-8 (SQL: Part-II)

length
146
146
131
143
126
110
156

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

Aggregate functions contd


mID
1
2
3
4
5
6
7

title
Shining
Player
Chinatown
Repulsion
Star Wars IV
American Graffiti
Full Metal Jacket

director
Kubrick
Altman
Polanski
Polanski
Lucas
Lucas
Kubrick

year
1980
1982
1974
1965
1977
1973
1987

Query: Count the no of tuples in Movies


- Select Count(*) As noTuples
From Movies

Abdullah Al Hasib

29 / 49

Lecture-8 (SQL: Part-II)

length
146
146
131
143
126
110
156

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

Aggregate functions contd


mID
1
2
3
4
5
6
7

title
Shining
Player
Chinatown
Repulsion
Star Wars IV
American Graffiti
Full Metal Jacket

director
Kubrick
Altman
Polanski
Polanski
Lucas
Lucas
Kubrick

year
1980
1982
1974
1965
1977
1973
1987

Query: Count the no of tuples in Movies


- Select Count(*) As noTuples
From Movies
- Result:
Abdullah Al Hasib

noTuples
7
29 / 49

Lecture-8 (SQL: Part-II)

length
146
146
131
143
126
110
156

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

Aggregate functions contd


Query: Find the number of directors

Abdullah Al Hasib

30 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

Aggregate functions contd


Query: Find the number of directors
Select Count(Distinct director)
As noDirectors
From Movies

Result:
noDirectors
4

Query: Find the average length of Lucass


movies.

Abdullah Al Hasib

30 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

Aggregate functions contd


Query: Find the number of directors
Select Count(Distinct director)
As noDirectors
From Movies
Query: Find the average length of Lucass
movies.
Select Avg(length) As Avgl
From Movies
Where Director = Lucas

Abdullah Al Hasib

30 / 49

Result:
noDirectors
4

Result:
Avgl
118

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

Aggregation and grouping


Query: For each director, return the average running time of
his/her movies.
Select director, AVG(Length) As Alength
From Movies
Group By director

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


mID
1
2
3
4
5
6
7

title

director

year

length

Player
Shining
Full Metal Jacket
Chinatown
Repulsion
Star Wars IV
American Graffiti

Altman
Kubrick
Kubrick
Polanski
Polanski
Lucas
Lucas

1982
1980
1987
1974
1965
1977
1973

146
146
156
131
143
126
110

Abdullah Al Hasib

31 / 49

Then, for each group, compute the average


length of the movies in it.
Result:
Director
Alength
Altman
Kubrick
Polanski
Lucas

Lecture-8 (SQL: Part-II)

146
151
137
118

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set 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 whom
COUNT(mID) >= 2;
for those directors, compute AVG(Length)

SQL has a special syntax for it: HAVING.


Select director, AVG(Length)
From Movies
Group By director
Having Count(mID) >= 2

Abdullah Al Hasib

32 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

Important considerations for Where and Having clause


Where clause can be used to check for conditions based on
values of columns and expressions related to individual rows.
It cannot be used with conditions related to groups.
- Select director, AVG(Length) From Movies
Where Count(mID) >= 2
Group By director
Having clause is specially designed to evaluate the conditions
that are based on group functions such as Sum and Count.
Having clause cannot be used for conditions that are not
related to groups.
- Select aName
From Artists
Having nat = USA
Abdullah Al Hasib

33 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

Selection based on aggregation results

Results of aggregates can be used for comparisons not only in


the HAVING clause.
Query: Find the director and the title of the longest movie
Select M.director, M.title
From Movies M
Where M.length =
( Select Max (M1.length) As maxLen
From Movies M1)

Abdullah Al Hasib

34 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

String operations
SQL includes a string-matching operator for comparisons on
character strings e.g Like operator)
Syntax: match expression [Not] Like pattern
Patterns are described using two special characters:

Wildcard
underscore ( )
percent (%)

Abdullah Al Hasib

Description
Any single character
Any string of zero or
more characters

35 / 49

Example
a b matches cacbc, aabba etc
%a%b matches ab, ccaccbc,
aaaabcbcbbd, aba, etc

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

String operations contd


Find the list of movies containing the word War.
Select Title
From Movies
Where title Like %War%
Is Polanski spelled with a y or with an i?
Select Title, Director
From Movies
Where director Like Polansk

Abdullah Al Hasib

36 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

String operations contd


SQL supports a variety of string operations such as
Function
CONCAT(x, y)
INITCAP(x)
LENGTH(x)
LOWER(x)
REPLACE(x, str1, str2)
SUBSTR(x, start[, length])

UPPER(x)

Abdullah Al Hasib

Description
Appends y to x
Converts the initial letter of each word in x to
uppercase
Returns the number of characters in x
Converts the letters in x to lowercase
Searches x for str1 and replaces it with str2
Returns a substring of x that begins at the
position specified by start. You can supply
an optional length for the substring
Converts the letters in x to uppercase

37 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

String operations contd

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)

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

Set comparison
< value >< condition > ALL(< query >)
Is true if either
< Query > evaluates the empty set
for 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)

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

Set comparison contd


Query: Find directors whose all movies have been completed
before 1980
Select Distinct M.director
From Movies M
Where 1980 > ALL
(Select M1.year
From Movies M1
Where M1.director = M.director)

Abdullah Al Hasib

40 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

Set comparison contd


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

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

Set comparison contd

Query: Find directors who completed some movies after 1980


Select Distinct M.director
From Movies M
Where 1980 < ANY
(Select M1.year
From Movies M1
Where M1.director = M.director)

Abdullah Al Hasib

42 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

Aggregate functions
String operations
Set comparison

Set operations

The set operations UNION, INTERSECT, and EXCEPT


operate on relations and correspond to the relational algebra
operations , ,
Each of the above operations automatically eliminates
duplicates; to retain all duplicates use UNION ALL,
INTERSECT ALL, and EXCEPT ALL.

Abdullah Al Hasib

43 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

SQL Constraints
SQL Query

Outline

Constraints

SQL Query

Exercise

Abdullah Al Hasib

44 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

SQL Constraints
SQL Query

Exercise
Create a client master table as described below
Column Name
client no
name
address
city
pincode
state
bal due

Data Type
char
varchar2
varchar2
varchar2
float
varchar2
number

Size
6
10
10
10
15
10,2

Attributes
Primary Key
Not Null, *
*

Cannot be negative

*(Name & address) uniquely identify each row


Abdullah Al Hasib

45 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

SQL Constraints
SQL Query

Exercise
Create a order details table as described below
Column Name
order no
order date
client no

Data Type
char
date
char

delivery date

date

Abdullah Al Hasib

46 / 49

Size
6
6

Attributes
Primary Key
Foreign Key references
client no of client master table;
if a row in master table is deleted
corresponding row in child is also
deleted
Cant be less than order date

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

SQL Constraints
SQL Query

Sample Database schema for query


Consider the Shipment schema below, consisting of four
relations. 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

Abdullah Al Hasib

Return the product names and inventory value of each product


(price*inventory) ordered by product name.
For all customers in California (CA) list the customer name,
product name, and amount for all shipments
Return total value of products in inventory.

47 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

SQL Constraints
SQL Query

Sample Database schema for query


Consider the Shipment schema below, consisting of four
relations. 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

Abdullah Al Hasib

Return product names and total amount shipped


(price*amount) for products shipping over $1,000.
Return the shipment id and total value of the entire shipment
(price*amount) ordered by the shipment values.
Return the products (name) whose name contains RAM with
a price more than the average price.

48 / 49

Lecture-8 (SQL: Part-II)

Constraints
SQL Query
Exercise

SQL Constraints
SQL Query

Sample Database schema for query


Consider the Shipment schema below, consisting of four
relations. 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

10

Abdullah Al Hasib

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.
Return the number of shipments to customers with first name
Scott.
Return the list of customers (no duplicates) that have never
received a shipment.
Return all customers and their states that share a state with
another customer.
49 / 49

Lecture-8 (SQL: Part-II)

Das könnte Ihnen auch gefallen