SQL Queries and Database Design Basics
SQL Queries and Database Design Basics
Syllabus
SQL: Queries, Constraints, Triggers: Form of
Basic SQL Query, UNION, INTERSECT, and
EXCEPT, Nested Queries, Aggregate
Operators, NULL values, Natural JOINS,
Complex Integrity Constraints in SQL,
Triggers and Active Data bases..
Schema Refinement and Normal Forms:
Introduction to Schema Refinement,
Functional Dependencies - Reasoning about
FDs, Normal Forms, Properties of
Decompositions, Normalization, Schema
Refinement in Database Design, Other Kinds
SQL
SQL: The Query Language
4 | Chaitali | 6500.00 |
5 | Hardik | 8500.00 |
6 | Komal | 4500.00 |
7 | Muffy | 10000.00 |
Table name Attribute names
Tables in SQL
Product
Tuples or rows
The schema of a table is the table name and
its attributes:
Product(PName, Price, Category,
Manfacturer)
SELECT
SELECT attributes
attributes
FROM
FROM relations
relations(possibly
(possibly
multiple)
multiple)
WHERE
WHERE conditions
conditions(selections)
(selections)
Simple SQL Query
Product PName Price Category Manufacturer
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
SELECT
SELECT **
FROM
FROM Product
Product
WHERE
WHERE category=‘Gadgets’
category=‘Gadgets’
SELECT
SELECT PName,
PName,Price,
Price,Manufacturer
Manufacturer
FROM
FROM Product
Product
WHERE
WHERE Price
Price>
>100
100
SELECT
SELECT PName,
PName,Price,
Price,Manufacturer
Manufacturer
FROM
FROM Product
Product
WHERE
WHERE Price
Price>
>100
100
Output Schema
Eliminating Duplicates
Category
SELECT
SELECT DISTINCT
DISTINCTcategory
category Gadgets
FROM
FROM Product
Product Photography
Household
Compare to:
Category
Gadgets
SELECT
SELECT category
category Gadgets
FROM
FROM Product
Product Photography
Household
Ordering the Results
SELECT
SELECT pname,
pname,price,
price,manufacturer
manufacturer
FROM
FROM Product
Product
WHERE
WHERE price
price>
>5050
ORDER
ORDERBY
BY pname;
pname;
?
Gizmo $19.99 Gadgets GizmoWorks
Powergizmo $29.99 Gadgets GizmoWorks
SingleTouch $149.99 Photography Canon
MultiTouch $203.99 Household Hitachi
Ordering the Results
Category
SELECT
SELECT DISTINCT
DISTINCTcategory
category Gadgets
FROM
FROM Product
Product Household
ORDER
ORDERBY
BYcategory
category
Photography
Compare to:
?
SELECT
SELECT category
category
FROM
FROM Product
Product
ORDER
ORDERBY
BYpname
pname
Joins in SQL
Connect two or more tables:
GizmoWorks 25 USA
What is
the connection Canon 65 Japan
between
them ? Hitachi 15 Japan
Joins
Product (pname, price, category, manufacturer)
Company (cname, stockPrice, country)
SELECT
SELECT pname,
pname,price
price
FROM
FROM Product,
Product,Company
Company
WHERE
WHERE manufacturer=cname
manufacturer=cnameAND
AND
country=‘Japan’
country=‘Japan’ PName Price
AND
ANDprice
price<=
<=200
200 SingleTouch $149.99
Joins
Product (pname, price, category, manufacturer)
Company (cname, stockPrice, country)
SELECT
SELECT country
country
FROM
FROM Product,
Product,Company
Company
WHERE
WHERE manufacturer=cname
manufacturer=cnameAND
ANDcategory=‘Gadgets’
category=‘Gadgets’
Joins in SQL
Product
Company
Name Price Category Manufacturer
Cname StockPrice Country
Gizmo $19.99 Gadgets GizmoWorks
GizmoWorks 25 USA
Powergizmo $29.99 Gadgets GizmoWorks
Canon 65 Japan
SingleTouch $149.99 Photography Canon
Hitachi 15 Japan
MultiTouch $203.99 Household Hitachi
SELECT
SELECT country
country
FROM
FROM Product,
Product,Company
Company
WHERE
WHERE manufacturer=cname
manufacturer=cnameAND
ANDcategory=‘Gadgets’
category=‘Gadgets’
Country
??
??
Disambiguating Attributes
Sometimes two relations have the same
attr:
Person(pname, address, worksfor)
Company(cname, address)
Which
SELECT DISTINCT address ?
SELECT DISTINCTpname,
pname,address
address
FROM
FROM Person,
Person,Company
Company
WHERE
WHERE worksfor
worksfor= =cname
cname
SELECT
SELECT DISTINCT
[Link],
[Link],[Link]
[Link]
FROM
FROM Person,
Person,Company
Company
WHERE
WHERE [Link]
[Link]=
=[Link]
[Link]
Example Database
Sailors Boats
Reserves
Sailors Reserves
Sailors(sid:integer, sname:string,
rating:integer, age:real)
Boats(bid:integer, bname:string,
color:string)
Reserves(sid:integer, bid:integer, day:date)
Relation Instances…1
An Instance of Sailors
22 Dustin 7 45.0
29 Brutus 1 33.0
31 Lubber 8 55.5
32 Andy 8 25.5
58 Rusty 10 35.0
64 Horatio 7 35.0
71 Zorba 10 16.0
74 Horatio 9 35.0
85 Art 3 25.5
95 Bob 3 63.5
Relation Instances…2
An Instance of Reserves
22 101 10/10/9
8
22 102 10/10/9
8
22 103 10/08/9
8
22 104 10/07/9
8
31 102 11/10/9
8
31 103 11/06/9
8
31 104 11/12/9
8
64 101 09/05/9
8
64 102 09/08/9
8
74 103 09/08/9
8
Relation Instances…3
An Instance of Boats
Dustin 45.0
Brutus 33.0
Lubber 55.5
Horatio 35.0
Zorba 16.0
Horatio 35.0
Art 25.5
Bob 63.5
Preventing Duplicate Tuples in Result
Use the DISTINCT keyword in the SELECT
clause:
sname age
Dustin 45.0
Brutus 33.0
Lubber 55.5
Andy 25.5
Appears only once
Rusty 35.0
Horatio 35.0
Zorba 16.0
Art 25.5
Bob 63.5
Union, Intersect, and Except
SQL provides three set-manipulation
constructs that extend the basic query
form presented earlier.
Union ()
Intersection ()
Except ()
(many systems recognize the keyword MINUS for
EXCEPT)
UNION Operator
SELECT [Link]
FROM Sailors S, Boats B, Reserves R
WHERE [Link]=[Link] AND [Link]=[Link]
AND ([Link]=‘red’ OR [Link]=‘green’)
SELECT [Link]
FROM Sailors S, Boats B, Reserves R
WHERE [Link]=[Link] AND [Link]=[Link]
AND [Link]=‘red’
UNION
SELECT [Link]
FROM Sailors S, Boats B, Reserves R
WHERE [Link]=[Link] AND [Link]=[Link]
AND [Link]=‘green’
sailors sid sname rating age
Boats bid bname color
Reserves sid bid day
Example: Find sid’s of sailors who’ve reserved a red and a green boat
SELECT [Link]
FROM Sailors S, Boats B, Reserves R,
WHERE [Link]=[Link] AND [Link]=[Link]
AND [Link]=[Link] AND [Link]=[Link]
AND ([Link]=‘red’ AND [Link]=‘green’)
SELECT [Link]
FROM Sailors S, Boats B, Reserves R
WHERE [Link]=[Link] AND [Link]=[Link]
AND [Link]=‘red’
INTERSECT
SELECT [Link]
FROM Sailors S, Boats B, Reserves R
WHERE [Link]=[Link] AND [Link]=[Link]
AND [Link]=‘green’
sailors sid sname rating age
Boats bid bname color
Reserves sid bid day
Example: Find sid’s of all sailors who’ve reserved red boat but not green
boat.
SELECT [Link]
FROM Sailors S, Boats B, Reserves
Indeed, since the
R
Reserves relation contains WHERE [Link]=[Link] AND
sid information, there is [Link]=[Link]
no need AND [Link]=‘red’
to look at the Sailors EXCEPT
relation. SELECT [Link]
FROM Sailors S, Boats B, Reserves
R
SELECT [Link]
WHERE [Link]=[Link] AND
FROM Boats B, Reserves R
[Link]=[Link]
WHERE [Link]=[Link] AND
AND [Link]=‘green’
[Link]=‘red’
EXCEPT
SELECT [Link]
FROM Boats B, Reserves R
WHERE [Link]=[Link] AND
[Link]=‘green’
Nested Queries
A Subquery or Inner query is a query within another SQL
query and embedded within the WHERE clause.
Subqueries generally occur within the WHERE clause (but
can also appear within the FROM and HAVING clauses)
SELECT column-names
FROM table-name1
WHERE value IN (SELECT column-name
FROM table-name2
WHERE condition)
mple: Find names of sailors who’ve reserved boat #1
SELECT [Link]
FROM Sailors S, Reserves R
WHERE [Link]=[Link] AND [Link]=103
alternative:
SELECT [Link]
FROM Sailors S
WHERE [Link] IN (SELECT [Link]
FROM Reserves R
WHERE
[Link]=103)
Consider: Find names of sailors who’ve not reserved boat #103:
SELECT [Link]
FROM Sailors S
WHERE UNIQUE (SELECT [Link]
FROM Reserves R
WHERE [Link]=103
AND [Link]=[Link])
Example: Find sailors whose rating is better than every sailor called
Horatio.
SELECT *
FROM Sailors S
WHERE [Link] > ALL (SELECT [Link]
FROM Sailors S2
WHERE [Link]=‘Horatio’)
SELECT *
FROM Sailors S
WHERE [Link] >= ALL (SELECT [Link]
FROM Sailors
S2)
Aggregate Operators
SQL allows the use of arithmetic expressions.
SQL supports five aggregate operations, which can be applied on any
column of a relation .
What is aggregation?
Computing arithmetic expressions, such as Minimum or
Maximum
COUNT([DISTINCT] A) The number of (unique) value in the A
column.
SUM ( [DISTINCT] A) The sum of all (unique) values in the
A column.
AVG ([DISTINCT A) The average of all (unique) values in
the A column.
MAX (A) The maximum value in the A column.
SELECT [Link]
FROM Sailors S
WHERE [Link] > ALL (SELECT [Link]
FROM Sailors S
WHERE [Link] = 10)
Alternative
SELECT [Link]
FROM Sailors S
WHERE [Link] > (SELECT MAX ([Link])
FROM Sailors S
WHERE [Link] = 10)
Example of MIN operators
Select min([Link])from sailors s;
BETWEEN and AND operators
SELECT sname
FROM Sailors
WHERE age BETWEEN 25 AND 35;
GROUP BY CLAUSE
The SQL GROUP BY clause is used in
collaboration with the SELECT statement to
arrange identical data into groups.
Important Points:
GROUP BY clause is used with the SELECT
statement.
In the query, GROUP BY clause is placed
after the WHERE clause.
In the query, GROUP BY clause is placed
before ORDER BY clause if used any.
Syntax:
SELECT column1, function_name(column2)
FROM table_name WHERE condition GROUP
BY column1, column2;
function_name: Name of the function used
for example, SUM() , AVG().
table_name: Name of the table.
condition: Condition used.
Employee
Student
Group By single column: Group By single
column means, to place all the rows with
same value of only that particular column in
one group.
Consider the query as shown below:
8
Contd…
• When a relation in the relational
model is not in appropriate normal
form then the decomposition of a
relation is required.
• If the relation has no proper
decomposition, then it may lead to
problems like loss of information.
• Decomposition is used to eliminate
some of the problems of bad design
like anomalies, inconsistencies, and
redundancy. 8
Types of decomposition
Lossless Decomposition
• If the information is not lost from the relation
that is decomposed, then the decomposition
will be lossless.
• The lossless decomposition guarantees that
the join of relations will result in the same
relation as it was decomposed.
Employee table
Department table
Dependency preserving
• It is an important constraint of the database.
• In the dependency preservation, at least one decomposed
table must satisfy every dependency.
• If a relation R is decomposed into relation R1 and R2, then the
dependencies of R either must be a part of R1 or R2 or must
be derivable from the combination of functional dependencies
of R1 and R2.
• For example, suppose there is a relation R (A, B, C, D) with
functional dependency set (A->BC). The relational R is
decomposed into R1(ABC) and R2(AD) which is dependency
preserving because FD A->BC is a part of relation R1(ABC).
Problems Related to decomposition
• Unless we are careful, decomposing a relation schema can
create more problems than it solves.
• Two important questions must be asked repeatedly:
1. What problems (if any) does a given decomposition
cause?
[Link] we need to decompose a relation?
Functional dependency
George R. R.
Game of Thrones 66
Martin
George R. R.
Dying of the Light 66
Martin
REASONING ABOUT FD’S
We say that an FD F is implied by a given set F of FD’s
if F holds on every relation instance that satisfies all
dependencies in F.i.e f holds whenever all FD’s hold.
Closure of set of FD’s:
The set of all FD’s implied by a given set F of FD’s is
called closure of F denoted as F+.
How can we infer or compute the closure of given set
F of FD’s.
Sol: Armstrong axioms can be applied repeatedly to
infer all FD’s implied by set of F of FD’s
13
We use A,B,C to denote sets of attributes over
a relation schema R
Step-02:
Recursively add the attributes to the
result set which can be functionally
determined from the attributes already
Example:
[Link] a relation R(A,B,C,D,E,F,G) with the
functional dependencies
A->BC
BC->DE
D->F
CF->G
Find the closure of an attributes and
attribute sets.
Solution:
Closure of attribute A-
A+ = { A }
= { A , B , C } ( Using A → BC )
= { A , B , C , D , E } ( Using BC → DE )
= { A , B , C , D , E , F } ( Using D → F )
= { A , B , C , D , E , F , G } ( Using CF → G )
Thus,
A+ = { A , B , C , D , E , F , G }
Contd…
Closure of attribute D-
D+ = { D }
= { D , F } ( Using D → F )
We can not determine any other attribute using
attributes D and F contained in the result set.
Thus,
D+ = { D , F }
Contd…
Closure of attribute set {B, C}-
{ B , C }+= { B , C }
= { B , C , D , E } ( Using BC → DE )
= { B , C , D , E , F } ( Using D → F )
= { B , C , D , E , F , G } ( Using CF → G )
Thus,
{ B , C }+ = { B , C , D , E , F , G }
Finding the Keys Using Closure-
Super Key-
If the closure result of an attribute set
contains all the attributes of the relation, then
that attribute set is called as a super key of that
relation.
Thus, we can say-
“The closure of a super key is the entire
relation schema.”
Example-
In the above example,
The closure of attribute A is the entire relation
schema.
Thus, attribute A is a super key for that
Contd…
Candidate Key-
If there exists no subset of an attribute set
whose closure contains all the attributes of
the relation, then that attribute set is called
as a candidate key of that relation.
Example-
In the above example,
No subset of attribute A contains all the
attributes of the relation.
Thus, attribute A is also a candidate key for
that relation.
2. Consider a relation R(A,B,C,D,E,F) F: E->A,
E->D, A->C, A->D, AE->F, AG->K. Find the
closure of E or E+
The closure of E or E+ is as follows −
E+ = E
=EA {for E->A add A}
=EAD {for E->D add D}
=EADC {for A->C add C}
=EADC {for A->D D already added}
=EADCF {for AE->F add F}
=EADCF
[Link] the relation R(A,B,C,D,E,F)
F: B->C, BC->AD, D->E, CF->B. Find the
closure of B.
Solution
The closure for B is as follows −
B+ = {B,C,A,D,E}
4. Consider the given functional dependencies-
AB → CD
AF → D
DE → F
C → G
F → E
G → A
Which of the following options is false?
(A) { CF }+ = { A , C , D , E , F , G }
(B) { BG }+ = { A , B , C , D , G }
(C) { AF }+ = { A , C , D , E , F , G }
(D) { AB }+ = { A , C , D , F ,G }
Contd…
Option-(A):
{ CF }+ = { C , F }
= { C , F , G } ( Using C → G )
= { C , E , F , G } ( Using F → E )
= { A , C , E , E , F } ( Using G → A )
= { A , C , D , E , F , G } ( Using AF → D )
{ BG }+ = { B , G }
= { A , B , G } ( Using G → A )
= { A , B , C , D , G } ( Using AB → CD )
{ AF }+ = { A , F }
= { A , D , F } ( Using AF → D )
= { A , D , E , F } ( Using F → E )
{ AB }+ = { A , B }
= { A , B , C , D } ( Using AB → CD )
= { A , B , C , D , G } ( Using C → G )
Since, our obtained result set is different from
the given result set, so,it means it is not
correctly given.
Thus,
Option (C) and Option (D) are correct.
Finding the no of candidate keys using
closure
Let us take one simple example..
Consider R(A,B,C,D,E) & FD={A->B,D->E}
Sol: consider all attributes and find closure
which is super key.
(ABCDE)+={A,B,C,D,E}
As we know that from the given FD A->B,that
means A derives B,so we can discard B,because
B is derived by A.
Now we get(ACDE)+={ACDEB}
Similarly we can also discard E in above
closure from the FD D->E.
CONTD…
Now we get
(ACD)+={A,C,D,B,E}
We cant discard further the above closure, as
we don’t have any dependencies given.
Now we have to find out the proper subset of
(ACD)+.
(AC)+={A,C,B}
(AD)+={A,D,B,E}
(CD)+={C,D,E}
(A)+={A,B}
(C)+={C}
(D)+={D,E}
Contd..
Since the proper subsets of (ACD)+ are not
having super key ,therefore it is a candidate key.
But we cannot say that only (ACD) is a candidate
key, there can be any number of candidate keys.
Here comes the concept of prime attributes.
Prime attributes are those attributes which are
part of candidate key.
In this example, A,C,D are prime attributes.
Now we need to check whether these prime
attributes (A,C,D) are available in right hand side
of given dependencies.
Since we cannot find A,C,D in right hand side of
dependencies, then only ACD is candidate key for
the given relation.
Example 2:
R(A,B,C,D),FD={A->B,B->C,C->A}
SOL: (A,B,C,D)+={A,B,C,D}
(A,C,D)+={A,C,D,B} (discard B since A->B)
If A->B,B->C THEN A->C
(A,D)+={A,D,B,C} (discard C since A->C)
(A)+={A,B,C}
(D)+={D}
PRIME ATTRIBUTES=(A,D)
Since A is available in right hand side of given
FD’S we can replace A with C from C->A
Now (A,D) becomes (C,D)
Contd..
(C)+={C,A,B}
(D)+={D}
Now prime attributes= C,D
Since C is available in right hand side of given
FD’S we can replace C with B from B->C
Now (C,D) becomes (B,D)
(B)+={B,C,A}
(D)+={D}
Since B is available in right hand side of given
FD’S we can replace B with A from A->B,But as
AD is already a candidate key so we can stop
here.
Total possible Candidate keys are:AD,CD,BD.
Normalization
Normalization is the process of organizing the
data in the database.
Normalization is used to minimize the
redundancy from a relation or set of relations. It
is also used to eliminate the undesirable
characteristics like Insertion, Update and
Deletion Anomalies.
Normalization divides the larger table into the
smaller table and links them using relationship.
The normal form is used to reduce redundancy
from the database table.
Normalization
Here are the most commonly used
normal forms:
9900012222
8123450987
Contd…..
emp_addres
emp_id emp_name emp_mobile
s
1002 Ap Guntur
1004 Ap Guntur
design and
1002 American technical D134 100
support
Purchasing
1002 American departmen D134 600
t
Functional dependencies in the table
above:
emp_id -> emp_nationality
emp_dept -> {dept_type,
dept_no_of_emp}
Candidate key: {emp_id, emp_dept}
The table is not in BCNF as neither
emp_id nor emp_dept alone are keys.
emp_nationality
emp_id table:
emp_nationality
1001 Austrian
1002 American
emp_dept table:
emp_dept dept_type dept_no_of_emp
Production and
D001 200
planning
design and
D134 100
technical support
Purchasing
D134 600
department
emp_dept_mapping table:
emp_id emp_dept
1001 stores
Candidate keys:
For first table: emp_id
For second table: emp_dept
For third table: {emp_id, emp_dept}
EXAMPLE:
Check whether R(A,B,C) is in BCNF or not
using FD’s : A->B,B->C,C->A.
Sol:(ABC)+=(ABC)
A+=(ABC),so A is CK.
C+=(CAB),so C is CK.
B+=(BCA),so B is CK.
Now as per BCNF rule,left hand side of all FD’s
must be a super key.
So,the given relation is in BCNF.
Other kinds of dependencies
Multivalued dependencies
Join dependencies
Inclusion dependencies
Fourth Normal form
For a table to satisfy the fourth normal form,it
should satisfy the following conditions:
[Link] should be in BCNF
[Link] table should not have any multivalued
dependency.
Multivalued dependency
A table is said to have multivalued
dependency,if the following conditions are
true:
[Link] a dependency A->B,if for a single value
of A multiple value of B exists,then the table
may have multivalued dependency.
[Link],a table should have atleast 3 columns
for it to have a multivalued dependency.
3. And for a Relation(A,B,C)If there is a
multivalued dependency between A &B,then
B&C should be independent of each other.
Example
STU_ID COURSE HOBBY
21 COMPUTER DANCING
21 MATH SINGING
34 CHEMISTRY DANCING
74 BIOLOGY CRICKET
59 PHYSICS HOCKEY
Subject Student
C Nav
C++ Siri
Java Balu
Dbms Nag
Se Sam
Oops Aish
Contd…
Then perform natural join operation on these
three tables
Join substu table with Dsub ⋈ Dstu