0% found this document useful (0 votes)
9 views30 pages

Dbms Unit 3 Dbms Unit 3

The document discusses SQL and schema refinement. It provides explanations of DDL, DML, various SQL statements like SELECT, aggregation functions, and triggers. It also defines and provides an example of schema refinement, which is the process of refining a schema to solve problems caused by redundantly storing information.

Uploaded by

maansijanardhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views30 pages

Dbms Unit 3 Dbms Unit 3

The document discusses SQL and schema refinement. It provides explanations of DDL, DML, various SQL statements like SELECT, aggregation functions, and triggers. It also defines and provides an example of schema refinement, which is the process of refining a schema to solve problems caused by redundantly storing information.

Uploaded by

maansijanardhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

lOMoARcPSD|35655477

Dbms unit 3 - Dbms unit 3

jntuh 2-2 sem (Mahatma Gandhi University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Maansi Janardhan ([email protected])
lOMoARcPSD|35655477

Marketed by:

UNIT SQL AND SCHEMA


2
3
REFINEMENT
SIA GROUP

PART-A
SHORT QUESTIONS WITH sOLUTIONS
Q1. Give the basic form of SQL query.
Answer Model Paper-ll, Q1(e)
The basic form of SQL query 1s, e
SELECT (DISTINCT |ALL] column-list
afs
FROM TABLElist
WHERE Condition,
Here, SELECT clause is used to query data from a relation present in a database.
i
FROM clause specifies the list of relations that are to be scanned during the evaluation so as to retrieve the desired data
WHERE clausespecifies conditions based on which resultantrelation is derived
02. Explain about DDL and DML languages. May-17(R15), Q1(b)
OR
What are the SQL statements are used to retrieve and modify the database? April-18(R16), ai(¢)
Refer Only Topic: DML)
OR
Discuss about DDL.
3o eneg
Refer Only Topic: DDL
Answer May-16(R13), a1(a)
DDL

The Data Definition Language (DDL) creates, alters and deletes relations in a database. The DDL commands perform three
operations these are,

1 CREATE
ALTER
3. DROP.
CREATE: CREATE command is used to create a table.
Syntax: CREATE TABLE table_name
2. ALTER: ALTER command is used to modify the structure of the table or view.
Syntax: ALTER TABLE Table_name
a table.
DROP: DROP command is used to destroy or delete
RESTRICT/CASCADE
Syntax: DROP TABLE table_name
The keywords RESTRICT or CASCADE must
always be used with DROP command.

PECTRUM ALL-IN-ONE JOURNAL FOR


ENGINEERING STuDENTS SIA GROUP

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

IJNTU-HYD
MANAGEMENT SYSTEMS SQL and Schema Refinement A
3.2 DATABASE UNT-3 3.3
) NOTIN: The negated versionofIN operatorisNOTN C: AVG followed by a column name returns Q8.
VG the| What is schema refinement?
DML Tt returns a true
value if an element is not in N average value of all the values in the specified column.
a false value. thegiven
Data Manipulation Languages (DML) is used to set. Otherwise, returns MAX: MAX followed by a column name returms the Answer April-18(R16), Q1le)
manipulate data on database using various operations, Example: SELECT E.ename maximum value irom tne vanues present in the ecified Schema refinement is a process of refining
the schema
The SQL statements that are used to retrieve and modity FROM Employee E column. so as to solve the problems caused by redundantly
storing the
database are, followed information. Redundancy in its simplest terms
WHERE E.eid NOT IN MIN: MIN by a column name returns the can be defined as
duplication of data, which is the main cause
SELECT Command: It is considered as the basic SQL minimunum value from the values present in the specified for all the problems
(SELECT D.Dept_managerid that exists in databasc. One way to eliminate
command which is used to retrieve the information or column. the redundant
to select specific columns from the tables. Every SQL FROM Department D data is to make use of decomposition which is the process
of
query starts with the SELECT keyword and is followed WHERE D.DNo -6); 6. Define Trigger and give an example. breaking longer relation into smaller relation schemes.
This
by the list of columns that forms the resulting relation. NoVJDec.18R16),
division into smaller schemes is based on the functional
Answer: Q1C)other dependencies which arespecified by and
The above statement returns a value true for the row that
The basic format of SQL query is, the database designer
contain the names of employees who are not worki. Triggers
Q9.
SELECT select list department number 6,
What is redundancy? Define decomposition.
Atrigger can be dehined as a program that is executed
FROM from_ list Q4. What is meant by nested queries? hv DBMS whenever updations are specified on the database Answer
WHERE condition, May-16(R13), More precisely, it is lIke an event which occurs whenever Redundancy
Answer
INSERTCommand: This command is used to ddd i
Q10
a change 1s done to the tables or columns of the table
Nested Queries Redundancy in its simplest terms can be defined as
information or columm values to a row in a table. Its DBA can specity triggers,
duplication of data, which is the main cause of all problems
A query inside a query 1s called as nested query, Inner that
tsyntax is as follows,
is called as sub query. Sub query is usually present in Example exist in a database. If modification is performed to redundant
uery
INSERTINTOtable_name(columnl, column2, column3,.) data, then it is necessary to perform the same modification
WHERE or HAVING clause. In other words the main query Consider the following trigger description wherein the in
VALUES(valuel, value2, value3, multiple fields of database
that contains the subquery is called as nested query. Trigger"emp-count' counts the number of employees inserted.
INSERT INTO table_name VALUES(valuel, value2, Decomposition
Example CREATE TRIGGER emp-count BEFORE INSERT ON
value3,.)
Find the names of employees who are workingin EMPLOYEE * Event / Decomposition is the solution to the problem caused by
UPDATE Command: This command is used to change data redundancy. It means breaking up the large schema into
or modify the existing column values of a row in a table. department number O. e
DECLARE smaller multiple schemas. It helps to remove all the anomalies
lts syntax is as follows, Solution
Count INTEGER and also helps to maintain data integrity.
UPDATE table _name SET column name SELECT E.Ename BEGIN / Action Q10. Explain what are the problems caused by re-
scalar_expression WHERE condition; FROM Employee E
DELETE Command: This command is used to delete d00e lg END
Count :=0
dundancy.
WHERE E.Eid IN
the existing column values of a row from the table. Its Answer : May-19(R16), Q1(
ESymtax 15 as follows, (SELECT D.Dept Managerid
FROM Department D
on a/ This example clearly explains that the trigger must be
activated before each insertion into the employee table and
The problems caused by redundancy are,
DELETE FROM table_name the
actionto be taken whenever an insertion made. ) Anomalous Updation
WHERE condition; WHERE D.DNo=6) is
07. What is an active database? If update operation is performed, for example,
a3. Explain the following operators in SQL with 95. What are aggregate operators? List the the
Emp Section_ld 268 is updated to 520 and this correction is
examples, different types of aggregate operators. Answer: May-15(R13), a11d) made only to the first record of the database, then this may
() SOME OR lead to inconsistent data, unless all the copies in the database
Active database is a database consisting of set of triggers.
Write down the various aggregate operators are updated. This is referred as update anomalies, The changes
(i) NOT IN. Ihesedatabases are very difficult to be maintained because of
of SQL. must be done to all the copies of data.
Answer: May-19(R16), Q1(d) tnecomplexity that arises in understanding the effect of these
Answer: Nov/Dec.-18(R16), Q10 ggers. In such database, (i) Anomalous Deletion
) SOME: 'SOME' operator is generally used in WHERE DBMS initially verifies whether the
clause for verifying whether the value of a specific col- ABgregate operators (functions) improves the dala
aricular trigger specified in the statement (that modifies the PDelete anomalies refer to the condition whereinsome
it is
umn match with set of values returned by a subuery or retrieval property of SQL statement. These operators en Lbase) is activated or not, prior to executing the stalement. impossible to delete some information without loosing
not the users to summarize the data retrieved from the relano ger iS active then DBMS executes the condition part and
other information. For example, deletion of grade entries
Basically, the aggregate operators takes the entire Co umn o where grade is equal to 4' will delete all the information ot
Syntax: SELECT columnl FROM tablel WHERE data as its argument and generates a result set that mmarizes eXeCutes the action part only the specified conditionis Emp Section 268.
columnl=SOME (SELECT columnl FROM counni rato if
aluated to true. It is possible activate more Id
the column. The following are the different aggregalc to than one trngEC(i)
"somevalue'); within Anomalous Insertion
supported by SQL, 4Single statement. In such situation, DBMS processes
Example: SELECT operatos Ipsertion anomalies refer to the condition where it is
The following are the different aggregale op he trigger randomly. The execution of an action part of compulsory
a trigg
to store some information in addition to some other
at y
FROM Employee E Supported by SQL, erther activate other triggers or the same trigger
retums initialized information. For example, if a new employee record is being
WHERE E.salary SOME (SELECT salary COUNT: COUNT followed by a column nan this action. Such types of trigger that activates
tselfis called entered, who has not yet assigned an Emp id, and an assumption
FROMEmployee E WHERE E.salary> 15000);
The above statement returns a value for the column 2.
the number of tuples in the specified colum
SUM: SUM followed by a column name returns the
sum otas as recursive trigger', The DBMS executes such
ans oftrigger 'rec made that the nulvalues are not allowed, then it is impessible
is
in some pre-defined manner but it efects the to enter the new record unless the new employee has been
containing employee's salary greater than 15000. of all the values in the specified column. pt
SPECTRUM
of understanding
the collection of tiggets assigned an Emp_ ld. This is called as insertion anomalies

Look for the SIA GROUP LOGO


2 on the TITLE coVER before you buy RL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS SIAGROUP

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

IJNTU-HYDERAR
3.4 DATABASE MANAGEMENT SYSTEMS ABAD UNIT-3 sQL and Schema Retinementa AAGA
3.5
Q.Explain transitive dependency with an example. | (iv) With the help of normalization process it is poseik
transform unnormalized table to first normal form
Answer: INF
by removing repeating groups irom unnormalizedtables
tahi

g-i
Transitive Dependency
() Nomalized relations (tables) gives the more simplits
lified
The functional dependency X Yand Y>Zare said to ore compl
result whereas unnormalized reiation gives more o
be transitive dependency if there exist a functional dependeny cated results
X Zvia attribute Y.

Example (vi) Normalized relations bring progress in storage efficieney Key: Super key, A1, 44, Non-key attributes
data integrity and scalability. But unnormalized relation
FDI: Student_ldCourse ld Figure:
Structure of BCNF Relation Indicating its FDs
cannot improve the storage einciency and data integity
FD2:Course ld> Fee (vii) Normalization results in database consistency, flexcibe BCNF is considered to be the most desirable normal form with respect
to redundancy, since it restricts the detection
FD3: Student ld- Fee data accesses. ofredundancy using only the FD information.
The functional dependency FD3 is said to be transitive Q14. What is second normal form? May-16(R13), O a16. What is the difference between 3NF and BCNF?
dependent
OR Answer
Q12. What is normalization? What are the conditionss (Model Paper-l, 91(01 May-17(R13), 0110)
required for a relation to be in 1NF, 2NF? Define SECOND normal form. BCNF 3NF
Answer: (Model Paperd, a1(e) May-19(R16), 01(o)) Answer : May-15(R13), Q1
| Ifa functional dependency
Normalization Second Normal Form (2NF) ABis present,
then BCNF allows this dependency in a relation
Ifa functional dependency 4Bis present, then
3NF allows this dependeney to be in a relation
Normalization is the process of converting a relation A relation is said to be in 2NF if it is in INE and every only if 4' is a candidate key. if
and only if, 'B' is a primary key attribute and '4"is
Toa standard torm by decomposing a larger relation intoon-key attribute is fuly functionally dependent on primar not a candidate key.
smallerefhicient relations that depicts a good database design. key attribute. A relation is said to be in 2NF if any one ofte
Normalization technique involves a sequence of rules that are A relation in BCNF is also in 3NE.
ollowing conditions are satisfied. Arelation in 3NF need not be in BCNE
employed to test individual relations so that the database can
be normalized to any degree. The main objective of normaliza- There should be only one attribute associated with Decomposition of BCNF relations is not possible. It is possible.to decompose any relational schema
tion is to refine the design of database in order to remove data primary key. into a set of 3NF relations, by using decompositions
maintaining anomalies, reduce data redundancy and to that possess certain desirable properties like lossless-
data inconsistency
eliminate2 There must be no non-key attributes in the relation.
Non-key attribute must be functionally dependent on u join, dependency preservation
Conditions to INF
set of primary key attributes i.e., partial dependencies mut n BCNF guarantees that no redundancy can occur There is a possibility of some redundancy to ocCur
Arelation schema is said to be in first
normal form if
the attribute values in the relation are atomic i.e., there
s using only the information about functional because every transitive dependency is not
should Example dependencies eliminated.
be no repeated values in a particufar column.

Conditions to 2NF Consider a simple example of STUDENT relaton


.
Q17.
Define lossless join decomposition with example.
Student (Student ld,Class_ld, Name, Course, Tume Answer
A relation is said to be in 2NE, if the following two May-17(R15), a1(e)
conditions are satisfied, (Student Id, Class ld) is the primarykey: Lossless-join
Decomposition gies pnt a lat if
) Arelation must be in INF Q15. Define BCNF. pertes.
Write prope
down its basic
(i) Anon-key attribute must be fully functionally dependent nonlosssIess-join
decomposition is one of the properties of decompositions. This dependency is also called as nonadditive o
Answer Nov./Dec.-18(R16), 01 jo
n dependency. In a more specific way, lossless-join dependency can be defined as the one which generates noaddiional
on primary key. Fifthe Cn the natural
A relation schema R is said to be in "join" operation is performed on the decomposed relation schemes.
Q13. List the advantages ofnomalized relations over B Example
following statements are true for
each FD P
unnormalized relations.
of FDs that hold over R. Here, P is the subset o attribule hul
Answer of R and O is a single attribute R. onsider a relation, R(M, N, O) and it is decomposed into two subrelations R,CM, N) and R(N,O).
of
The advantages of normalized relations over unnormal- 0) The given FD is a trivial, i.e., QEP
ized relations are, R(M, N, O)
() Normalized relations (tables) does not contain repeating
(i) a
Pis super key.
groups whereas, unnormalized relation (tabie) A
tuple in a BCNF relation is
contains or a relationship, described considercuthe
one or more repeating Broups. by attributes other
The key is used to differentiate
3
(di) Normalized relation cons1sts of aprimary key while there each tuple. R(M, N, O)
can be
is no primary key in unnormalized relation. The structure of such a BCNF
obtained by representing the attributes
relatiore bo
iii) Normalization removesthe repeatnggroup which OCcurs of R asbutes
and drawing arcs between
many times in a table. the key and the R,ON. O)
indicate its FDs. R,M, N)
SPECTR
Look for the SIA GROUP LOGO
on the TITLE COVER before you buy UM ALL-N-ONE JOURNAL FOR ENGINEERING STUDENTS SIA GROUP

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

SYSTEMS (JNTU-HYDERA
RABAD SOL and Schema
Refinement
3.6 DATABASE MANAGEMENT T-3 3.7
The meaning of MVD
Course Student
That is, is, PART-B
There exists a set of students correspondin g to ed
ofdch
a textbook, B, the set ofstudents
ESSAY QUESTIONs wITH SOLUTIONS
R,(M, N) = course Ci.e., for a course C'and
CST depends on the value of C
matching the pair (CB) in
dependencv
only, 3.1 sQL: QUERIES, cONSTRAINTS, TRIGGERS
It is independent of the value A multivalued
B.
can
be defined as: If X,Y,Z are
the attribute sub sets ofattributeset 3.1.1 Form of Basic SQL Query
of
relation 4 then Yis said to be multi-dependent on Xif for ev
RN, O) Ca What is SQL? List the features of SQL.
instance of A, a set of7 values matching a given pair Xvalue,
on
Zvalue) depends only on the X value and does not depend 2 Answer
value. SQL
is a database language which is compatible with RDBMS. It provides an interface to
The condition for lossless decomposition should be, Join Dependeney sOL (Structured Query language)
ale relational database. It 1s a simple portable language that does not require enough learning to work with its syntax and
imp functions
Rbe R-R Ajoin dependency refers to a constraint that is provided mands. It performs the following
Here, the R,b4 R, returns R on a group of relations over a database schema. For instance, a (a)Creates tables and database structures.
table 'S" holds a join dependency relationship if multiple tables
The above decomposition is lossless join decomposition. Performs addition, deletion and modification operations on the database structures
consisting of similar attributes of S" are joined so as to recreate b)
Q18 Mention the properties of decomposition. (c) Performs difficult queries to convert raw data into useful information.
the table S.
Answer Nov/Dec.-18(R16), Q1()
Let M, M, M,...M be a group of relations corresponding All these operations are performed using the concept of DML (Data Manipulation Langunge) and DDL (Data Definition
The two properties of decomposition are as follows,
to a relation M. Here, M is said to have a join dependency
Language).
a) Lossless-Join Property
relationship 1.e., (M,, M, M..M) if the following equation Features
Thisproperty helps to identify any instance of the satishes lor each relation m of the schema M 1.sQL is a non-procedural and English-like langunge containing statements in English
sentences. Hence SQL statements
nginal relation from the corresponding instance of the smaller are easily understandable.
relation attained after decomposition m-Thn(m) ba Tm) ba Ta(m)... Tm)
(b) Dependency Preservation Join dependency is said to be trivial if and only if any
2T minimizes the time required in creating and maintaining the database systems.
This property helps to enforce constraint on smallerof the relations M,, M, M..M, contain all the atributes ot the It is a portable language and can be executed on various computer systems
relation in order to enforce the constraints ou tc g relation schema M4. It gives quick solutions to complex queries.
relation. enables communication between clients and servers over a network
Toanswer the second question a number of normal formsQ20. Describe the inclusion dependencies
5.It
It is also an interactive query language that allows users to store data on adhoc bases.
exists. Every relation schema is in one of these normal forms and Answer : (Model Paper-d, Q1(0 May-16(R13), 010)
I

these nomal forms can help to decide whether to decompose enables programmers to write applications for accessing database.
t
the relation schema further or not Inclusiondependency is a statement containing attribtes 022. Explain about the basic form of a SQL queries.
One of the drawbacks of decomposition is that it enforces and B in X and Y relations respectively such that 4
a4 Answer 1
April-11, Set4, 95(0)
to join the decomposed relations in order to solve the queries dependent attribute and is a subset of B which is its reference
Basicform of SQL
Query
of the original relation. This may result in the performance attribute. Foreign key constraint which allows columns in 0u
The basic structure of an SQL query 15,
degradation if such queries are common. In order to improve relation to refer the columns of a primary key is an example
the perfornmance it is necessary to 1gnore the problems caused inclusion dependency. SELECT [DISTINCT|ALLJ Column-list
by redundancy and decomposition of therelation. FROM TABLE-list
Q19. Define Multivalued dependencies and join WHERE condition:
dependency. April-18(R16), Q1(9
c structure of an SQL query consists of following three clauses
aDOVe
OR
0 SELECT
Write about join dependencies.
Refer Only Topic: Join Dependency
() FROM 9
(ii) WHERE
Answer May-15(R13), 01( 0) SELECT Clause nob
in a database. The result after executing the
SELECT statement
Multivalued Dependencies clause is used to query data from a relation present
is anoth that are desircd
CT

The resultant relation consists of list of columns


MVDs are generalization of functional dependencies be in
ofo be aton which is derived from the relations specified.
in the result
They can be represented as, of a query
DISTINCT is used along
T clause can be followed by two optional
keywords DISTINCT or ALL. If the keyword
Student With the C hand, if keyword ALL is
Course- contain any duplicate rows. On the other
Clause, then the resultant relation doesn't asterisk symbol (") is used to
Course Text book d then ie rows are eliminated from the
resultant relation. Generally,
operations
notellpeciies that duplicate may even include arithmetic
expressions that consists of arithmetic
This is read as "student is multi-dependent on course" x utes of a relation. This clause
or "Course multi-determines
Textbook"
PECTRUM are operating on constant or attributes
ENGINEERING
of tuplesS
STUDENTS
SIA GROUP

Look for the SlA GROUP LOGO on the TITLE COVER before you buy ALLIN-ONE JOURNAL FOR

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

3.8 DATABASE MANAGEMENT


SYSTEMS (JNTU-HYD
DERABAD
UNIT-3 sQL
and Schema
Refinement c A 3.9
Q23. What are the types of languages a manipulations.are applied at internal, conceptual | 1. SELECT Command
) FROM Clause databa
system provides ? Explain. Dauatabases. However, the levelof complexity in- This command is mostly used
xternalomplex low-level procedures allow etncientconsidered as the basic SQL command in SQL queries. It is
t

FROM clause specifies the list of relations that are to OR


U YAL olved
which is used to retrieve
sternal procedures tocus on ease of usage, there the information or to select specific columns from the tables.
Oe scanned during the evaluation process so as to retrieve the
Give an overview ofdatabase languages-D ceess, but e complexity.
desired data. It corresponds to the Cartesian product operatton incurring low Every SQL query starts with the SELECT keyword and is
tn a relational ahgebra. It is followed by table list that speciñes and DML. by
pulation lunguage that involves in retrieval of followed by the list of columns that forms the resulting relation.
the list of tabie names from which data is to be retrieved, 1This April-18(R16), alled "query languageDML
are classified based on Syntax
Answer 03 15 C
table list can in tum be followed by a range variable when the dala constructs.
Database Languages trieval The basic format of SQL query is,
same table-name is used more than once in the table-list the LANGUAGE
DATA MANIPULATION SELECT select list
(i) WHERE Chuse The database languages are called sublanguages
is because they do not have all the facilities of a full-
Thu FROM from_list
cdgel
WHERE clause is used to specify a condition () basedprogramming languages. Several constructs like selectin WHERE condition,
ctionand
onwhich theresultantrelation is derived. This relation contains iterative statements are not available. The sublanguage h NON-PROCEDURAL DML Example
ehasiwa PROCEDURAL DML
only those rows that satisfy the given condition. SQL uses parts,
SELECT Ename, Eid
logical connectives as well as comparison operators in the
Data Definition Language (DDL) Figure: Classification of DML
WHERE clause. The operand of logical connectives are the FROM Employeet g
expressions consisting of comparison operators. 2 Data Manipulation Language (DML). Procedural DML WHERE Esal >20000; i t
()
Examples DATABASE LANGUAGE Using procedural DML the user can specify what data (a) FROM Clause
needs to be retrieved. The user also have to guide as how This clause specifies the names of the tables from which
Consider the following schema, to retrieve the data. data is to be retrieved. FROM is followed by a set of
Employee(Ename, Eid, Esal, Phone, Age, DNo) This means that the user has to express the operations range values which uniquely identifies a table, when its
DATA DEFINITION DATA MANIPULATION name occurs more than once.
Department(Dname, DNa, Dept_Managerid) LANGUAGE thatwould retrieve the desired data. DML initiates by
LANGUAGE evaluating these operations. The result of evaluation is (b) WHERE Clause
Project(PNo, Pname, Pduration, Plocation)
Data definition language is used for designing database again operated until the desired data is etrieved. 1The WHERE keyword is used to specify a condition. All the
DML statements are embedded into high-leve| languages tuples which satisfy the condition are selected.
Query 1 schema. Data manipulation languages are used for queries and
to perform selective and iterative operations
operations like insertions, deletions etc. The various other clauses that can be used in the SELECT
Find distinct names of employee D) Non-procedural DMLs statement are GROUP BY, HAVING, ORDER BY cte.
Data Definition Language (DDL)
SELECT DISTINCT Ename Non-procedural languages are also called declarative ( GROUP BY Clause
Data definition language defines the schema for the de languages. These languages are easy to learn as the
FROM Employee; GROUP BY clause is used to group the data of a table
tabase by specifying entities and the relationship among them user simply needs to express the desired data. It is up to in a single row or column based on the given grouping
lt also says some security constraints. the database system to choose an optimal procedure to
Query 2 condition. It applies some aggregate functions like MAX.
The execution of DDL statements results in new tables retrieve the data. DBMS translates the DML statements MIN, AVG, SUM and COUNT on groups.
Find all the employees who are working in department These tables are stored in "system catalog" also called dan into set of procedures and retrieves the data.
number 7. (d) ORDER BY Clause
dictionary. SQL(Structured Query Language) and QBE (Query By ORDER BY clause is used to retrieve the data ina
SELECT Data dictionary has the information of all the definitios Example) are some of examples of non-procedural DM particular order i.e., either ascending ar descending order
FROM Employee E, Department D of database schema, low-level data structures, files and recors 24. Define data manipulation. Explain command HAVING Clause
()
It also maintains the relationship information among varou used in data manipulation.
WHERE D.DNo 7; HAVING clause is similar to the WHERE clause. It is
reçords. Data dictionary provides faster access to database y
maintaining certain indexes. OR used to pose the conditions on groups. With WHERE
Query 3 clause, conditio are set on rows and with HAVING
Explain various DML function in SQL with
Data dictionary also contains meta data that has u examplesS. clause, conditions are set on groups
Find the names of employees who are working about the data stored in database.
under
Project-number 44 and project-location is either Hyderabad
or
Answer: May-19(R16), Q5(b)Sntax
Bombay. Data definition language allows the user to speciuy
storage and access methods
Data Manipulation SELECT select listL
by using a special languag caled FROM from_list
SELECT E.Ename, D.DNo, P.Plocation, P.PNo data storage and definition Data manipulation is a method of manipulating data on
language. GROUP BY grouping_list
0aabas USing
FROM Employee E, Department D, Project P 2 Data Manipulation Language (DML) various operations. It uses DML for this purpose ORDER BY ordering list
DML
WHERE E.Eid - D.Dept Managerid AND Data manipulation language performs tne HAVING condition
operations, Data Manipulation Language (DML) uses the Example
P.PNo= 44 AND following
0 Insertion of new data mands to perform operations in databases, SELECT Ename, DNo, MAX(Esal)
(PDlocation Hyderabad") SELECT command FROM Employee
() Deletion of stored data
OR INSERT command GROUP BY Ename
(11) Retrieval of stored data UPDATE command ORDER BY Esal DESC
(PPlocation= "Bombay') (iv) Modifying the > 6000;
data. HAVING MAX(Esal)
DELETE command.
Look for the SlA GROUP LOG0
2on the TITLE COVER before you buy
PECTRUM
ALLIN-ONE
JOURNAL FOR ENGINEERING
STUDENT SIA GROUP

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

SYSTEMS IJNTU-HV
HYDERABA
3.10 DATABASE MANAGEMENT
Schema inement
NIT-3 SQL and 3.11
Ifall the information is to be retrieved from a table then its syntax is as 1o NT
various DDL and DML commands.
o26. Explain Nov/Dec.-18(R16), c2(b)
SELECT FROM table: OR
Example Explain DDL commands with
syntaxes.
SELECT FROM Employee: Refer Only Topic: Data Definition Langwage (DDL
INSERT Command Answer Model Paper-, Q6(a)
DEs commandis used to add the infomation or cohumn valves to a row in a table, tts syntax is as follows Definition Language (DDL)
INSERTINTO able name(columnl, column2, column3,..) VALUES(valuel, value2, value3, -
Data
e Data Definition Language (DDL) creates, alters and deletes relations in a database. The DDL performs the following
operatrons,
INSERT INTO table name VALUES(valuel, value2, value3, k
CREA
Example ALTER
INSERTINTO Employee(Eid, Ename, Esal, Age, Phone) VALUESCE-102, David, 28000, 35, 44004400) 2 DROP
3.
INSERT INTO Employee VALUES(E-102, David', 28000, 35, 44004400) CREATE
From the above example, it is observed that at any time only a single row is inserted into the table. This is donee Thetables (or relations) in sQL are created using the CREATE TABLE command.
based
thevalues specified forthe columns. Forinstance, ifthe phone number of an employee is not known and a row is to be add
added Syntax
the table then the insertion can be done in the following two ways, CREATE TABLE table name
0 NSERT INTO EmployeEid, Ename, Beal, Age) VALUES(E-104", "Bechikam', 30000, 32, NULL) (columnl name datatype [NULL |NOT NULL (WITH DEFAULT]| UNIONJ,
) INSERT INTO Employee VALUES(E-104, Bechkam, 30000, 32, NULL); (column2name datatype [NULL|NOT NULL [WITH DEFAULT] | UNION).
While inserting a new row, the following points must be considered, (columnN_name datatype [NULL NOT NULL [WITH DEFAULT]| UNIONJ,
(a) When columns are defined with NOT NULL and DEFAULT option, then they [Primarykey_definition].
shouldn't contain null values
default values must be assigned to them. i [Alternate key_definitions),
b) When columns are defined with NOT NULLoption and values are not specified to them then the INSERT comma Foreign key_definitions);
fails to perform its operation thereby keeping the database unchange. In the definition of CREATE TABLE command, column name is the name of the column, data type is the type of data
fc) When acolumn is not specified with NOT NULL option then a ull value is assigned to it. that the column will hold. The keywords NULL and NOT NULL are optional. These keywords specify the conditions that
must be checked while inserting data into the table.
3. UPDATE Command
If acolumn is specified as NULL then a NULL value.will be inserted in that column ifthe user does not insert value for
Thiscommand is used to change or modify the existing column values of a row in a table. Its that column. If a column is NOT NULL, then the user must specify value for that column otherwise the system does not
syntax is as follows,
UPDATEtable_name SET column_name = scalar_expression WHERE accept that record and returns an eror message. With NOT NULL, two other keywords WITH DEFAULT or UNION can
condition;
Therows that satisfy the condition ofthe WHERE clause updated based also be specified. Both the keywords are optional. If a column is NOT NULL WITH DEFAULT,then the system uses the
All the rows in the table get updated whenever WHERE clause isate on the assignments given in the SET claas: default value for that column if the user does not specify the value. For example, the defauit value for numeric dsta type
not specified. is 0 and for character data type is a space. If a column is specified as NOT NULL UNIQUE then the system does not a-
Example
low the duplicate values for that column. The last three lines in the CREATE TABLE definition specily the primary key.
UPDATE
Employee SET Eid-"E-120 allernate key and the foreign key for the new table.
WHEREAge- 30 EXample

Inthe above example, the Eid of an Employee whose age is 30 is set to 'E-120" he following statement creates a new table named customer,
CREATE Table Customer
DELETE Command
(cid INTEGER NOT NULL
Thiscommand is used to delete the existing column
values of a row from the table. cname CHAR(20).
DELETE FROM table name Its syntax is as follows,
Accno INTEGER:
WHERE condition; fname CHAR(30) NULL,
All rows, which satisfy the condition of WHERE amt REAL NOT NULL WITH DEFAULT,
clause are deleted.
Example Primary key(cid)
DELETE FROM Employee 2 ALTER
WHERE Eid-"E-210; ALTERTABLE
mand is used to modity the structure of the table or
view
Syntax
In the above example, allthe students whose Eid is "E-210' are deleted ALTER TABLE Tablename
Whenever WHERE clause is not specified, all from the Employee table
the rows in a table gets ADD TCOLUMN) Columnname dataly pe
deleted. Its syntax is,
DELETE FROM table name
KOP TCOLUMN) Columnname RESTRICTCASCADE
Example ADD [CONSTRAINT]Constraint name
DELETE FROM Employee; oPTCONSTRAINT] Constraint name RESTRICTCASCADE
In the above example, all rows from the Employee table ALTER (COLUMN) SET DEFAULT Default option)
gets deleted.
ALTER JCOLUMN] DROP DEFAULT)
PECT SIA GROUP
Look for the SiA GROUP LOGO
& on the TITLE COVER
before you buy
u ALL-IN-ONE JOURNAL FOR ENGINEERING STuDENTS

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

3.12 DATABASE MANAGEMENT SYSTEMS


ITU-HYDERABAD
IJNTU-HV.
T.3 SQL
and Schema Refinement a 3.13
Steps for Processing a Query oSe of such annotation is that it specifies the algorithm or index to be used for a specifie
operation. The query
wnAlter command following modification can be done, Following are the steps considered
red while the optim
optimizer
while processing by is supplied as input to the query execution engine that is responsible for evaluating the
(a) Addition of column
1evaluation plan selected
query. evalu Once the querY Is evaluated, the result is returned back to the query
(b) Deletion of column the plan.
Query parsing and translation queryUSin
(C)Addition of constraint 2. Query optimization
Query
(d) Deletion of constraint 3 Query evaluation.
(e) Setting a default value for a column Query Parsing and Translation
Query parsng Parsing and trans lation
( Unsetting a default value for a column. The initial step pertormed during query proces and trans ation
translation. In this, the user-entered query is transla
Example an internal form that is easily understood by the syt
ALTER TABLE Employee purpose of performing translation is that, the querv ente Relational alge bra expression

ADD Project Number INTEGER theuser is in a format which is not understood by the suystem
There are many internal forms of representinga query amon
ALTER TABLE Employee but
these,the most widely used inteTnal representation is dependem Optimizer
Statistics Query
ALTER SEX SET DEFAULT 'M'. on extended relational algebra. database optimzation
3. DROP A software called "Parser is responsible for perfomin
Evaluation plan
Destroying or deleting a table can be done with the
the translation process. This software will carry out the
help following activities,
of DROP command.
Verifies whether the query entered Evahuation engine
Syntax is syntactically
correct. Query
DROP TABLE table name RESTRICT/CASCADE (i) Verifies if the relation name specified in tian
evaluation
the query Output
The keywords RESTRICT or CASCADEmust matches with the name stored in database.
always
be used with DROP command. i) Construct a parse-tree (query-tree) for representing the
query or expression
Exampler a (OvConverts the parse-tree into
using views.
relational algebra expressionQ27.
Figure: Steps for Query Processing
DROP TABLE Department RESTRICT Explain with example the significance of DISTING Keyword
and if views are used then replace these views wih
Thiscommand deletes the department table relational algebra expression defining Answer
someview or integrity constraint is referring to if
it Query Optimization
the view.
otherwise, this command fails. Consider the following three relations.
Query optimization is an essential activity relatio
DROP TABLE Department CASCADE of
DBMS. In this step, the selection an
of efficient query evaluan Employeepll
In this case all views and integrity plan is made. It is the plan consisting
constraint of series of prmive Ename DNo Esal Age
Eid Phone
totherelation 'department' are deleted along referring
with the
operations using which a query can be evaluated.
is done based on the
The Selecu
24578912
table. estimate of cost associated with e 101 John 35000 50
evaluation plan. It is the responsibility
Data Manipulation Language of the system to develo 100 Harry 18000 29 33273120
(DML) a query evaluation plan that
For answer refer Unit-II, Q24.
reduces the cost incurred
evaluating the query. Practically, it is
not
w
possible to estimate n
107 Henry 7 22000 25 55809192
Q26. Define query processing cost ofevery individual 30000 23535135
and briefly explain evaluation plan. Thus, in order to 97 David
a good cost estimate,
the steps involved init. optimizes can use statistical mtot 25000 32 24532121
such as size of the relation, 108 Sam
the index depth. 24578290
OR Ihe relational query languages 102 Henry 22000 35
that a user uses for creuu
Discuss the functionality of query a query
can either be declarative Smith 20000 20 56408489
evaluation or algebraic. Dec 120
engine 1anguages are the languages
that allow the user to speci 18000 24517635
(RferOnb Topie:Orer Evahiution) outcomes should be
does not specify the way,
generated from the query: Howo
operation
Department 122 David 25

Answer May-15(R13), a2(b) for generating the


the system performs
s
desired outcome. Algebraic languag are o elhsbu Dept_Manage DNo Dname Dlocation PNo
Query Processing the languages that the
userhas specified perform algebraic transformatioimizef Administration Hyderabad 44
Query processing i1s a sequential process the desired query optim T08
of retrieving then easily generate languag from
data fron a database based on the input multiple query evaluation Accounts Secunderabad 11
by performing these plans, the plan with pi lected. 101
several operations. The cost of processing a minimum cost can be
query is directly 3. Query Evaluation sci Packaging Bombay 44
proportional to the number of disk accesses. There 100
are many specityimg
strategies (good strategy, bad strategy) that can be During query evaluation 120 Research Nellore 33
processing a complex query. The selection of the best
used for relationalalgebra expression, step, in addition
strategy expressions using it is necessary 97 Accounts Hyderabad 22
is a crucial point and there fore requires significant amount the instructions way of
of evaluating each operation. that deter eferred
time to be spent, even if the query 1s Deing executed once.
only Such an expressio 122 Operation Pune
"evaluation primitive"
Packaging Bangalore 55
Look for thé SlA GROUP LOGO
2on the TITLE COVER
SPECTRU
107

SIA GROUP
before you buy LLIN-ONE JOURNAL FOR ENGINEERING STUDENTS

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

SYSTEMS IJNTU-HY
U-HYDERARA
3.14 DATABASE MANAGEMENT
UNIT-3 SQL and
Schema Refinement BR A3A26 3.15
Project CLname
SELECT
FROM Class Cl
PNo
11
Pname Pduration Project Managerid
9 Months 102
WHERE Cl.room= "R128 o
A
name IN(SELECT Er. Cname FROM Enrolled Er GROUP BY Er. Cname HAVING CoUNT ()>5
22 14 Months 97 St.sname
5
SELECT DISTINT
120
6 Months Student Stolbrt7s
FROM
108 WHERE St.snum IN(SELECT Er,
snum
25 Months
Erz, Cass CI1, Class CI2 WHERE Erl.snum= Er2.snum AND Erl.ename <> Er2.ename
9 Months 107 ROM Enrolled Erl, Enrolled
AND Erl.ename= Cll.name
Query
AND Er2.ename = C12.name AND CI.time #CI2.time)
Select the names and salaries of the employees, whose salary is greater than 20000.
Solution 029, Write queries for the roloWing using the given information,
SELECT DISTINCT E. Ename, E.Esal EmpName DOB DOJ Emp Salary Bonus DOR
FROM Employee E
Buelin 06-12-1983 07-08-2005 15000 600 07-08-2055
WHERE E.Esal> 20000;
The result of this SQL statements is as follows. Andy 12-01-1970 06-12-1973 20000 1200 06-12-2043

Lubber 07-08-1985 12-04-2006 13000 500 12-04-2056


Ename Esal
John 35000 Zobra 08-02-1960 07-03-1982 25000 1500 07-03-2032
Henry 22000 (a) Find total salary of employees from emp table.
David 30000 (b) Find months between employee DOJ and DOR from emp_schema.
(c) Create new salary table using the empname and empsalary from existing table.
Sam 25000 (d) Arrange empnames in ascending and descending order.
Table: Resulit using DISTINCT Keyword
Answer:
The above table does not contain all the tuples whose salary is greater than 20,0O0.
The tuple with Ename "Henryis repeatel () Select sum(EmpSalary) from Emp schema;
twice but is displayed only once. This is due to the use of DISTINCT keyword. (b) Select [(Month(DOR) MonthDOJ) + [(Year(DOR)- Year(DO)]* 12] from Emp_schema;
If this keyword is not used then table is resulted -

t
number of o
conieses
DSNCTkeywordresulted in a row (Henry, 22000) which is repeated twice, This
number of copies of the element is important. For example the
is caled as
stconssting of unordered elements which may consist of manycopies of same elementbut te
muliset d (0)Create table salary as (select EmpName, EmipSalary FROM Emp_schema
Select From Emp_schema ORDER BY EmpName ASC
set (1,2,1,1,) and (2,1,1,1) are same multiset. Both contains thire Seleet from Emp_schema ORDER BY EmpName DESC
copies ofT and only one copy of
2.But the multiset (1,2,2,1) is different. Number of copies of each element is an impon
criteria to differentiate between two multisets.
3.1.2 UNiON, INTERSECT and EXCEPT
Q28. Consider the following relations,
Student(snum: integer, sname: string, major: string, 30. Discuss about set operators with suitable examples.
level: string, age: integer)
Class(name: string, meets at: time, room: string, fid:
integer)
Answer a Model Paper-1, Q6(a)

Erolled(snum: integer, Ename: string) Set Operators


Faculty(fid: integer, fname: string, deptid:
set. Before, using the set operators, it
1s
integer) Det operators merge the result set of two different queries into a single result
Write the following queries in sQL, every column belongs.to same data type
y to ensure that every select statement must have same number of columns and
(i) Find the names of all juniors
(level JR) who are enrolled amily, Following are the
three commonly used set operators in SQ
(ii) Find the age of the oldest student in a class taught by I.teach.
who is either a history major
(i1) Find the names of all classes that or enrolled in a course taught by ) UNION
either meet in a room R128 or
(iv) Find the number of all students who
are enrolled in two
have five or more students e
classes that meet at the same ti
() INTERSECT a git
Answer (i) EXCEPT.
SELECT St.sname April-1, Set3, a7
) 0) UNION
FROM Student St, Class Cl, Enrolled Er, Faculty F SQL, have same
UNION single result set. Though UNION operator in
WHERE St.snum= Er.snum AND Er.ename functiona operator combines two or more result sets into set by merging multiple result sets,
whereas
=Clname AND CI.fid=Ffid AND .level= the former generates a single result
F.fname= I.teach' AND SLC as join operation in relational algebra,
(ii) SELECT MAX (St.age) the latt
are two forms of UNION operator,
Xtends the row horizontally. There
FROM Student St
WHERE St.major= "HISTORY) OR St.snum IN(SELECT Er.
Snum
n UNION [DISTINCT]
FROM Class Cl, Enrolled ER, Faculty F WHERE Er.ename= (6) UNION ALL
1,Teach
Cl.name AND Cl.fid
F.fid AND F.fname SPECTRU SIAGROUP
o Look for the SlA GROUP LOGO on the TITLE COVER
N ALL-IN-ONE JOURNAL FOR ENGINEERING
STUDENTS

before you buy

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

INTU-HYDERAA
MANAGEMENT SYSTEMS IJNTU.
DATABASE Refinement
3.16 and Schema 3,17
G)
INTERSECT r.3 sQL
(a) UNION IDISTINCT EXCEPT Q31. Explain the various set comparison operators
INTERSECToperator combines the rest with examples.
nis operator returns a result set that doesn't confain
any
different queries intoa singie result set that
e e (il) EXCECEPT operator combines the multiple result set
duplicate rows. common in both relations. lains queries into singie
queries si result set that contain the Answer
columns which are INTER tly oftwo dilierent present in the result set of first relation, Du
Syntax operator in SQL 1s Similar to the inner join tched rowS Set Comparison Operators
operator In
SELECTcolumnl,column2, column3... FROM Table lalgebra, but the difference is that the former f
rel set of second latio nis opcrator reon,
15 Similar
is that the EXCEPT Set comparisonoperators are used to perform comparison
UNION [DISTINCT] columns vertically whereas the latter
findea
following are the two forms of INTERSECT operator,
the
e Com
in the
rows er
ot
join" operation but the ditference
vertically whereas the
ontal10fnds matched horizontally. The two forms of EXCEPT
outer join finds between two different SQLqueries. The result of comparison is
ner Irue, False or Unknown. The following are the different
ELECT columnl, column2, column3...FROM Table2 thehed rows
unmatchc set comparison operators supported by SQL,
Example (a) INTERSECT (DISTINCT]
operalorare, IN
SELECT E.ename, D.DNo, D.PNo (b) INTERSECT ALL (a)EXCEPT[DISTINCT)
FROM Employee E, Department D EXCEPT ALL (i) <Comparison operator ANNY
(0) INTERSECT |DISTINCT (6)
(ii) <Comparison operator ALL
WHERE E.eid D. Dept managerid This operator removes duplicate rows from EXCEPT |DISTINCT
AND D.PNo- 44 AND resultset.
rom the
i (o This operator returns a result set that doesn't
contain any (iv) EXISTS.
D.Dlocation-Hyderabad Syntax duplicates. ) IN
UNION DISTINCT SELECT columnl, columnz, column3,.... FROMTA This comparison operator retums a value true if an
Syntax
SELECT El.ename, D1.DNo, DI.PNo element is in the given set, otherwise, returns a value false.
INTERSECT [DISTINCTJ SELECT columnl, column2, column3.. FROM Tablel
FROM Employee El, Department Dl, Example
SELECTcolumnl, column2, column3,... EXCEPT (DISTINCT]
WHERE El.eid DI.Dept managerid FROMT SELECT E.ename
Example SELECT columnl, column2, column3,... FROM Table2
AND DIPNo-44 AND DIDlocation "Bombay' FROM Employee E
Example
The above statement lists the unique names of the SELECT E.ename1oula
i SELECT D.Dname
WHERE E.eid IN (SELECT D.Dept managerid
employees who are working on project number 44 and FROM Employee E FROM Department DWHERE D.DNo-6%
project location is either Hyderabad or Bombuy. yano FROM Department D
WHERE E.DNo-4 Theabove statement returns a value true for the row that
(b)UNON ALL
INTERSECT
WHERE D.PNo44 contains the names of employees who are working in departmient
This UNION operator returns the result set that contains INTERSECT number 6,.
duplicate rows. SELECT El.ename
SELECT D1.Dname The negated version of IN operator is NOT IN. This
Syntax FROMEmployee El FROM Department D operator checks if an element is not present in the given set.
SELECTColumnl, Column2, Column3.FROM Tablel WHERE EI.DNo-6; WHERE D1.PNo 55; Example
UNION ALL The above statement lists the unique names of employes SELECT E.ename
The above statement lists the unique names of department
SELECTColumn1,Column2, Column3.. FROM Table2 who are working for department 4 and 6, that are controlling the project number 44 not project FROM Employee E
Example b) INTERSECT ALL number 55. WHERE E.eid NOT IN (SELECT D.Dept managerid
SELECT E.ename, D.DNo, D.Dlocation (b) EXCEPT ALL FROM Department D
This operator doesn't remove duplicate rows from te
FROM Employee E, Department D final result set. This operator returns a result set that contains duplicate WHERE D.DNo-6)
WHEREE.eid-D.Deptmanagerid AND rows row
Syntax Theabove statement retums a value true for the
D.PNo- 44 AND D.Dlocation="Hyderabad SELECT columnl, column2, column3.. FROM1N
Syntax that contain the names of employees who are not working in
UNION ALL SELECTcolumnl, column2, column3,. FROM Tablel department number 6.
INTERSECTALL <Comparison Operator ANY
SELECT El.ename, DI.DNo, DI.PNo EXCEPT ALL (i)
FROM Employee El, Department DI
SELECT column1, column2, column3... FROM TaNe
SELECT column1, column2, column3.. FROM Table2 This operator returns the value true if there is atleast one
Example record that satisties the given condition, otherwise, returns talse.
WHERE El.eid-DI.Dept managerid Example
SELECT E.ename Example
AND DI.PNo 44 AND D.Dlocation SELECT D. Dname
Bombay'; FROM Employee E SELECT E.ename
The above statement lists all the names FROM Department D
(including duplicate names) who are working of employee FROM Employee E
on project number WHERE E.DNo- WHERE
44 and project location is either Hyderabad or Bombay. 4 D.PNo-44 WHERE E.Esab ANY (SELECTEL.esal
INTERSECT ALL EXCEPT ALL
UNION operators are generally used FROM Employee El
in many data SELECT DI.Dname
warehouse applications because. the relations SELEC. 21.ename WHERE El.ename Henry');
in
applications are not perfectiy normalized. This operator these FROMEmployee FROM Department DI example, El.esal is calculated for the subquery
guarantee the order of rows (1.e., rows doesn't El In this
of second relation may WHERE D1.PNo are compared with E.esal. The tupie
WHERE EI.DNo= 6; 55 and all the tuples retrieved
appear before the rows of first relation). However,
if specific al employe heabove statement lists all the departments (including which returms true is the desired result
E.esa> ANY returms falsec
greater than that
order is to be followed then ORDER BY clause can be The above statement lists all the names
oing are no such employees whose salary is
used duplicate departments) that are controlling the project there
if Henry
with UNION operator. (ancluding duplicate names) who are
imber 44 not project number 55. of
department 4 and 6.
ALL-HN-ONE JOURNAL FOR ENGINEERING STUDENTS
SIAGROUP
Look for the SIA GROUP LOGo RGM
on the TITLE COVER
before you buy

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

3.18 DATABASE MANAGEMENT SYSTEMS IJNTU-HYDe.


DERABA Refinement
SQL and Schema 3.19
UNIT-3
(i) <Comparison Operator>ALL Explain the following operators s
insOL Kecution of this nested subquery is done in It is a simple nested sub-query that is moved directly
into
examples, the FROM clause of outer relation. lf a nested sub-query cannot
This operator returns the value false, if their is atleast manner
one record that doesn't satisfy the condition. Otherwise, a value () sOME following
executed first, move to the "FROM" clause, thern in such situation, a temporary
inner guery
The
1s
relation is created that maintains the information aboutthe result
true is returned. (1) IN
D.Dept Managerid generated after processing a nested query without selection. This
Example (il) EXCEPT SELECT
Department D Subquery relation is created using correlation variable from the outer level
(iv) UNION. FROM
query Then, this relation is combined with outer level query
SELECT E.ename D.DNo-6
WHERE
Answer April-18(R16), using join operation. Consider the following instance of query
FROM Employee E
sOME Q This quuery
retrieves the Dept_Managerid of all the SELECT
WHERE E.esal > ALL (SELECT E2. esal
SOME' operator is generally used in WHERE Claemployees wnose DNo 6.
=
FROM T,
FROM Employee for verifying whether the value ot a specific column Ca
nnatchw
Next, the DBMS checks the presence of If, resultant value
it exist then
WHERE E2.ename = Henry ) set of values returned by a subuery or not. of Dept Managerid in employee table. Ename). WHEREC,AND EXISTS(Select FROMT, WHERE C)J
it displays the result for that id (i.e., the
In this example, E2.esal is calculated for the subquery and Syntax, In the above query, C, is a conjunction of simple
SELECT columnl FROM tablel WHERE The main query that contains the sub queries in called predicates and can be rewritten a5,
all the tuples retrieved are compared with E.esal. If the salary columnl
Outer query
of alltheemployees named 'Henry' is greater than Eesal, then SOME (SELECT columnl FROM columnlsom s
The IN keyword can also be replaced with NOT IN
CREATE TABLE Tab1 As
a value tnue is returned, otherwise value faise is returned. Example word, In this case, it checks for the tuples which are not SELECT DISTINCT Att
(iv) EXISTS SELECT gresent in the given relation. Example: Find the employee who
FROM C,
EXISTS operator is a test for checking whether the set of FROM Employee E arenot working in dept number 6,
tuples satistying the conditions 1S not nulL. The opetator returnsS
a valuetrue only if the evaluating subquery is non-empty (i.e,
WHERE E.salary SOME
(SELECT salary
Employee E WHERE E.salary> 15000);
FROM
Employee E
SELECTE.Ename
FROM SELECT
WHERE C ro s
il the subquery retuns at least one row that is not null and E.Eid NOT IN (SELECT
WHERE
The above statement returns a value for the columa FROM C, Tabl
that satisfies the given condition). OtherwISe, a value talse 1s
containing employee's salary greater than 15000. D.Dept Managerid FROM
returned. WHERE C, AND C
() IN Department D WHERED.DNo 6);
Example
Foranswer refer Unit-1I1, Q31, Topic: IN. 034, With an example, explain the optimization of Here. ch consists of predicate in C, without the selection
SELECT E.ename consisting of correlation variable and Credefines selection
(ii) EXCEPT nested sub-queries.
FROM Employee E with correlation variable. "At" specifies all attribute used in
For answer refer Unit-IlI, Q30, Topic: EXCEPT Answer a

selection consisting of correlation variable.


WHERE EXISTS (SELECT (iv) EXISTS Optimization of Nested Sub-queries
Nested sub-queries are placed under theWHERE"
Query(9,) can be transformed to,
FROM Department D Foranswer refer Unit-III, Q31, Topic: EXISTS. clause in the form
of parameterized function, which returns a CREATE TABLE Tabl AS
WHERE D.DNo=6 AND (9UNION single value or set of values. Basically, the parameters passed
withinthe functions are the variables (correlation variable)
SELECT DISTINCT sid
D.Dept managerid E.eid); For answer refer Unit-II, Q30, Topie: UNION.
derived from the outer level query. The evaluation of nested FROM Reserves
The above statement returns a value true for the
tuples which satisfies the condition D.DNo= set of 3.1.3 Nested Queries, Aggregation guery I5 done by
initially computing the cross product in SELECT sid
6 AND D.Dept Operators the outer "FROM" clause. After computing the product,
managerid-E.eid is not empty. FROM Sailor, Tabl
epredicates in the "WHERE" clause are tested for every
Q33. What is a nested query? Explain with an examp
Thenegated version of EXISTS operator is vidual tuple in the resultant product. Such way of evaluating WHERE Tabl.sid Sailor.sid;
EXISTS", thatchecks whether "NOTAnswer:
the set of tuples which satishes Model Paperl, Q6 y
consisting of nested sub-query is referred to as corelated
the condition is empty Nested Oueries Q35. Write the following queries in SQL using nested
Nested
ethicient
aion.
The drawback of this evaluation technique is tha
as more disk input/output are required. 1his is queries concept for the following schema,
Example A query imside a query is called as nested query. because,
query
is called as sub query. Sub query is usually presen very Cvery
sub-query is evaluated separately by consideringB Sailors(sid: integer, sname: string, rating: inte-
In the above example, "NOT EXISTS" operator retrievesWHERE tuple in the outer
or HAVING clause. In other words the main y level querY ger, age: real)
the set of tuple for which a value true is returned an
i.e., the nameshat contains the subquery is called
as nested query. atc
lherefore, to overcome this issue, SQLuses optimizer Boats(bid: integer, bname: string, color: string)
of employees who are not working in department number 6. Example sub-queries into joins wherever it is possible
Q32. Explain the following operators
loperfo
Posgibls
cd
n conversion. In situation where conversion is not Reserves(sid: integer, bid: integer, day: date)
in SQL with Find the names of employees who are wo vorking
() Find the names of sailors who have re
sub-query
examples, department number 6. eparafe ev optimizer maintains each of the
() sOME Solution One expression and then optimizes each query separateiy. served both red and green boat
PerformSub-query is optimized, correlation evaluation 1s re-
SELECT E.Ename
performed
so (i) Find the names of sailors who have
() IN Example as to evaluate the sub-queries.
FROM Employee Edwp served all boats.
(n EXCEPT have not
WHERE E.Eid IN Consider the following query (9) (il) Find the names of sailors who
(iv) EXISTS. May-17(R15), Q4(b) (SELECT D.Dept Managerid SELECT reserved red boat.
sid better than
OR FROM DepartmentD FROM (iv) Find sailors whose rating is
Sailor, Reserves
WHERE D.DNo WHERE Sailor.sid Reserves.sid, some sailor called Raghu.
6);
Look for the SIA GROUP LOGO
WECTRUM
STUDENTs
SIA GROUP
on the TITLE COVER before you buy HLLIN-ONE JOURNAL FOR ENGINEERING

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

U-HYDERABAD
3.20 DATABASE MANAGEMENT SYSTEMS IJNTU-HYn Scherme Refinement
UNIT-3 sQL
and 3.21
Answer April-11,
Set1.
aregate operators does SQL support? Explain with examples.
a37.
() SELECT S.sname emApil-18(R16), Q4(b)
Answer
FROM Sailors S, Reserves R, Boats B
Operators
Aggregafe
Onerators (functions) improves the data retrieval property of SQL statement. These opetators enables the users to
WHERE S.sid R.sid AND ABPdata retrieved from the relations, BasIcally, the aggregate operators takes the entire column of data ás its argument
aummarize result set that summarizes the column. The following are the diferent aggregate operators supported
R.bid-B.bid AND generales a resuit by SQL,
and COUNT
B.color "Red' AND I.
S.sid IN(SELBCT S2.sid FROM Sailors $2, Boats B2, Reserves R2 WHERE S2.sid = R2.sid AND 2
SUM
R2.bid-B2.bid AND B2.color "green')% AVG
() SELECT S.sname MAX
FROM Sailors S
4.

5. MIN.
elre
WHERE NOT EXISTS(SELECT B.bid FROM Boats B WHERE NOT EXISTS (SELECT R.bid FROM Rese cOUNT
WHERE R.bid- B.bid AND R.sid- S.sid); es R
coUNT followed by a column name returns the number of tuples in the specified column. If DISTINCT keyword is used
(ii) SELECT S.sname only the count value of unique tuples otherwise it will return count value of all tuples (including duplicates)
will return
hen it
FROM Sailors S Syntax

WHERE S.sid NOT IN (SELECT R.sid FROM Reserves R WHERE R.bid IN SELECTCOUNT ([DISTINCT] column-name)
(SELECT B.bid FROM Boats
WHERE B.color "red'); B FROM table-name
(iv) SELECT Ssid WHERE cOndition;

FROM Sailors S Example

WHERE S.rating > ANY (SELECT S2.rating FROM Count the number of ditferent employee names,
Sailos $2 WHERE S2.sname ="raghu');
Q36. What is correlated SELECT COUNT (DISTINCT E.empname)
nested query? Explain with an example. FROM Employee E;
Answer:
April-11, Sot-1, 07 2 SUM
Correlated Nested Query
SUM followed by a column name returns the sum of all the values in the specified column. If DISTINCT keyword is used
lf there is a relationship between outer query and
sub query then such queries are said to be
correlated nested queries.
then it will
in the
return the sum ofall unique values in the columns otherwise, it will retum the sum of all values (including duplicates)
columns.
Example
Syntax
Find the names of employees who are working
in department number 6. SELECT SUM [DISTINCT] Column_name
SELECT E.cname
FROM table_name
FROM Employee E WHERE condition;
WHERE EXISTS(SELECT Example

FROM DEPARTMENTD Find the sum of salaries of all the employees.


WHERE D.DNo-6 AND SELECT SUM(E.esal)

D.Dept_Managerid-E.eid); FROM Employee E;


EXISTS is a setcomparison operator AVG
which checkswhether theset is not
name, EXIST operator checks
whether the set of tuples which satisfies null(non empty). In this exampie,10 AVG
suscd then itfollowed by a column name returns the average value of allthe values in the specified colunin. IfDISTINCT keyword
E.eid is not empty. the resulting set is not
If
the condition D.DNo 6 AND
empty that means some Employee E D.Dept_Managc erid will return average
the ues only
of distinct valucs
sub query is dependent on the outer query. is working in department number 6.
Here, ntax
That is
condition is checked for cach row of the Employee. cach tuple.of department is dependent on tuple of Employee. The spec
Thus, the statement.
&eitte
SELECT AVG ( [DISTINCT] column-name)
D.Dept Managerid E.cid indicates
the corelation and hence termed FROM
as correlated query. table-name
If NOT EXISTS is used, then the names of Employees WHERE condition
who are not working in department
In addition to EXISTS, NOT EXISTS keywords number 6 are displayed Example
the user can even use another
This operator is used to eliminate the duplicate rows set-comparison operator called NIQUE
query then it ensures that all the retrieved rows are
(1.e., the rows that appear more
than once) when UNIQUE 1s b ind the average age of all employees,
in the table.
unique. Similarly NOT UNIQUE
operator
useoate SELECT
returms true if there are uu AVG (E.age)
FROM
Employee E
Look for the SIA GROUP LOGO
on the TITLE COVER before you buy
SPECTR
ALL-IN-ONE JOURNAL FOR ENGINEERING
STaDENTS SIA GROUP

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

DATABASE MANAGEMENT
SYSTEMS JNTU-HYs
3.22 Schema Refinement
INIT-3 sQL and 3.23
MAX value from the values
present in the ecified
maximum Q40. Consider the following schema,
column name returns the column Syntax
A Tollowed by a . Sailors(sid, sname, rating, age)
Syntax SELECT coll, col2,
SELECT MAX (column-name) Boat(bid, bname, bcolor)
FROM Table name(s)
FROM table-name Reserves(bid, sid, day
WHERE condition; WHEREcondition1, condition2,. Write the following queries in SQL
Example (GROUP BY coll, col2, Find pf 10.
the average age of sailors with a rating
Find the name and age of eldest-employee,
ORDER BY coll, col2 [ASC/DESC]];:
SELECT E.empname, E.age () Find the name and age of the oldest sailor.
FROM Employee E Example () Count the number of sailors
E2)%
WHERE E.age- (SELECT MAX (E2.age) FROM Employee SELECT Emp name, MAX(Emp salary) (iv) Count the number of different sailor names
MIN (V) Find the names of sailors who are older
FROM Employee
MIN followed by a column name returns the minimum value from the values present in the specified column. than the oldest sailor with a rating of 10.
Syntax GROUP BY Emp name (v) Find the age of the youngest sailor for each
SELECTMIN (column_name) rating level.
ORDER BY Emp _salary DESC;
FROM table_name (vii) Find the age of the youngest sailor who
WHERE Condition; The query determines the maximum salary among all the is eligible to vote (i.e., is at least 18 years
Example employees and groups them based on employee name. The result old) for each rating level with at least two
Find the name and age of youngest employ is listed by Emp_salary in descending order such sailors.
SELECTE.empname, E.age HAVING Clause (vii) For each red boat, find the number of res
ervations for this boat
FROM Employee E HAVING" clause is an extension of GROUP BBY (ix) Find the average age of sailors for each
WHERE Eage (SELECT MIN(El.age) FROM Employee,
El); clause and is similar to "WHERE" clause. The difference rating level that has at least two sailors.
Q38. Compare nested query and correlated query. Discuss suitable examples. between HAVING and WHERE Clauses is that, the former póse
restrictions on the output of GROUP BY clause, whereas the x) Find the average age of sailors who are
Answer latter sets restriction on columns and expression for individual
of voting age(i.e., at least 18 years old)
AprilMay-12, Set4,Ca
rows i.e., "Having is used to eliminate groups and "where is for each rating level that has at least two
Nested Query sailors.
Correlated Query used to eliminate rows. The "Having clause is always used in
1n nested query inner queries are not dependent on 1
conjunction with the GROUP BY' clause. (xi) Find the average age of sailors who are of
In correlated query
Outer once.
inner queries are dependent on oute voting age(i.e., at least 18 years old) for
once. Syntax t least two such
each rating level thatha
inner query 1s executed first.
2. sailors.
If consume less time.
Outer query is evaluated first. e SELECT coll, col2,
3. It consume more time. (xii) Find those ratings for which the average
FROM Table_names) age of sailors is the minimum over all rat
It issimple. 4. It is relatively complex. ings.
Inner query is executed only once [WHERE conditionl, condition2,
S.Innerquery is executed for every tuple presentin [GROUP BY coll, col2,
Answer
outer query SELECT AVG (Sage)
It does not effect the system performance.
6. t effects the performance of the system highly. HAVING conditionl, condition2, FROM Sailors S
It is casy to understand.
7 It is relatively.difficult to understand. [ORDER BY coll, col2, LASCDESC]: WHERES.rating=10
Example SELECT S.sname, MAX (S.age)
Example i)
For answer refer Unit-I, Q33, Topic: Example Example
FROM Sailors S
For answer refer Unit-11I, Q36, Topic: Example SELECT Emp name, MAX[Emp_salary] COUNT ()
Q39. What is the usage of (ii) SELECT
'group by' and "having'
clauses in SQL? FROM Employee FROM Sailors S;
Answer :
May-15(R13) 0 SELECT COUNT (DISTINCT S.sname)
GROUP BY Clause GROUP BY Emp name
FROM Sailors S
GROUP BY clause is a clause used HAVING MAX (Emp_salary)> 10000 SELECT
1or grouping the S.sname
This clause is defined within the SELECT dataoftable in a single
statement and is row/column based on someB ORDER BY Emp salary DESC; FROM Sailors S
with aggregate functions. Howe fagre
functions are not used then execution used in conjunction
S.age> (SELECT MAX ($2.agc)
can be said that a GROUP BY clause 1s
of GROUP BY clause
generates "not a GROUP rwords The above query determines the maximum salary among
WHERE
valid only ifused in combination
easily creating frequency distributions within
the SELECT statement
BY expression ero
with aggregate functions. GROUrD laus
help
se mployees
salary
and group them using Emp_name only if the
respective employee is greater than 10000. Finally,
FROM Sailors $2
WHERE S2.rating= 10)
o
e heresult
t is listed by Emp_salary in descending order:
Look for the SIA GROUP LOGO
on the TITLE COVER before.you buy
SPECTR
ALL-IN-ONE JoURNAL FOR ENGINEERING
STUDENTS SIA GROUP

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

SYSTEMS (JNTU-HYDER
DERABAD
3.24 DATABASE MANAGEMENT Schema finement
INIT-3 SOL and
| Q41. Consider the following relations, 3.25
e Know that ratings are integers in the range to
we could write 10 queries of the fom:
1
10,

Student(snum: integer, sname: string 3.1.4 NULL Values


major
SELECT MIN (S.age) string, level: string, age: integer)
FROM What are null values ? Explain how comparison is done using null values.
Sailors S 24.
Class(name: string, meets_at: time, room
WHERE S.ratingi Answer t Model Paper-4, Q6(b)
string, fid: integer) Values
Dr Null
Enrolled(snum: integer, cname: string sall values are those values wnich are as51gned to an attribute if its value is unknown or is not applicable. These
values
SELECT [DISTINCT] select-list DBMS
useuue
when the user does not know the type ot intormation to be entered for a
particular field. When the user doesn't
FROM from-list Faculty(fid: integer, fname: string, der are
for a field then uppercase DBMS assigns a NULL value to that field. A NULIL value does not
represent a zero or
WHERE qualification
Integer) es it just means the absence of value for that field and this value can be inserted later.

GROUP BY grouping-l1st Write the following queries in SQL Example


In the employee
e table it is not necessary that all the employees should have a phone number, so
HAVING group-qualification; (0) Find the names of students not enrolledin for the employer who
a phone number, a NULL value can be assigned. Whep a tuple (124, 'Kelly", 6, NULL, 26, NULL) inserted
(vil) SELECT S.rating, MIN (S.age) As minage any class. s not 1ave is in
nployee table then for the attrbutes e.sal and phone NULL values are assigned. Assignment of NULL value simply indicates that
FROM Sailors S dhe value is not known or is inapplicable for that attribute. A feld which is not declared as NOT NULL can have NULL values.
(11) Find the names of students enrolled in
WHERES.age> 18 the NULL values are used to deal with the exceptional data or the data that is not complete. Any operation performed on null values
maximum number of classes. mayresult into inconsistent data, due to wmch usage of null values are not preferred in relation. a
GROUP BY S.ating
(il) Print the level and the average age Comparison using NULL Values
HAVING COUNT ()>1 of
students for that level, for each level It is difficult to pertorm comparison of valid values with NULL values if two valued Logic - TRUE or FALSE is used.
(vill) SELECT B.bid, COUNT ()AS sailorcount -
Therefore to avoid this issues three valucd logic TRUE, FALSE or UNKNOWN must be used with NULL value. For example
FROM Boats B, Reserves R
(iv) Print the level and the average age of the
students for that level, for all levels except JR
ifaNULL value is entered for salary attribute of Kelly and
is specified. Then the evaluation of
20000
if

a
condition that queries to list all the employees whosé salary>
this condition for Kelly is UNKNOWN because salary is a NULL value for Kelly
WHERE R.bid-B.bid AND B.color 'red' operators (,
Similarly, for other comparison ),the evaluation of the condition will always be unknown.
GROUP BY B.bid: nswer April-11, 8et-2, Q7()
SQL provides IS NULL, 1s NOT NOLL comparison operators to compare the NULL values i.e., to test whether a value is
(ix) SELECT S.rating. AVG (S.age) AS average () SELECT DISTINCT S.sname NULL or not. 1f isNULLoperator js applied to salary attribute then "TRUE value is returned which specifies that esal attribute
a null value, And 18 NOT NOULL'operator is applied to same attribute, then FALSE value returmed.
FROM Sailors S FROM Student S
is if is
GROUP BY S.rating 043. Explain in detail about logical connectives AND, OR and NOT.
WHERE S.snum NOT IN (SELECT E.snum FROM
Answer
deb HAVING COUNT (")> 1;
Enrolled E); Logical connectives with NULL values must be defined using three valued logic wherein expressions evaluates to three
(x) SELECT S.rating, AVG (S.age) AS average
values .e..
to TRUE, FALSE or Unknown). For example consider the following query
FROM
(i) SELECT DISTINCT S.sname
Sailors S
Examples
WHERE S.age>-18 FROM Student S
List all the employees whose age is less than 40 whose salary is greater than 730000
GROUP BY S.rating WHERE S.snum IN (SELECT ELSnum SELECT
HAVINGI(SELECT COUNT () FROM Employee E
FROM Enrolled El
FROM Sailors $2 WHERE E.agec40 AND E.esal>30000;
WHERE S.rating-S2.rating); GROUP BY EL.snum All the tuples that satisfy this condition are selected but what about the tuple consisting of esal as NULL value. In this
case, this,
condition will evaluate to unknown Logical operators which involves at least one column whose value is assgned as
(xi) SELECT S.rating, AVG (S.age) AS average HAVING COUNT (")> a
NULL will always
result in an unknown value. The following table will give better understanding of logical operalons when
FROM Sailors S ALL (SELECT COUNT () Used with null values,
WHERE S.age> 18
FROM Enrolled E2 Operation Result and Reason
GROUP BY S.rating
GROUP BY E2.snum); () XANDY TRUE If both X and Y are true
HAVING 1< (SELECT COUNT (")
(i) SELECT S.level, AVG (S.age)rt FALSE If either X or Y is false
FROM Sailors $2
If either X or Y is unknown (null values)
WHERE S.rating $2.rating AND S2.age18) FROM Student S UNKNOWN
(xil) SELECT S.rating
U (i) XORY TRUE If either of them (X or Y) is true
GROUP BY S.level;
FALSE If either of them is false
FROM Sailors S (Gv) SELECT S.level, AVG (S.age) If one of the argument is false and other is unknown
WHERE AVG (S.age)- (SELECT MIN UNKNOWN
(AVG (S2.age)) FROM Student S (ii) NOTX TRUE IfX isisfalse
FROM Sailors $2 WHERE Slevel< 1fX true
JR FALSE
GROUP BY $2.rating) UNKNOWN IfX is unknown
GROUPBY S.level;
Look for the SIA GROUP PE STUDENTS SIAGROUP
LOGOon the TTLE COVER
before you buy TRGM ALL-IN-ONE JoURNAL FOR ENGINEERING

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

UNTU-HY
MANAGEMENT SYSTEMS DERABAD
DATABASE
3 SQL and Schema Refinement uMapR 3.27
3.26 UNI
on SQL construc 3.1.5
44. Explain briefly the impact of null values Complex Integrity Constraints in SQL

Answer values.
understand the impact of NULL values on these complex integrity constraints in SQL triggers.
boolean expression are usedin SQL,
it is necessary to iscuss about
Q46. Disc
May-13(RD9), 04(b)

any
constructs.
SQu
OR
Consider the following Student Relation Explain various Domain constraints in SQL with examples.
Class Group
Student_id Std name Course id (Refer Only Topic: Defining Domain
Constrain)
01 May-19(R16), O4b)
102 NULL Answer
A Complex Integrity Constraint in SQL
101
Integrity constraints can be applied on single columns, and also on group of tables (called assertions). This
section provides
103 NULL following features on diferent integrity constraints that can be applied on table or group of tabies
e
1.Constraints Applied on Single Table with Check Option
104
102 B on
Constraints that are applied on a single table are called "table constraints' and can be applied the table with the help
105 NULL dheck option. Constraint is a condition that must be satisfied by a table and check option is used to check that condition. For
G an employee
Example example, if we want to make sure that all the employee's salary must be greater than 15000 but less than 40000 is
lation, we can insert this condition at the time of creation of employee table. We may write as, 74.
List all the names of students who belongs to group "B.
SELECT
FROM Student S
CREATE TABLE Employeefeid INT NUT NULL,
ename CHAR(20) NOT NULL,
.
DNo INT NOT NULL,
WHERE S.Group- B:
This solution will result in the set of tuples that satisfies the WHERE' condition and all other tuples that does not satit esal DECIMAL(10,2).
thiscondition are ignored. In addition to these tuples. the tuples with NULL values are also ignored (eliminated) because for thes eage INT NOT NULL,
tuplesthe condition evaluates to false or unknown. Thus elimination of rows that resulted to unknown, (have significant impact Phone CHAR(18).
onthe queries, specially the nested queries consisting of) EXlSTS or UNIQUE keywords. PRIMARY KEY(eid),
We know that the comparison of any two fields with mull values for equality is an unknown value. But when it comes te
FOREIGN KEY(GNo) REFERENCES Department (DNo)
equality operator, the two null valueattributes are treated as equal.Ifafield contains two null values then that is considered a
duplicate values. Two tuples are said to be duplicates if they hold the same value or if they hold the null values. So, the compariss CHECK (esal >15000 AND esal 40000) s
When new tuple, are inserted into the table, the check condition is evaluated. Ifit returns true then the row inserted clse
ofNULLvalues with the=" operator always results in TRUE. is

The result of all the arithmetic operators (t,- ,") results in an unknown value (NULL) if any one of the argument it is rejected
is a NULL value. Similarly with all the aggregate operators the result is NULL if these operators are applied to a NULL value Defining Domain Constraint
Aggregate fanctions simply delete the NULL values and then returns the result of aggregate addition to this, we can even restrict
COUNT(DISTINÇT) simply delete/ignore the NULL values and returms the result
operator i.e., SUM, AVG, MIN, MAX, New domains can be defined in SQL, by using the statement CREATE DOMAIN. In
range of values that these new
aggregate operator
of other NOT NULL tuples. Only exceptian the valuesof new domains by using check option. This means that it is possible to specify the
in is count(") which does not ignore/delete. The NULL values, it counts them and then return the number o domains can take. The syntax for creating a new domain is,
tLupies in the table.
CREATE DOMAIN Domain-name Source domain (Default valuc)
Q45. Write short notes on disallowing of null values.
CHECK (VALUE)
Answer: new domain.
Create Domain: A statement or a key word used to define a
The insertion of NUlLL values for a field can be restricted by specifying the
fielddefinities. This implies that the field cannot take null values. For the primary NOT NULL constraint within the
resp
Domain Name: Name of the new domain
key field it is nmandatory to include NO new domain is derived.
It is constraint as these fields are not allowed to consider null values. Source Domain Name: Name of the source domain from which
Basically, the NOT NULL constraints impuicil
specifies for every primary key field Default Value: We can also provide default values for the domains.
which a new domain is specified). This option
Example Check: The option is used to restrict the values in the particular field (for
CREATE TABLE Sudent provides a condition that must be checked by all the tuples of the
column.

(Sid INT NOT NULL Value: This keyword is used to provide a value to a domain variable.
Sname CHAR(10) NOT NULL, Or example, we can create a new domain for salary
by stating these SQL statements
CREATE DOMAIN salary DECIMAL DEFAULT 15000.00
Project VARCHAR(15), l CHECK(VALUE>= 1So00.00 AND VALUE 40000.00)
Class INT
has to be refered it indicaies
is decimal. Now whenever the salary domain
PRIMARY KEY(eid); Salary' is the new domain whose source domain
Values allowed for this domain is of decimal type.
In the above example, Sid is the prinary key hence it must indicales value will be R IS000.00
be unique and it should be NOT NULL. Project did not enter the salary, then the default
the project taken up by the student This theld can take NULL values as it ing a Defult value for salary is 15000.00 i.e., if the usgr thuat all the inserted must
This stalement ia used to check
project/not yet assigned a project. However. t this held is not allowed
is possible that a student not interested im
is
to take NULL values, then the NOT NULL cOsu t u HECK (VALUE> 15000.00 AND VALUE40000.00).
be specified within the field. have a
valuc specified in this range.
SIAGROUP
Look for the SIA GROUP LOGO ECTRUM ALL-IN-ONE JouRNAL FOR ENGINEERING SYUDEits
2 on the TITLE COVER
before you buy

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

MANAGEMENT SYSTEMS IJNTU-Hy


3.28
DATABASE RABAD
MIT-3 SOL and Schema
Refinement aAATG 3.29
3. Defining Constraints Over Several Table: Assertions applied. Unlike table constraints which are
are applied Example
group tables on which a constraints
are onsinge
re of CREATETABLE STUDENT(
table, assertions are applied on multiple tables.
as department manager and project manager
mana
INTEGER NUT NULL,
of employees working must std id
example, consider that the total number be
exactly 20, then the following condition can be enforced, VARCHAR2(50),
std name
CREATE TABLE Dept_manager
std_address VARCHAR2(50),
(eid INTEGER
ename CHAR(10), cONSTRAINT student_ pk PRIMARY KEY (std id) s bet
dNo INTEGER Tn the above example, std id is the primary key. If the user inserts repeated values for "std id" then error occurs and
esal DECIMAL(10,2) straint name is returned indicating violation of constraint.
cage INTEGER,
Forelgn Key Constraint
Phone CHAR(8)
PRIMARY KEY (eid), It is used to determine any column that references the PRIMARY KEY in the other table. It generates a relationship
CHECK (esal >15000.00 AND esal 40000.00) hetween two columns residing in tne same table or between distinct tables. Inorder to define a column as a foreign key,
should be a primary key in the table to which it refers.
it
CHECK (SELECT COUNT(E.eid) FROM employee E)
+(SELECT COUNT (D.dept managerid) FROM Department D) Syntax
+(SELECT cOUNT (PProject managerid) FROM PROJECT P) <20) CREATE TABLE table_name
his SQL statements provides us with the solutionbutthe disadvantage of this solution is that it involves only emplo (coll datatype NULLNOT NULL
e whereas both department and project table must also be involved equally. It is a complicated way of writing the lements
lo enlorce the condition. Mone simpler way is to create assertions of these three tables as shown below
col2 datatype NULL/NOT NULL,
CREATE ASSERTION Total
CHECK (SELECT COUNT (E.eid) FROM employee E)
+ (SELECT COUNT (D.Dept managerid) FROM
Department D)
+(SELECT cOUNT (P.Project _managerid) FROM Project P) < 20) coln datatype NULL/NOT NULL,
With assertions we are required to only specify the conditions
that must be applied on group of tables. cONSTRAINT k_col
947. What are integrity constraints ? Define the terms
primary key constrains and foreign key constraints. FOREIGN KEY (coll, col2, .coln)
How are these expressed in SQL?
Answer REFERENCES primarykey _table (coll, col2,. coln)
Integrity Constraints May-17(R15), Q50)

Integrity constraint is a mechanism in which


certain rules are imposed on column Example
enteringinvalid data. or on table to prevent users from
The various types of integrity constraints Syntax for applying foreign key is as follows,
available in PlLSQL are,
1. PRIMARY KEY constraint
CREATE TABLE Department(Dname CHAR(30),
2. FOREIGN KEY constraint
DNO INTEGER, Manager_id INTEGER,
3. NOT NULL comstraint
4. UNIQUE constraint PRIMARY KEY (DNo, Manager id),
S. CHECK constraint. FOREIGN KEY (Manager_ id) REFERENCES (Employee);
PRIMARY KEY Constraint
The statement FOREIGN KEY (Manager_id) REFERENCES Employee- means
It is used to define a column or group that the "Manager id
Syntax
ofcolumns that can distinctively
identify every row in the table
ss primary id "Eid" of employee relation as a reference. Every tuple with Manager must match
relation. id
foreign
a
key

tuple in employee
CREATETABLE table_name
048. Explain
(coll datatype NULL/NOT about the following,
NULL
col2 datatype NULL/NOT NULL, (a) Domain relational calculus
col3 datatype NULL/NOT NULL, (b) Specifying foreign key constrains in SQL with an example.
Answer.
t jNow./Dec.18R18), Q04

cONSTRAINT const_name Domain Relational Caleulus


PRIMARY KEY
(coll, col2,. coln). or answer refer
(column_namel, column_name2, Unit-11, Q27, Topic: Domain Relational Calculus (DRC)
)
Here, coll, col2, col3 represents
the column name Specifying Foreign Key Constrains in Sol
that defines the
primary key. Or answer refer Unit-11, Q47, Topic: Foreign Key Constraint.
Look for the SIA GROUP s
LOGO
on the TITLE COVER
before you buy RGM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS SIA GROUP

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

NTU-HYDERABAD Refinement 1
SYSTEMS IJNTU-HV SQL and Schema 3.31
DATABASE MANAGEMENT T-3
UNIT
3.30
SQL
S.sname FROM Sailors S, Reserves R1, Boats B1, Reserves R2, Boats
Q49. B82
Consider the following relations, CT S.sna
SELECT
RI.bid B .bid
Sailors (sid, sname, rating, age) WHERE S.sid= RI.sid AND
Boats (bid, bname, color) AND Ssid= R2.sid AND R2.bid B2.bid
Reserves (sid, bid. sday BI.color Red' AND B2.color "Green';
Relational Calculus, Domain Relational Calculue
AND
Write the statements in Relational Algebra, s andSQ have Reserved a Red or a White Boat
Names of Sailors who
for the following questions. d)
Relational Algebra
Find the names of sailors who have reserved a Red boat.
(a)
Boats) Reserves)
Find the names of sailors who have reserved at least
(6)
one boat (Tempred, t,(oRe
and a Green boat. pCTempwhite, Ta ((otr -Wha Boats) a Reserves)
(C) Find the names of sailors who have reserved a Red
Tempwhite) ba Sailors))
(d) Find the names of sailors who have reserved a Red or
a White boat. TTempred u
(e) Find the names of sailors who have reserved all boats. Relational Calculus
Nov./Dec.-18R16), IN 3Se Sailors (Re Reserves (S.sid = R.sida 3Be Boats (B.bid- R.bid (B.color="Red" vB.color-"White"))
Answer 08
(a) Names of Sailors who have Reserved a Red Boat Domain Relational Calculus
Relational Algebra (N)131,T, A (1, N, T,A) E Sailors A34, Br, D) e Reserves n (Br, BN, 'Red', 'Green ) e Boats))
TC(-Boats) Reserves Sailors) sQL
Relational Calculus SELECT S.sname FROM Sailor S, Boats B,
Reserves R p
For answer refer Unit-II, Q300). WHERE S.sid R.sid AND R.bid=B.bid
Domain Relational Calculus AND (B.color- "Red' OR B.color="White');
KON)13L TA(LN, TA) e Sailors A 3 (d, Br, D) e Reserves A 3 (Br, BN, 'Red) e Boats)) (e) Names of Sailors who have Reserved All Boats
sQL Relational Algebra
SELECT S.sname FROM Sailors S, Reserves R, Boats B p(Tempsid, (Tab Reserves)T, Boats)) TTempsids pe Sailors)
WHERE S.sid= R.sid Relational Calculus
AND Rbid-B.bid AND B.color="Red'; For answer refer Unit-, Q30(iv).
(b) Names of Sailors who have Reserved at least One Boat Domain Relational Calculus
Relational Algebra (N)131, T, A (T, N, T, A) Sailors A V B, BN AC ((B, BN, C) E Boats) v dr, Br. D) e Reserves
Sailors e Reserves) 1=IRA Br= B))}
Relational Caleulus SQL

For answer refer Unit-1, Q30). SELECT S.sname


Domain Relational Calculus FROM Sailors S
(0N011TA(G. N, T, A) e Sailors ^ 2 (dr, Br, D) e Reserves)) WHERE NOT EXISTS (SELECT B.bid FROM Boats B)
sQL gbtt EXCEPT (SELECT R.bid FROM Reserves R WHERE R.sid= S.sid):
SELECT S.sname FROM Sailors S, Reserves R and Active Databases
WHERE S.sid-R.sid;
3.1.6 Triggers
April-11, Set-3, Q7[b)
) Names of Sailors who have Reserved a Red 60. What is a trigger and what are its 3 parts? Explain in detail.
and a Green Boat OR
Relational Algebra
SQL
P(lempred, T ( Boats) ba Reserves)) What is trigger? Explain how to implement triggers in
(Model Paper4, Q7(a) ] April-18(R16, 05a))
Answer:
P(lempgreen, T ((-Boats) « Reserves)) Irigger
T(Tempred n Tempgreen) a Sailors))
updations are specified on the database tables.
Relational Calculus a program that is executed by DBMS whenever
Bger can be defined as which or columns of the tables. Only DBA can
occurs whenever a change is done to the tabies
Mone
(N 3Se Sailors A(S.sname= N.sname A ERe Reserves (S.sid-R.sid n SDeciisely, it is like an event
R.bid) specify triggers.
3Be Boats (B.color"Red" A B.D

3Se Sailors (S.sname=N.sname A 3Re Reserves ne general format of the trigger includes the following
(S.sid = R.sid A 3Be Boats (B.color="Green R.bid)) (a)
Domain Relational Calculus A B.D Event
(6)
e
N)131 T, A (1, N, T,A) SailorsA3 Bri, Br2, DI, D2 e Reserves
a (Br2, BN, Green) e Boats n Brl ((Brl, BN, 'Red)e Boats
Condition
# Br2))
SPECT
() Action. SIA GROUP
ALL-IN-ONE JouRNAL FOR ENGINEERING STUDEN
Look for the SlA GROUP LOGO
2 on the TITLE CoVER
before you buy

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

SYSTEMS (JNTU-HYDERA Refinement


DATABASE MANAGEMENT ERABAD UNIT-3 SQL and Schema 3.33
3.32
Explain about
assertions.
(a) Event a51.
lead to the activation of trigger. The followingf
wing fall under
Event describes the modifications done to the database which the Answer
category of events. Assertions
may activate the trigger. va refers to a constraint defined over a single/multiple tables. The syntax of an assertion is as follows,
(a) Inserting, updating, deleting columns of the tables or rows of tables An assertion

(0) Creating, altering or dropping any database object may also lead to activation of triggers. w CREATE ASSERTION <asser name> CHECK pred_condition)

)An error message or user log-on or log-off may also activate the triggèr. elere Here, the CHECK command restrict only limited data values
to be entered into the database. Example,

CREATE ASSERTION ABC CHECK ((SELECT CoUNT (e.empid) FROM Employee


e)+
(b) Condition
Conditions are used to specify whether the particular action must be performed or not. If the condition is evaluated tootrue (SELECT COUNT (p.pid) FROM project p)< 100);
then the respective action is taken otherwise the action is rejected. ensures that the number of employees plus the number of projects are less then 100
The above query constraint
(c) Action all times, an assertion should be satisfied. But, if it is not satisfied then an error message is generated by the DBMS.
At
Action describes the step to be taken when the corresponding event occurs and the condiion evaluates to true. It is Typically, when an assertion is employed over the table, it is tested again and again
on each update for ensuring the validity
collection of SQL statements that are executed as a part of trigger activation. O overhead and also consumes a lot
sothat no one çan violate the assertion. This testing may however result in a large amount of
It is possible to activate the trigger before the event or after the event. cost and time. Hence, assertions are said to be very complex and sophisticated.
of
the assertion is required since it is useful in identifying the constraints/
For example, consider the following trigger description wherein the trigger "emp-count" counts the number of employesy Inorder to modify/delete an assertion, the name of query that is useful
implementation of assertions is done by creatinga
inserted. conditions defined by the assertion over the tables. The

n a particular constraint. This query is now inserted in a clause called NOT


EXISTS. This
for retrieving tuple values, which violate
CREATE TRIGGER emp-count BEFORE INSERT ON EMPLoYEE/ Event
Tse clause specify that the result of the query must generate a null value. Thus, when
a
the result is not null value, the assertion is said
DECLARE to be violated.
Count INTEGER
BEGIN Example
Action
Count0 CREATE ASSERTION Emp
END dAaals CHECK (NOT EXISTS

Thisexample clearly explains that the trigger must be activated before each insertion into the employee table SELECT
and the action
to be taken whenever an insertion is made. FROM Employee, Department
AND employee.sal<35000):
This was an example showing. The activation of trigger before the event. WHERE employee.ename Department.mgrmame
slrsjintltin as well as department tables are done only if the
Now, consider this example, which shows the trigger activation after the event, The above query ensures that the insertions/updations to the employee
CREATE TRIGGER count-emp AFTER INSERT ON EMPLOYEE salary is less than 35000.
/ Event /
WHEN (ew.salhry< 20000)
Q52. Define active database. Also, list the uses of triggers.
Condition OR
FOR EACH ROW

BEGIN Pole MO GWhat is an active database? Explain. AprilMay-12, Set-4, Q3(b


Count:-Count+ 1;
Answer
Action u bet
END T418e Pe Active
Databases maintained because
triggers. These databases are very dificult to be
Actuve database is a database consisting of set of whether the
In this example, trigger count-emp is activated understanding the effect of these triggers. In such database, DBMS initially verifies
after the insertion of new record and the complexity that arises in the statement. If
modifies the database) is activated or not, prior to
executing
then the action is executed. if condition evaluates to t
trigger specified in the statement (that
Cular condition part and then executes the action part
only if the speciñed condition 1s
There are two types of triggers. They are, gger 15 active then DBMS executes the
one trigger within a single statement. In
such situation, DBMS processes
to true. It is possible to activate more than trigger that
auated an part of a trigger may either activate other
triggers or the same
(a) Row-level trigger randomly. The execution of action executes such chains
the this action. Such types of trigger that activates itself is called as 'recursive trigger'. The DBMS
(b) Statement-level. zed
ger in pre-defined manner but it effects the
some
concept of understanding the collection of triggers
(a) Row-Level Triggers Uses of
Triggers
in the database. Whenever a change (updates, insert or
delete) is done n
Row-level triggers are the triggers that run for each row
of the table that is affected by the ggers are used to maintain the data integrity
change. There are several uses of
triggers.
event of triggers s, a trigger can be used to indicate that
(b) Statement-Level Triggers
integrity.
Statement-level triggers are the triggers that are executed aTriggers can be used to maintain data a database
only once for multiple rows
which are affected trigger acu used to identify the unusual events that occurs in
0) Triggers can be
In the example described previously, the emp-count is a statement-level trigger les security checks and also for auditing
as it is activated for multiple rows of lhe ) Triggers can be used for
whereas count-emp is a row-level tngger because t 1s actvated for each row
of the table where salary is greater than 20000 Topic: Trigger.
remaining answer refer Unit-11, Q50,
FO SIA GROUP
ENGINEERING STUDENTS
Look for the SlA GROUP LOGO on the TITLE CcoVER RUM ALLIN-ONE JOuRNAL FOR
before you buy

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

SYSTEMS [JNTU-HYDERABAN
(JNTu-HYDe AGAag
3.34
DATABASE MANAGEMENT
T.3 sQL and
UNIT
Schema Refinement 4 3.35
how does it address
What is decomposition and
To answer the first question following two propertiesof
3.2 sCHEMA REFINEMENT A5,
a55. ndancy? Discuss the problems that may be decompositions are considered,n jo
decompositions.
Decompositions, Problems Relateta to caused by the use of (a) Lossless-Join Property t odhA
3.2.1. Problems Caused by Redundancy,
Decomposition AprilUMay-12, Set-2, Q5 This property helps to identify any instance of the
original relation from the corresponding instance of the smaller
refinement? Explain how it can be accomplished? OR
What do you mean by schema relation atained after decom position, a e
(Model Paper-|l, Q7(@) | April-18(R16),
Answer o Explai the problem related to decomposition. (b) Dependeney Preservatio
database. The specihcations tor database schema is provi
rovided
A schema can be defined as a complete description of d Relatedto Decompsotion) This property helps to enforce constraint on smaller
frequently. Schema rehnement iS a process of refining the sche ing (Refer Only Topic: Problems
he database design and this schema does not change information. Redundancy in its simplest terms can be defined ac duplicati
d May-15(R13),
relation in order to enforce the constraints on the original
SOve the problems caused by redundantly storing the Answer : a7(D)relation.
OL data, which is main cause for all the problems which exists in database. One way to eiminate the redundant data ic
small e Decomposition To answer the secondquestion a number of normal forms
o decomposition, which is the process of dividing longer relation into smaller relations. This division into smaller schemes exi relation schema is in one of these normal forms and
on the functional and other depondencies which are specified by the database designer. Decomposition is the solution to the problem caused by
oscd
Schema diagram for employee database is as follows, redundancy. It decomposes the large schema into smaller
ese normal torms can helportonotdecide whether to decompose
schema further
all the anomalies andneretation
data
Employee (Emp_ ld, Emp Section Id, Emp_Name, Job Section, Girade) multiple schemas. It nejps in removing
maintains data integrIy. It is poSSiole to restrict the
redundancy Oneof the drawbacks ofdecomposition isthat it enforces
Emp Name Emp Section_ld Job Section Grade by dividing it into two smaller relations/ to join the decomposed relations in order to sofve the queries
Emp Id in Employee database
of the original relation. This may result in the performance
0012 Ravi Clerk schemas aS follows. degradation if such queries are common. In order to improve
0013 Nandan 268 Manager Emp_Id Emp_ Name Job_SectionGrade the performance it Is necessary to ignore the problems caused
0013 Nandan 268 Manager Ravi Clerk by redundancy and decomposition of the relation
0012
0013 Nandan 268 Manager Manager 3.2.2 Reasoning about Functional
0013 Nandan
0014 Kumar 314 Secretary Dependencies
0013 Nandan Manager
0016 Teja 059 Asst. Manager Manager
Q56. Explain functional dependency with an example.
0013 Nandan
0012 Ravi 124 Clerk B Answer AprilMay-11, Set-3, Q2(a)
0014 Kumar Secretary
Consider the above database. The tuple Emp
ld 0013 repeats the same name and same Job-Section îhformation multiple
time. This repetition wastes space as well as causes data inconsistency which 0016 Teja Asst. Manager D Functional Dependency (FD)
inturn leads to loss of data integrity, For example
anupdate operation on a new record for an employee with ld 0013 has to be done Clerk A functional dependency is defined as the relationship
storesthe employces details.
times i.e., it must be done for each file which 0012 Ravi
between the attributes that correspond to a single relation. in
Q54. What is redundancy? What are the different CTION
problems encountered by redundancy? Explain them. a given table, if X and Y are two attributes of a relation and
OR Emp_ Section _ld Grade the value of X is used to detemine the value of then the
Y

What are the problems caused by redundancy attribute Y is said to be functionally dèpendent on the attnbute
and decomposition of relation? 124
(ReferOnly Topics: Problems Caused by Redundancy, X-and
Problems Caused by Decomposition) A. Dragrammatically, a functional dependency between
Answer 268 A
Y attributes can be shOwn as,
Redundancy nislaxplaesd yApril-18(R16), Q6)
314 B
Redundancy can be defined as duplication XY
of data which is the main cause for 059 D
modification is performed to redundant all the problems existing in a datab ase. If
data, then it is necessary to perform the Example
same modification in multiple fields or daa database
Problems Caused by Redundancy Now it is easily possible to update Emp Section ld in
Emp_1d
the schema SECTION without bothering about the updations Consider the relation EMPLOYEE in which
) Anomalous Updation
If update operation is perforned, for example, the To insert a new tuple, directly insert the new and Social Security Number are the two attributes. Here,
Emp Section ld 268 is updated therin thetuples.
to the first record of the database, then
this may lead to inconsistent to 520 and this correction 1s Tna only
Tesord schema SECTION (with the help of Section
evenifthe new employee has not yet been assigned the Emp ldthe value of Social Security Number is used to deter
This is referred as update anomalies. The
changes must be done to all
data, unless all the copies
in the database a
the entry with the grade equal to 'A', directly delete
ldthe value of Emp. ld then Emp_ld is said to
be functionay

This dependency can


i) Anomalous Deletion the copies of data. te
IromS schema, which doesn't lead to loss of other
dependent on Social Security Number.
Delete anomalies reler to the condition
wheren it is impossible to delete
inf 1ON decomposition eliminates the problems be diagrammatically shown
as
information. For example, deletion some information without loosing meCmD on a Thus,
of gradec entries where
grade is equal to s Caused by difierent anomalies. Emp ld- Social Security Number
Section ld 268, A' will delete all the informaton f Emp.
Functional dependency is used in DBMS the
Problems Related to Decomposition for
(ii) Anomalous Insertion
Insertion anomalies refer to the condition reasons,
where 1t is compulsory to Droktne use of decomposition may lead to various following
information. For example, if a new store some information in some other lem the use of legal.
is made that the null values are not
employeerecord is being
entered, who has no1 yet addition mption decon nerefore one should be more careful with order
To determine whether the relations are
allowed, then 1t 15 impossible
been assigned an Emp ld. This 1s called as insertion
anomalies
to enter the new
assigned an Emp jd, and an
record unless the new cup
aee has 0to Use
sition. The questions that must be answered
decomposition are,
in
2 To deñne a set of constraints on the relations.

convert the relatos


Problems Caused by Decomposition (a) To normalize the relations so as to
what problems can be caused by using decomposition
Wh 3.
ver refer Unit-11, 955, Topic: Problems into standard form.
Related to Decompositionha
When to decompose a relation?
SIA GROUP
0Look for the SIA GROUP LOGO on the TITLE COVER MD P di ALL-IN-ONE JOURNAL FOR
ENGINEERING STUDENTS
before youbuy

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

INTU-HYDERABAD
MANAGEMENT SYSTEMS JNTU-H Refinem
DATABASE
3.36 SQL and Schema
UNIT 3.37
CloSur
sure
Q57. Write short notes on, Artribute ABC-ABCDE
(b) no ecessay to compute F in order to
(a) Closure of a set of FDs It is always ABD>ABCDE
dependency, A4 B, 1s in the closure of set
(b) Attribute closure. fnd out whether a ABE-ABCDE
OR findo Another
Another method is to compute the attribute closure A*
FDs. ACD-ABCDE
set of functional dependencies. Explain
in computing of dependeney
the given Attribute wn tespect to " (set of functional
is meant by closure of F? WhereF is the
e
nat
Fwith suitable examples. depender closure can be deinedas a set consisting ACEABCDE
(ReferOnly Tople: Closure ofa Set of FDS) attributes X such that XA can be computed using the
to compute attribute closure ADE->ABCDE
May-15(R13, 01rong axioms. The algonthm
Answer as folloWs. BCD->ABCDE
(a) of a set A 1s
Closure of a Set of FDs
all the FDS that satisfy all the dependencie ClosureA BDE->ABCDE
is represented as F and is defined as collection of
closure of a set of FDs de-
he
OT the given set of FDs. In order to compute the closure of agiven set F of FD'S ATmsrongs Axioms are used. The fa while (No change) CDE->ABCDE
are the three rules which are collectively known as Armstrongs axioms. A, B, and C are used to denote the set of attri ttribulesove g
a relation R. ABCD-ABCDE
if(K L in F &&KE Closure)
(a) Refexivity: If A2B, thenA>B ABCEABCDE
Closure = Closure UL,
6) Augmentation: If4B, then 4CBC for any C ABDE>ABCDE
(C) Transitivity: If A > B and BC, then AC ACDE->ABCDE
Armstrongs axioms are said to be complete because all the FDs in closure are computed by the repeated appli This algorithm can be changed so as to find other keys
o1 all these rules. They are "sound" because they do not generate wrong dependencies instead they generate only depende by initially considering
the set A'with single attribute and then BCDE->ABCDE
which are in the closure of P continuing until the closure set containing all the attributes in The candidate keys are A, E, CD, and BC.
in addition to the above rules some other rules are also applied the relation schema are found.
Q59. Determine the closure of the following set of
a) Union: 1f AB 4CthenA
and > BC Q58. Compute the closure of the following set of functional dependencies for a relation scheme.
(b) Decomposition: If A BC, then A >B and A>C functional dependencies for a relation scheme. R(A, B, C, D, E, F, G, H),
(C) Pscudotransitivity: IfA> B and CB D then AC>D RIA,B,C, D,E), F= {A BC,CD E,B-D,E-A)
Example keys of R.
F {ABC, BDEF, ADG, A H)
List out the candidate
SALE (product, date, customer, vendor, street). May-17(R15), Q6(b)
Listthe candidate keys of R. May-19(R16), Q6(b)
Answer: OR
Now, the schema for this particular relation can be represented as PDCVs which implies the
sale of product with production Given that,
(P)on date "D to the customer (C) is done by the vendor (), who resides in the street Compute the closure of the following set of
(3).
A->BC, B>D, So A->D and similarly A->DC->E
Thefollowing functional dependencies hold, functionaldependencies for a relation scheme.
FDI The product Id Pis a key. All the attributes are dependent on key. Therefore AABCDE R(A, B, C, D, E, F, G, H), F= {AB C, BD EF,
P->PDCVS Since E>A, A >ABCDE, So E->ABCDE
ADG, A H). List the candidate keys of R.
FD2- Avendorpurcháses a en p ona single date. Since CD>E, so CD->ABCDE Answer (April-18(R16), Q7(a) | May-17(R15), Q7(b))
VP->D Given relation schema 15,
Since B->D, BC->CD, So BC->ABCDE
FD3- The customer purchases alimost one product from the vendor.
Attribute closure: FA, B, C, D, E, F, G, H)
VC-P
FD4-Every vendor is associated wíth their own street. A->ABCDE Set of functional dependencies
V>S B-BD F-(4BC, BD EF, AD G.4H as
FDS Every product belongs to one of the vendor. The closure of set of functional dependencies P is
PV D->D tAA follows,
In addition to these FDs, several other FDs also hold AH
in the closure of given FDs. E->ABCDE A
From FD5, FD4 and transifivity rule, we get,
AB->ABCDE B-B
FD6: P-S
From FD4 snd augmentation rule, we get, AC-ABCDE C-C
FD7: VP-PS AD->ABCDE D-D
AE-ABcDE
From FD7, PD2 and transitivity rule, we ge,
FD&: VP- PDS BC-ABCDE
EE
From FD3, PDI and transitivíty rule, we get,
F--F
BD-BD
FD9: VC-PDCYS BEABCDE
G-G
Decomposition can be applted s0 as fo compute many H-H
other FD's ike, CDABCDE ABABCH
From PDS and deconposition, folowing FD's are obtained.
CE-ABCDE
P-DP-P,P-9 C,P-Y.P-9S, ACACH
Look for the SlA GROUP LOGo
sPECTRO
DE-ABCDE
ALLAN-OME JOURMAL FOR
EMGINEERIHG STODENTS sA GROUP
2on the TITLE CoVER before you buy uM

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

3.38 DATABASE MANAGEMENT


SYSTEMS [JNTU-HYDERABAD)
wasQL and Schema Refinement M 32aATAG 3.39
UNIT-
ABDGABCDEFGH BDEFH ACDEFACDEFGH ABCDGH-ABCDEFGH
AD ADGH BCPBCP BDFH-
ABDH- ABCDEFGH BDGHBDEFGH ACDEGACDEGH
AEAEH BCG- BCG ABCEFG ABCEFGH
ABEF ABCEFH BEFGBEFG ACDEH ACDEGH
AFAFH BCH- BCH ABCEFHABCEFH
BDEBDEF ABEGABCEGH BEFHBEFH ACDFG-ACDFGH
AGAGH ABCEGH ABCEGH
BDEF .ABEH ABCEH BEGHBEGH ACDFHACDFGH
AHAH BDF
BC BC BDGBDEFG ABFG ABCFGH ng BFGH BFGH ACDGH ACDGH
ABCFGHABCFGH

BDH BDEFH ABFH ABCFH CDEF ACEFG ACEFG ABDEFGABCDEFGH


BDBDEF CDEF
ABGHABCGH CDEG ACEFHACEFH ABDEFH ABCDEFGH
BE BE BEFBEF CDEG
BF- BF BEG BEG ACDE CDEGH CDEHCDEH ACEGHACEGH ABDEGH-BCDEPGH
BGBG BEHBEH ACDP CDFGH CDFGCDFG ACFGHACFGH ABCFGHABCFGH
BH BH BFG BFG ACDGACDGH CDFHCDFH ADEFGADEFGH ABDFGH-ABCDEFGH
CDCD BFH-BFH ACDHACDGH CDGHCDGH ADEFH-ADEFGH ABDEFGABCDEPGH
CECE BGH-BGH ACEFACEFH CEFG CEFG ADEGHADEGH
ABDEFH ABCDEFGH
CFCF CDE CDE ACEGACEGH CFGHCFGH ADFGHADFGH
CGCG s CDF-CDF ACEHACEH AEFGHAEFGH ABEPGH-ABCEFGH
DEFGDEFG
CHCH CDGCDG
tte ate jotACFGACFGH 20 DEFHDEFH BCDEFBCDEF ACDEFG-4CDEFGH
ABCABCH CDHCDH 1d6a BCDEG BCDEFG ACDEFHACDEFGH
d3:040PHACHHa DEGH DEGH
ABDABCDEFGH CEFCEF eACGHACGHso1eil DFGH DFGH BCDEH BCDEFH ACDEGH ACDEGH
ABE ABCEH CEG CEG )Y- ADEF ADEFGH c EFGH EFGH BCDFGBCDEFG ACDFGHACDFGH
ABF ABCFH CEHCEH BCDFH
ADEG ADEGH ABCDEABCDEFGH BCDEPHol ACEFGHACEFGH
ABGABCGH CFGCFG ADEH ADEGH ABCDF ABCDEFGH diBCDGH BCDEFGH
ADEFGH ADEFGH
ABH-ABCH CFHCFFG ADFGADFGH T ABCDGABCDEFGH BCEGH BCEGH
ACDACDGH CGH CGH ADFGADFGH ABCDHABCDEFGH us BCFGH BCFGHls BCDEFG-BCDEFG
ACE ACEH DEFDEF BDEFG BDEFG Insa BCDEFHBCDEFG
ADFHADFGH
n ABCEFABCEFHal
ACFACFH DEGDEG ADGHADGH ABCEGABCEGH BDEFH BDEFH BCDEGHBCDEFGH
ACG ACGH DEH DEH ABCEHABCEHn BDEGH BDEFGH
AEFGAEFGH'A l BCDFGHBCDEFGH
ACHACH DFG DFG AEFH-AEFH ABCFGABCFG BDFGH BDEFGH
BCEFGH BCEFGH
ADEADGH DFH DFH ABCFHABCFH BEFGH BEFGH
AEGHAEGH BDEFGH BDEFGH
ADFADFGH DGHDGH ABCGH ABCFH CDEFG CDEFG
AFGHAFGH
ADGADGH EFG EFG CDEFH CDEFH
CDEFGHCDEFGH
BCDFBCDEF ABDEFABCDEFGH.
ADHADGH EFH ABCDEFGABCDEFGH
EFH BCDG BCDEFG
ABDEGABCDEFGH CDEGHCDEGH
AEFAEFH EGHEGH ABDEHABCDEFGH CDFGHCDFGH ABCDEFHABCDEFGH
BCDH BCDEFH
AEG AEGH FGH FGH ABDFGABCDEFGH CEFGH CEFGH ABCDFGHABCDEFGH
BCFGBCFG
AEH AEH ABCDABCDEFGH ABDFHABCDEFGH DEFGHDEFGH ABCEFGHABCEFGH
BCFH- BCFH
AFGAFGH ABDEABCDEFGH ABDGHABCDEFGH ABCDEFABCDEFGH
AFH AFH
BCGHBCGH
ABEFG ABCDEGABCDEFGH
e ABDEFGHABCDEFGH
ABCFABCFH ABCEFGH
BDEF BDEF tc ACDEFGHACDEFGH
AGHAGH ABCGABCGH
BDEG BDEFG
ABEFHABCEFHM
ee ABCDEH-ABCDEFGH
BCDEFGH-BCDEFGHp
BCDBCDEF
BCE BCE
ABCHABCH
ABDFABCDEFGH
BDEH BDEFH
ABEGHABCEGHadte
ABFGH ABCFGH
r ABCDFG
ABCDFH
ABCDEFGH
ABCDEFGH
ABCDEFGH-ABCDEFGH.
BDFGBDEFG
LL-IN-ONE JOURNAL FOR ENGINEERING
STUDENTS SIA GROUP
2
Look for the SIA GROUP LOGO 2on the TITLE coVER before you buy

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

3,40 DATABASE MANAGEMENT SYSTEMS IJNTU-HY


DERABA SOL and Schema
Refinement
UNIT-3 3.41
present in the R.H.S of set of functional
function
1O tind the candidate key, find the closure of elements
which are not dependen alain all the functional dependencles in entity sets.
261
ABCh Answer
can have the following functional dependencies,
April-11, Set-4, 01(b)

BDEF - nentity set dependency


ADG 1.Full functional
Partial functional dependency
AHs99
lt can
be observed that ABD is not present in the R.H.S of any functional dependency.
3Transient or transitive functional dependency.
lDependency
y Full Functional
The closure of ABD ie. (ABD) is 1.
ABCDEPGHubh- R are attributes of an entity set in a table such that y is functionally dependent only onx, but not on any proper
fofx,rand
y
candidate of R with set of fiunctional dependencies Fis ABD. then this type of dependency is called full functional dependency
he subset of
Q60. How are primary keys related to functional dependencies? Example

Answer a
uppose the roll number and subject name specify the marks of student in particular subject. In this case,it is not mandatory
student will get good markS in all the subjects. Therefore, marks depend on the subject name.
Relation between Functional Dependency and Primary Keys
ie, RolINumber, SubjectName Marks
Consider the following table representing the Employee-department relation. . Partial Functional Dependeney
Emp_idEmp_name Phone_no Dept id Dept name Mgr id Performance Ifr and y are attributes of an entity set in a table and y is functionaly dependent on r such that elimination of
some attributes
8011 Neha 23345612 fromx does not effect the dependency, then this type of dependency is called partial functional dependency. That is, y is partially
04 HR 11234 Good dependent onx.
8012 Seema 65430112 i1640
06 IT Average Example
8013 Sara 24571230 09 FI 11039 Good During examinations, any subject can be randomly held in any examination hal. Therefore, hall number depends on subject
8023 Asra name as well as roll numbers. In this case, hall number's dependency on subject name is partial because it also depends on roll
24592607 03 Marketing 11931 Bad number as well.
TheEmployee-department relation consists of the
following attributes. Emp id, Emp name,
mgr_1d, and performance. In this relation, Phone _no, Dept id, dept nan SubjectName HallNumber
the primary key is a composite key that is composed
andDept id of the following two parts Emp3. Transient or Transitive Functional Depene

The Emp_id uniquely cannot identify a row or Ifx, y, z are attributes of an entity set in a table such that r is functionally dependent on y and y is functionally dependent
tuple and hence it is not a primary key. onz, then z will be transitively dependent on x through y.
uniquely identify a row in the Employee On the other hand, the Dept id cannd
department relation and thus it is also
are combined in order to uniquely not a primary key. Howeve, Emp_ id and DeptA
identify all the rows, Thus Emp Example
relation. It is used to determine every id, Dept_id is a primary key for the Employee deparm
attribute i.e., Emp_name, Phone_no,
attributesare dependent on the primary key. Dept name, Mgr_id and performance. Since tne For examinations to be held, if students are dependent on teachers and teachers are dependent on management. Then
The functional dependency between management will be transitively dependent on students through teachers.
the following relations, the primary key and the attributes 1s show
StudentsTeachers
()Emp_id Emp_name
Teachers Management
(i) Emp id Phone no
(ii) Emp_id, Dept idPerformance
(v) Deptid-Deptname
-La - Q62.
Management Students.
Differentiate between FD and MVD.
Answer: May-15(R13), O70)

Dept id - Mgr id Functional Dependeney Multivalued Dependency


Functional dependency was first defined by armstrong8 Multilevel dependency was first defined by fagin.
The attribute present at the right
of the arrow are functionally dependent
above five relations, it is observed that Emp_id
uniquely jdentify the attributes,
on the attribute at the left
of the arrow.
m th Functional dependency states that set of attributes are Multivalued dependency states that one attribute 1
identify the attributes Dept name Emp_name and Phone no and aependent on one another. independent of the other attribute.
and Mgr Dept
Dept id. Thus, a combination (Emp_1d, id.
But, the attribute 'performance'
cannot be separately identihea oy p Every FD is a MVD. Every MVD is not a FD.
of Dept 1d) are required to determine
fully functional dependent on the primary 'Performance. Thus, this attribute 18 saidto t is a constraint used for relational schema design It is used for database schema design.
key, whereas Emp_name,
Phone no, Dept
dependent i.e, they are partially functional name and Mgr id are not fuy functuon lt is initiated with set of attributes on the right.
dependent since they can be jdentified I8 initialized with only single attribute on the right.
Dept 1d G
by a part of the primary
key 1.e., 0y np Redundancy is eliminated by using 4NF only.
h Kedundancy is eliminated by using BCNF and 4Nt
C Look for the SIA GROUP LOGo
on the TITLE COVER
SPECT
aM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS
SIA GROUP 2
before you buy

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

DATABASE MANAGEMENT SYSTEMS


IJNTU-HYE Refinement
3. RABA sQL and Schema
BCNF
3
UNIT
table can be converted into INF by performing the followingsteps, 3.43
3.2.3 First, Second, Third Normal Forms, The
the repeating groups
ininating table (0) and assigning appropriate values
in
By elim to every attribute
3. What is normalization? What are the various normal forms? 0 is converted into the following table (i) as given below
Thus,I
Answer
Dept name Empid
Normalization
Normalization is the process of converting a relation to a standard form by decomposing
a larger relation
a sequence ofof rules
.
nto
that are emploSt
rules that
Dept
Finance 612
Emp name
Henry
Emp designation
Accountant
Emp _salary
Cncient relations that depicts a good database design. Normalization technique involves Finance 615 Morrison
50000
test individual relations so that the database can be normalized to any degree. The main objective ot normalization is to Accountant Assistant 45000
design of database in order to remove data maintaining anomalies, reduce data redundancy and to elimiñate data incone Finance 609 Peter Finance manager 60000
forms. Each and every normal form has i n 329 Ortinga
he process of normalization is based on the concept of normal ts owr
properties and constraints. A relation is said to be in particular normal form only if it satisies all the properties of nom
Software System Analyst 46000
Software 311 Cena Software Programmer 70000
associated with that normal form. These properties are usually applied on the attributes of the relation and also on the ne rrela
relationg 333
that exist between these relations.
Software Rocky Software Designer 75000
Types of Normal Forms Table (il: Table in 1NF
The different types of normal forms based on FD's include,
By identifying a primary key and uniquely determining the attribute values.
1 First Normal Form (INF)
Second Nomal Form (2NF) Tn table (ii), it is clearly observed that
Dept id cannot be considered as a primary key because it does not uniquely iden-
tify the attribute values. For instance, the Dept id 21dentify all the three employees belonging to that Dept Thus, a
3. Third Normal Form (3NF) ner id.
4 Boyce-Codd Normal Form (BCNF). prope primary key must be detemined so that any of the attribute values are uniquely identified. A new key consisting
ofDeptid and Emp 1d is created, which reters to a primary composite key. This key can be used to uniquely identify the
hpit joteotRelation attribute values. For instance, if Dept id -2and Emp_id=6l5 then the values of the attributes Dept name, Emp name,
Empdesignation and Emp_salary are Finance, Morriseon, Accountant Assistant and 45000, respectively.
Normalization proceSS Byidentifying the dependencies from the tabile (i). For instance,the attributes Dept name, Emp_name, Emp_ designation
L.INF 2. 2NF 3. 3NF and Emp salary are dependent on the composite primary key Dept id and Emp_id. If the Employee id is known, then
4. BCNF
its corresponding atributes such as Emp_name, Emp designation and Emp_salary can be determined. This dependency
relation can be shown as follows,
Emp id Emp name, Emp_designation, Emp_salary
Smallermore
In a similar way, the dept id key can be used to determine the dept name. This dependency relation can be shown as:
efficient relation
Figure: Normalization Process dept id dept _name
Q64. Explain 1NF. Give one example. Q65. Explain 2NF. Give one example.
Answer Answer:
INF Second Normal Form (2NF)
A relation schema iS said to be in first normal form Arelation is said to be in 2NF, if the following two conditions are satisfied,
repeated values in a particular column. if the attribute values in the relation are atomic i.e., there should be w
0 Arelation must be in INF
Converting a Relational Table to INF
(1) Anon-key attribute must be fully functionally dependent on primary key.
The conversion of a relational table to INF can by done
be performing the following steps, Inother words, it can be saidthatarelationisin 2NE, if it does not contain any partial dependencies. Thesecond condition
Step1:in this step, the repeatng groups must be removed by eliminating to be verified
only if a relation consists of a primary key that is composed of many atributes i.e., if a relation consists of a
every repeating group has an appropriate
value.
the null coJuntns. This can be done by ensung
suring
primary key hads
with only one attribute then that table 1s in 2N Onny *

Step2:In this step, a priinary key among a set of attributes Converting 1NF
must be identified. into 2NFF
Thus, this primary key helps in uniquely INE
identifying every attribute value. The conversion of a relation in (with composite primary keys) into a relation in 2NF can be done by performing the
Step3;In this step, the dependencies existing ina relation must following
steps,
be identified. This can be done by knowing which aui
Example
relation 1s dependent based on the primary key.

Dept id Dept name Emp id


Step:1allyInitially all
, single key components of the
the single relation are listed separately. Then the key component which is a composite key
the relano
the combination of all the listed keys) is specified. Each of the listed component becomes the primary
key in the respec

ve table i.e., the original table is decomposed into different tables such that each table contains its related key atribute
Emp_name Emp designation. Emp_salary dependent attribute. These
all of the key components identified in step are assigned with their coresponding
I

2 Finance 612 Henry


step,
Accountant 50000 attributes whose value depends on the value of the key atribute.
615 Morrison not result in any of he data anomalies
Accountant Assistant 45000 Et ables generated after pcrforming these steps do
imple
609 Peter 60000
Finance Manager obtained in INE
relation
329 Ortunga System Analyst 46000 Consider the dependency diagram of Employee
Software 311 Cena Software Programmer 70000 Dept name
idDept Empid Emp name Emp desgEmp_salary
333 Rocky Software Designer 75000
Table (il: Organization Information Figure: 1NF Dependency Diagram

Look for the SlA GROUP LOGO


VECTRUM
ALL-IN-ONE JOURMAL FOR EMGINEERINGSTUDENTE SIA GROUP
on the TITLE COVER before you buy

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

JNTU-HYDERA
SYSTEMS JNTU-HY
DATABASE MANAGEMENT and Schema RefinementaOANAN 32A8ATAg
3.44 UNIT-3 sOL 3.45
Salary 1able
tne above dependency diagram consists of two partial|
(ii)
Examplea52 t.2981 0toF0 (ii) Set_salaryouT s
dependencies, In this table, combination of Dept id, Em E Consider the dependency diagram of Employee
dayssworked) idi Emp Salar
mary key and NOD W (number of
US desg
isthedepe
uG

2NF Emp
) Dept 1d. Dept name. attribute on primary këy. tablefrom
Transitive dependency
(1) Emp id. Emp_ name, Emp desg, Emp_salary. eridency
The relation schema and dependency diagr
diagram
table is, of Empye Schemas1R g
Since these partial dependencies result in data anomalies Emp_name Emp_ desg Emp_saary
necessary to eliminate these dependencies. This can be done Schema Emp id Set salary (Emp_desg. Emp _salary)
1s
by performing the steps mentioned below, Salary(Dept 1d, , EmpP_id, NODW
Primary key
Step 1 Table: Dependency Diagram.of Employee"
Primary key diagram consists of a transitive Table: Dependency Diagram for Salary Table
Last the key components The above dependency
oendency, Emp_desg
Emp_salary, which must be eliminatedd
Salary Salary
() Dept_id into 3NF. This elimination is
Dept id Ep id NODW in order to convert the relation
(i) Empid done by pertorming the above mentione step
Dept id Emp id NODW

(11) Dept _id, Emp_d Step


Figure: Dependency Diagram for Salary Table Identiflythe determinant in transitive dependency
Here, the combination of Dept_id, Emp_id is the origi
nalcomposite key. Based on these key components the actual Q66. What is meant by functional dependen Schemaa
Empdese esurgto ap
cmployee relation is decomposed into following tables, Discuss about second nomal form. CIe Salary(Dept id, Emp_id, NODW)
Step 2
Department Answer May-16R11,2
Tdentify dependent attributes
Functional Dependencies Primary keys
()Employee Emp_desg Emp _salary
For answer refer Unit-I1l, Q56, Topic: Functi Table: Dependency Diagram for Salary
(1) Salar Dependency (FD). Emp salary' the dependent attribute since its value
is
Step 2 Second Normal Form depends on the value ofits determinant (1e, Emp desg) This way of converting a 2NF relation into 3NF relation
helps in eliminating transitive dependency which in turn removes
Assign the corresponding dependent attribute. For answer refer Unit-1I, 065. Step 3
all the posSibilities of occurrence of differert data anomalies.
Department Table Q67. Explain 3NF with examples. Remove the dependent attribute
Emp_salary is deleted
Q68. Define BCNF. Explain with an example.
In this table, Dept_id is the primary key and Dept _name Answer (Model Paper-, Q7(b) I NovJDec.-18(R16,0
is the dependent attribute on the primary key. The relation Third Normal Form (3NF) The dependency of "Employee" table is defined as, Answer
schema and dependency diagram for Department table is,
A relation is said to be in third normal form if the Emp id Emp name, Emp_desg Boyce-Codd Normal Form (BCNF)
Schema lowing two conditions are satisfied, Where Emp_desg acts as a foreign key in Employee A relation schema R is said to be in BCNF if the
Department( Dept id, Dept name) Arelation must be in 2NF table. The relation schema and dependency diagrams generated following statements are true for each FD P->0n aset F
n) Arelation must not have any transitive dependences
atter completion of step I to step 3 for Employee relations are,
Primary key
of FDs that hold over R. Here, P is the subset of attributes
In other words, it can be said that a relation is in 3NM 0)Department of R and Q is a single attribute of R
Departmemt every determinant is a key i.e., for every functional dependes
Dept id Dept name () The given FD is a trivial, i.e., QEP
AB, Ais a key. Basically, determinant is an attribute whose
Dept id Dept name determines the value of other attributes. (i) Pis a super key.
Schema
Figure: Dependency Diagram for Department Table Converting 2NF to 3NF A tuple in a BCNF relation is considered as an entity
Department ( Dept id, Dept _name) or a relationship, described by attributes other than the key.
()Employee Table The conversion of a relation in 2NF into a relati
The key is used to differentiate each tuple.
3NF can be done by performing the following steps,
In this table, Emp istheprimary key and Primary key
id Emp_name, Step1:In this step, determinants The structure of such a BCNF relation R can be
Emp desg Emp_salary are the dependent attributes on the in transitive depen Table: Dependency Diagram for Department Table
primary key. The relation schema and dependency diagram 1dentified and are written as a primary key tora obtained by representing the attributes of R as square boxes
for Employee to
Employee table is, Step2: In this step, the attributes that depend on the etemis and drawing arcs between the key and the attributes

-
indicate its FDs.
Schema are identified along with the dependency betwe Emp_ id Emp name Emp_desg
Ds
Ermployee( Emp_id, Emp_name, Emp_desg, Emp attribute and its respective determinant.
_salary)
Step3: In this step, the dependent attributes that weredentio Schema
Primary key step 2 are removed from every table consistmg
nresulse
responding transitive relationship. This deletion
o Employee (Emp id, Emp name, Emp_desg

Employee new table that consists of determinant and also 15 Primary key
Emp_name Emp_desg attrnbute that was present in the transitive relatox
Empid Emp_salary new tab
determinant acts as the primarý key in ne Emp_idEmpname Emp desg Non-key atributes
The table generated after performing stepsdoesp Key:Super key, 4, 4,4,
Figure: Dependency Diagram for Employee Table
tneee
contain any inappropriate dependencies and therelo
it
Figure: Structure of BCNF Relatien Indicating its
FDs

said that the original table is now in 3NE. able: Dependency Diagram for Employee Table08 GROUP
SPECTR SIA
Look for the SIA GROUP LOGO
on the TITLE coVER before you buy
ALL-IN-ONE JOURNAL FOR ENGINEERING STuDENTS

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

TU-HYDERABA
(JNTU-HY
DATABASE MANAGEMENT SYSTEMS
3.46
since it restricte s a SQL and
UNIT-3
Schema Refinement i/t sas 3.47
normal form with respect to redundancy, since it restricts the 3NF? Explain with an
BCNF is considered to be the most desirable dete differ from
of redundancy using only the FD information. How does
BCNF
o, example.

Example Answer
rences between BCNF and 3NFT
relation satisfying an FD P92
Consider the following instance of a BCNF BCNF
3NF
If a functional dependency AB is present
dependency in a relation
If a functional dependency A B is present, then
then BCNF allows this 3NF allows this dependency to be in a relation if
is a candidate key.
only if4' and only if, 'B' is a primary key attribute and 4' is
T not a candidate key.
is also in 3NF.
A relation in BCNE 2. A relation in 3NF need not be in BCNE.
This instance contains three attributes P, R and Q and two tuples. The value of the Q attribute in first tuple
t
is p Decomposition of BCNF relations is not possible. 3. It is possible to decompose any relational schema
known. But, it is given that these two tuples satisfy the FD P> 0. Moreover, as both the tuples have the samemevalues into a set of 3NF relations, by using decompositions
the P column, it can be inferred that the first tuple also has the value q in Q column.
that possess certain desirable properties like lossless-
But, a BCNF relation cannot store redundant tuples, which means the value inferred is not correct. Thus. in join, dependency preservation.
.

relation, all the fields in each tuple store some information, which cannot be computed using the other fields in the relai BCNF guarantees that no redundancy can occur 4. There is a possibility of some redundancy to Occur
instance. using only the information about functional because every transitive dependency is not
dependencies. eliminated.
Example
Example
Student ID Staff ID Course Grade Consider the relation "STUDENT
Code
504 02B 27486 Student_IdClass_Id NameCourse_Id Fees
S09 03B 29346 0123 502 Ravi 312 5,000
509 03B 32463
516 04B 27536 0124 503 Kumar 313 8,000

0125 502 Mahesh 312 5,000


The above table includes the following conditions,

) Each Course _code represents a unique Course


0126 s04 Mehta 460 9,000

0127 505 Mehta 461 7,000


i) A Student can learn any number of courses. For
instance, student 509 has taken two courses with Course Code
29346 and 32463 and earned the Grades A and B
respectively.
otTable: Student Relation
This table consists of three composite candidate keys. These keys intersect with each other because of common attrbute
(ii) A Staff member can teach any number of Sources but
each Course is taken by only one class_Id.
staff member, ti
Student Id, Class Id
Suden Class
1DSu D Course_Code Grade
2 ld, Course ld, Name
3. Fees, Class_Id, Name
The above table structure is reflected in the following key. Following are the functional dependencies for
figure,
he candidate key (Student Id, Class Id) can be treated as primary
STUDENT
Student ID+ Staff_ID -Course_code, relationship.
Gradea
Course_code FDI: (Student_Id, Class_Id}> (Name, Course_1d, fees
Staff_ID

The above figure is in 3NF but not in BCNF D2: (Course_Id, Class_Id, Name)Student ld
and includes a problem
assignments to courses and student grade information. ie., the table structure is describing two hingsstal D:Class_Id, Fees, Name) (Course Id, Student_Id)
This dual-purpose table can
solved by decomposing the table structure structure results in anomalies. hich
into two table structures. Thus
the two table structures which are ined ifes
satisie FD4: {Course Id, Class Id) Fees
the requirements of 3NF and BCNF oDu they are in BCNF. However,
does not cause any problem and therefore
M D, FD3 are candidate keys whose presence candidate key. The primary
which belongs to {Fees, Class_ld, Name}
ioon NF since "Fees" is a primary key attribute and as FD4 is allowed, the student relation
Class_Id} does not consist of any partial or transitive dependencies
sevStudant I 3NF ut Id,
in 3 candidate key. Due to this, the
is
Course Code the attributes in a relation must be a
not in BCNF. Since, BCNF require that all
Grade
Cone Code Suff D Btudent course is updated then every such
row must also
1 relationship example, if the fee of a
Figure: 3NF and BCNF
nship
beupdated. ssuffers from update anomalies. For an inconsistent database may be generated.
updated, then
Howe the corresponding rows are not
Look for the Sla GROUP LOGO
on the TITLE COVER before you buy,
SPE Owever, if SIA GROUP
M ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

DATABASE MANAGEMENT
SYSTEMS IJNTU-HYDE.
DERABA SQL and
Schema Refinement 3,49
3.48 ut-3
Letr be a relation schema and let F be a set of functional
with | Example O 0 PE
0a The FDs
are,
Explain 2NF, 3NF and BCNF Normal forms dependencies on R, let R, and R, forms a decomposition of
rG.
example. What is the difference between 3NF Consider the "STUDENT" relation. {A BC R. This decomposition is lossless-join decomposition of R
and BCNF? STUDENT (Std id, Name, Location)ts
FA with respects to F, if at least one of the following functional
dependencies are in FP (closure of F).
Answer May-19(R16), Q7(b)
This relation can be broken-down into two
C A
2NF
folows
relations DE 1 R,R,R
For ar swer refer Unit-1lI, Q65. E- 2. R,nRR
(a) Location (Std id, Location) and Relatio
3NF
Name (Std_id, Name)
Decomposed ations
R,nR,-Din this problem) andthereisan FD, D-E
(b) C, D), R,(E, F, D)
For answer refer Unit-1l1, 067. R, (A, C, D), R(B, R, nR,E (E R) which satisfies the above condition
lossless
When a natural join operaion is pertormed on these check whether the given relations are (2). There fore, the decomposition is lossless.
BCNF In order to
schemes, the original STUDENT elation is sustained following three conditions are to be satisfied.
For answerrefer Unit-1I, Q68. or not,
the Q74. Suppose that we decompose the schema R=
Location Name STUDENT Condition 1
(A, B, C, D, E) into R, (A, B, C) andR, (A, D, E).
Differences between 3NF and BCNF R should be in at least one R, where Determine that this decomposition is a lossless-
STUDENT very attribute in
For answer refer Unit-1l, Q69, Topic: Differences be join decomposition or dependency preserving if
ween BCNF and 5NN Std id Location 1sisn the following set F of functional dependencies
Name Condition 2
Q71. What is normalization? What are the conditions holds:
012 Hyderabad Radha R,nR #
are required for a relation to be in 2NF 3NF and A BC, CD E, BD, EA
BCNF explain with examples. 013 Secunderabad Meena Condition 3
May-19(R16), a7(0)
Answer
Answer May-17(R15), Q6[a) 014
015
Hyderabad
Secunderabad
Pinky 0 RRR
or nRRR, Checking for Lossless Join Decomposition
Normalization Rani R, functionally
ie., the attributes common to both R, and Given that R=(4. B. C, D, E)
For answer refer Unit-IIL, Q63, Topic: Normalization. Location Name determine the attribute in either R, or R
The FDs are,
Condition Required for a Relation to be in 2NF Std id Find the closure of the intersection element and verify
Location Stdid Name ()
ABC
For answer refer Unit-Il, Q65 at least one of the functional dependencies are in the
012 Hyderabad 012 Radha if CDE
Condition Required for a Relation to be in 3N closure
013 Secunderabad 013 Meena Based on the three conditions, the given example is
For answer refer Unit-II, Q67. BD
014 solved as,
Condition Required for a Relation to be in BCNNF Hyderabad 014 Pinky
Condition 1
EA
For answer refer Unit-II, Q68. 015 Secunderabad 015 Rani R R, R consists of at least one attribute of relation k.
Decomposed Relations

a aldLocation Name- Student condition is satisfied.


-(4, B,
R, C.R
(A, D, E)
3.2.4 Lossless Join Decomposition
Inorder to check whether the given relation are lossless
Std id aoLocation Name Condition 2
Q72.,Define lossless join decomposition with example.
012 (or) not, the following conditions are to be satisfied.
OR
Hyderabad Radha R,R=CD Condition 1
013
Explain about lossless join decomposition.
Secunderabad Meena (R UR)nR, =(ABCD) Uu (EFD)
Every attribute in R should be in at least
one R, where
014 Hyderabad Pinky = D 1
sišn
June-14(RO9), Q5(b)

OR 015 Secunderabad Rani Condition 3 Condition 2

When is the decomposition ofa relation schema No additional tuples are generated and neither dala
duplicated nor data is lost. Therefore the relation 5
(CD)= CDAEBC R,R
R into two relation schemas X and Y (Dy-DEADBC Condition 3
said to 15 lossless.
be lossless-join decomposition? Why is
property so important? Give a necessary this Example3 ul)ht he functional dependencies in (CD) are C4, |) RORR, orR, nRR
and sufficient condition to test
isbti DEE and in (D)' are DE, A BC i.e.,the attributes common to both R, and R,
functionally
whether a For answerrefer Unit-111, 073. determine the attribute in either R, or R
decomposition is lossless-join. Since, all the three conditions are satisfied, the given
Q73. Consider the relation R(A, B, C, D, E, F) andr intersection element and vertly
Answer
posed relations are lossless. i) Find the closure of the
Nov./Dec.-18(R16), Q6(e)
ADH Requirer one of the functional dependencies are in the
it at least
Losslessjoin Decomposition
A BC, A,
C A, D E, E D
of Lossless Decomposition
closure
the decomposition of R into R1(A,
Lossless-join decomposition is one of the properties C, D) and R3 (E, F, D) t the
(RLet R be a relation schema. A set of relation schemas Based on the three conditions, the given
example is
of
decompositions. 1his dependency 1s also called as non-additive lossless. Ep , )iseVery a decomposition of R ifR R,UR,O as,
requirement of lossless decomposition
R Should present in at least on R(1 Sissoved
or non-loss join dependency. In a more specific way, lossless-
join dependency can be defined as the one which generates no
Answer
. Let h
relatione
n
eation on schema R and similarly r areCondition 1
attribute of reation k
additional tuples when the natural "join"operation is performed Given that, i Ut3 ri yaud nemasR, R,., it is observed that r r,b | R, R, consists of at least one
find w s always true. A decomposition is always easy
on the decomposed relation schemes.AS se 1condition is satisficd.
R(A,B, C, D, E, F)
h aoa he given decomposition is lossless-jotn
SIA GROUP
RLook for the SIA GROUP LOGO
2 on the TITLECOVER
before you buy
" HLL-IN-ONE JOURNAL FOR
ENGINEERING STUDENTS

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

MANAGEMENT SYSTEMS (JNTs


JNTU-HYDERAR Refinement
DATABASE SQL and Schema 3.51
3.80 UNIT-3
The union of closure set of two projectie how to decompose a relatlon into BCNF with example.
ain
orioin
dependencies of the ginal stbe e a77.
Conditlos 2 to the closure set of relation
R,nR4-D In other words, it can be said that er
Condition 3
decomposed into projections R,, R, R, in suchtionAn
enforcement of constraint to set of F
Way
F
equal to enforcing the constraint on the originolalog
ay hpeco
ition into BCNF
ider a universal relational schema K4,A .
4,) that is decomposed into set of relatienal schemaD-(R, R
hat every individual R, is in BCNF and the decomposition relation D satisties the lossless join decomposition
(Ay = ABCDEA Set P in such set offunctional dependencies This sort of decomposition can be performed by considering the followingalgorithm.
F.
said to be "dependencu l
functional dependencies in (4)'
are A BC, CD| the decomposition is decomposition_INTo_BCNF
The E, B-D, EA
Example Algorithm
Consider an example where the relation A universal relation schema "* and set of functional dependencies
"F on the attributes.
Z is de Tnput:
Since, all the three conditions are satistied, the givea
decomposed relations are lossless.
into relations. The attribute set of Z consist
of
bo Step 1: Set D: = {R}
attribute set of decomposed relations consist of P0an d Step 2: If three exista relation SChema X in D which is not in BCNF, then
Checking for Dependency Preserving Decompositiono set of FDs that hold over 2 mcludes P>0, 0Raand
Given that R=(4, B. C, D, E) FroSet of attributes of the relation contains b X D, which is not in BCNF
elect a relation schema in
The functional dependencies are,
and > P
Identify the FD, A B in X that violates BCNF

4BC a FOR-Contains R and


R->.
Now, the original set of functional dependencies
consis
Substitute X in D by two relational schema (X-B) and AB
CD (a) F (b) P C) 0 >R d) R->P
Now, the union of closure ot Fpo and Fop includes In the above algorithm, the relation schema X, which is not in BCNF.is decomposed into two relation schema whenever a
BD executed. The relation schema X-B consists of all etributes except the single attribute B' in X. The relation sehema XB
EA FroU For XUB) denotes the union of attributes in X and B.
(ie.,
Decomposed Relations are R,= (4, B, C), R, =(4, D, E) P0.0P, R, R In step 2, the algorithm determines whether X vioates BCNF or not. This is done by verifying if A is a super key in
With R ,0>Pand transitivity y' testing every functional dependency AB
or not by in X. This will determine whether the closure set ofA (i.e., A) fails to
R,4,B, C with the functional dependency as, RPis obtained attributes in X. Once the decomposition is performed, different relation schemas are generated each of which is in
include all the
BCNF and consists of fewer attributes.
F-4 BC Thus,the decomposition is said to preserve the dependeas
Example: Consider a relation schema "Student" with the following set of functional dependencies.
R(4,D, E) with the functional dependency as, Q76. Decompose the relation R(A, B, C, D, E,
FD1: {Stu Jd, Subject} Lecturer
F-E-A with the following set of FDs into a BCN
relation. FDs of the relation are ABCDE, ABD FD2: Lecturer Subject
.
F=FuF P-4BC, E-A) DEABCE, EC is the decomposition lossless
at In these set of FD's, {Stu Id, Subject} is a candidate key. Oins
Here, the FD, CDE is not in both F, and F, dependency preserving. Student

Therefore, it is not dependency preserving.


Answer: Stuid Subject Lecturer
Given R(A, B, C, D, E, F
Q75. When is a decomposttion said to be
dependency The FDs are,
preserving? Why this property Useful? Explain. Figure: Schematic Relation with FD's
ABC DE
Answer May-19(R16), as(a) AB From this, it can be inferred that the student relation is in 3NF, but not in the BCNF as {LecturerSubject} violates be
D
Dependency-preserving Decomposition BCNE rule. Therefore, the relation is decomposed into two relations.
DE ABCE Sthudent 1
Ris a relational schema, that is decomposed into schemas E C
R,, R, R, with attributes 4, B, C... by applying all the steps of foitll Lecturer Stuid
As ABC>DE and DE ABCE,
normalization. LetF be the set of functional dependencies
that Student 2
hold over R and F,,
that hold over R, FP. ,
be the set of functional dependencies
R, R. K, respectively. refers to the
aftributes of R, where1=1,2,3.
Jt is possible to write ABC
Now, remaining FDs are,
ABCE (Transitive nlg
Lecturer Subject
AB D FIgure
If R is decomposed into two relations R, and R, Jlt4
attribute set of S, and S. Then the projection with an EC 8. Explain decomposition in 3NF
of R on R, can
be defined as a set of functional dependencies in telt ABC ABCE Answer
the closure of Now, consider ABC
F consisting of the aftributes present in R,. The ABCE, then
notation for Let, R be a relation and F be a set
of FDs representing a minimal ecover associated with R.
representation of a projection of on S, in ABC A,ABC B, ABC C,
projection of F on S, 1s
F F. Similarly, the np(Decomposition rule)
ABCE synthesis, all the attributes over R are considered along with F and. a relation schema X4 is included
in the
deca NF obtained will be in 3NF and they will
prese
on of R with respect to each FD XA in F. As a result, the relation schemas
Now, the relation R with a set of FDs F is decomposed
into two relations R, and R, with an attribute set of
As ABC
E
and E c
It is possible to write ABC
decomm dependencies. Thus, this decomposition is a dependency-preserving decomposition of
e R, but not a lossiess-join
n. However, this decomposition can be made as a lossless-join decomposition as well, by including arelation
C(Transitive rul sclhema
S, and S, is at hae
to
sard be dependency preserving if, As AB D and ABCC attributes which appear in some key.
ransitivity na decomposition into 3NF with a polynomial
(F, F-F. lis possible to write ABCDPseudo to Thus, ONF
complexity. Synthesis algorithm produces a lossless-join, dependency preserving
Therefore,ABC- ABD
Look for the SIA GROUP LOGO SPECTRUM
SIA GROUP
2on the TITLE COVER before you buy ALL-IN-O
ALL-IN-ONE J0URNAL FOR ENGINEERING STuDENTS

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

DATABASE
MANAGEMENT SYSTEMS
[JNTUHYDERABAD
and Schema Refinement
n
3.52 BAT3 sQLnosing the relation it 1s possible to
eliminte the update anomalies. For example, inorder to enter the data a
3.53
of
Example
the attributes AMTVLNG and following
FDsAAMIVLNG, MT4
MTA, taking
VN1,M-1 pewstudent chemistry course simply enter a single tuple in the relation CS.
taking o
Let the relation 'orders have It is decomposed as
follows. generalization of functional dependencies. They can be represented as,
consider the FD AAMTVLNG.
loobtain the minimal cover, Student
Course
otrd y
oslt
AM, A T,AV,AL, AN, AG Course -Text book
The FD ATcan be deleted since,
IS read as "student is multi-dependent on course or "Course multi-determines Textbook".
AV,A Nand VN>T ie

Similarly, the FD A Tcan be deleted since, The meaning of MVD Course Student is,
AMandM>V evists a set of students corresponding to each course C 1.e., for a course C and a textbook, B, the set of students
he pair (C,B) in CST depends on the value of C only. It is independent
Thus, the minimal cover F for the given FDs is, of the value B. A multivalued dependency can
nalchinsTE X.Y.Z are the attribute sub sets of attribute set of relation A then Y is said
AM,A L,AN, AG, MT4, VN T, MV to be multi-dependent on Xif for every
decomposSition, if the relational schema are obtaine pce of A, a set of Y values matching a given pair (Xvalue, Zvalue) depends only on the X value and
does depend on Z not
The 3NF synthesis algorithm on R can result in dependency preserving instance

from the set F of FDs. al0e.

ie., AM, AL, AN, AG, AMT, VNT, MV. X


This schema can be minimized by combining those relations that have as their
A key. Every FD is an MVD. s eal ii udig 9 tetaee
ie., combining AM, AL, AN, AG, AMT as AMTLNG ie,X
Y This also means X Y

The resulting schema are 4MTLNG, VNT and MY as AMTLNG is a super key of R, these relations are in 3NE Five rules are used to compute additional FDs and MVDs. These are,

3.2.5 Multivalued Dependencies, Fourth Normal Form, Fifth Normal Form (a) MVD complementation: If 4 B, then A R-AB.
Q79. Describe multivalued dependencies with examples. (6) MVD augmentation: If A >B and CCD then 4D BC
(o) MVD transitivity: If4 -
B and B C then A CB)
Answer : (Model Paper-ll, Q7(b) |April/May-12, Set-3, 04
Multivalued dependencies are generalizations of functional dependencies to understand the concept of multivahu )Replication: If AB, then 4 - >B
dependencies. Consider a relation, )Coalescence: If A- B and there is a C such than BNCis empty,

Course Student Textbook CD and D CB, then 4D


Chemistry Jack Principles of Science 080. Discuss the need for schema refinement. Explain the fourth and fifth normal form and inclusion
Chemistry Jack ABC of chemistry dependencies. Nov/Dec-18(R16), 07
Chemistry John Principles of Science OR
Chemistry John ABC of chemistry Explain 4NF, 5NF normal forms with examples.
Physics Jack Principles of sciences Refer Onily Topics: Fourth Normal Form (ANE), Fifh Normal Form (5NE)
Physics Jack Optics AnSwer: April-18(R15), Q7(a)
Physics Jack Optical physics Need of Schema
Refinement
Here, each tuple means that the course "C is taken by the student mmenda FOr answer refer Unit-I, Q53 (First Paragraph Only).
"S and the textbook 'T is theone
one which
which 1s te
The attributes student and textbook are independent
of each other. Any number of students can refer any textboOK a 15ecant Fourth Normal
Form (4NE)
any course. The composite key for this relation consist of (CST).

ce ae auioutes are part Arelation R is said to be in 4NF if it is in 3NF and doesn't have any multivalued dependencies. In other words, if R is a
OT Key, this
Much of the data is being repeated. That 1, the textbo0ok
relation is in BCNF
and therefore, there is no use of decomposing 1
for chemistry i.e., ABC of chemistry i.e.,
This redundancy again give rise to update anomalies. By repeated for ca
nal
es
, schema with Fas a set of dependencies which includes all the FDs and MVDS oTK
hen s Said
to be in 4NF if any of the following conditions hold overK.
and A and D aewou
decomposing this relation into two attribules
and CT, it is possible to deal with redundancy. schemas wiu Forevery MVD A- >B
It is worth noticing that the redundancy is due to the fact other. Su BCA or AB = R or
that students and textbooks are independent or each
1dependent of ca
type of constraint is an example of multivalued dependency or.MVD.
2 A is a super key.
M
more pres are trivial always holds over R. A dependency is said to be trivial i.e., A B is trivial if BSAS
O
Course OTE precisely
Student Course xample ABR.
Teacher
Chemistry Jack Chemistry ABC of chemistry
Chemistry John Chemistry answer refer Unit-IlI, Q79.y u
Principles of science Inthe exa an MVD which is not a FD. When the relation is decomposed
Physics Jack Physics
Principles of science O Sche ple,CST" relation is not in 4NF because it involves
are in 4NE And also if natural join operation is performed on
and CT With atributes CS and CT, then these schemas
decomposition
Physics Optics he resulting relation will be CST, Hence, this is a lossless
(RVA) and then the
4NE, first eliminate the Relation Valued Attributes
Physics Optical physics sCan be reduced to BCNF
Can Ca be concluded that, in order to achieve
RUM ALL-IN-ONE SIA GROUP
Look for the SIA GROUP LOGO JOURNAL FOR ENGINEERING STUDENTS
on the TITLE COVER hefore you buy

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

DATABASE MANAGEMENT
SYSTEMS JNTU-HYDERA
[JNTU
3.54 UNIT-3 sQL
and Schema Refinement 3.55
Fifth Normal Form (5NF) decomposition in 4NF always dependency preserving and lossless, justifyyour answerwith the
Generally, a non- Q81.
help of an
example
4NF and cannot be non-loss decomposed. loss c
A relation is said to be in SNF if it in
is
ditferent tables. But in SNF, non-loss decompositionopo
achieved by decomposing an individual table into two Answer
operator makes non-loss decomposition possible. Considchie
15

decomposing a table into three or more tables. The join Decomposition in 4NF
example table.
Performance
es the decomposition 4NF is always dependency preserving and loss less. Multivalued dependencies and lossles-joins
in
decomposition. Consider"R" as relation schema, and as a set of functional and multivalued dependencies
Student Emp_ Address only lossless D
Hyderabad Good
pose R and R, form a decomposition of R, then this decomposition is said to be lossless-join decomposition of R, if and
Ravi
least one of the following multivalued dependencies is in D".
Hyderabad Good oifat
Kumar R, R R
Average R,
Ravi Delhi
R, R,>
(or)
Kumar Delhi Average If R, R R,
R,, then
Ravi Delhi Best R, R
Table: Student Table
R, and R, are said to be a lossless-join decomposition of R.
R, and R, it should hold either of the two schemas
For every lossless-join decomposition of into two relation schemas
R
This table contains pair-wise cyclic dependencies in the primary key. To determine the performance, one must it ie,R R, R, (or) R, R,R
studentand its Emp address. Similary to detemine emp_ Address and student, one must identify student, performance and s Dependency preservation is not as simple to determine as with functional dependencies.
respectively: This can be done by deoomposing the table into three tables as follows,
a decomposition of R, and D be the set offunctional and multivalued dependency
Student Emp_Address io Let Rbe a relation schema and R, R.R, be
holdingon R.A decomposition of schema R is dependency preserving with respect to a set D of
function and multivalued dependency,
every set of relation r,(R), r,(R)..r(R) such that for all i,r, satisfies Di, there exists relation r(R) that satisfies D
Ravi Hyderabad iffor
Example
Kumar Hyderabad checked.
Using decomposition algorithm, the result for dependency preserving can be
Ravi Delhi
LetR-4,B, C.G,H.I) ae
Kumar Delhi Let D be
Table: Student-EmpAddress A B
Student Performance B H
Ravi Good onabnukqo CG H
Ris not in 4NF, since A B and A is not a super key.
Kumar Good
The algorithm causes to decomposed using this dependency into,
Ravi Average R, 4, B)
Kumar Average R, 4, C, G, H, I)
dependency CG Hthen decomposes R, into R,=(C, G. H)
Ravi R, IS now in 4NF, but R, is not in 4NF then, apply multivalued
Best
Table: Student-performance

EmpAddress Performance
, 15
R,-4, C, G, 1)
now in 4NF, but R, is not 4, A-His in D then restrict of this dependency to R, gives 4-

Hyderabad
)ms Thenagain apply R,- (4, )
Good R, -(4, C, )
Delhi RL is obiained.
Average algorithm terminates and decomposition R,, R,, R, and
The and 3NF explain with examples.
Delhi Best 82. for a relation to be in 4NF
Table: EmpAddress-Performance
What are the conditions that are required
Answer
May-17(R15), a7(a)

After the decomposition, all the three tables obtained are in nditions for a Relation to be in 4NF
5NF
Form (4NF).
Inclusion Dependency answer refer Unit-1lI, Q80, Topic: Fourth Normal
Inclusion dependency is a statement containing attributes depend
or
Onditions for a Relation to be in 3NF
aA and B in.X and Yrelations respectively such s
attribute and is a subset of B which is its relerenced attribute. Foreign
the columns of a prinmary key is an example of inclusion dependency.
Inclusion dependency does not encourage division attribute
key constraint which allows thatonto
columns in one r

lencythen
. For answer refer Unit-1II, Q67,
Explain fourth normal form andt BCNF
Answer
May-18(R13), 07

of groups. If PQSRS has an inclusion


relation schema PQ must be decomposed keeping atleast one schema depetnothe Fourth
with both P and Q. If this property 1s Normal Form
schema PQ has to be developed again to check 1or the inclusion dependency
PQ SRS. Practically, inclusion d
ndencie (4NF).
based on keys. In additional to foreign key constraint, an ER diagram with key-b For nswer refer Unit-111, Q80, Topie: Fourth Normal Form
ISA hierarchies is also an examproup
inclusion dependencyO key-based inclusjon dependencies reduce the overhead Broupd e Codd Normal Form (BCNF)
incurred in dividing the atribule a
decomposition.
Or answer refer Unit-11, Q68.
aROUP
SPECTRU
ENGINEERING STUDENTS
Look for the SlA GROUP LOGo on the TITLE CoVER before you buy N ALLAN-ONE JOURNAL FOR

Downloaded by Maansi Janardhan ([email protected])


lOMoARcPSD|35655477

IJNTU-HV
3.56 DATABASE MANAGEMENT SYSTEMS HYDERA
broqelhayovla MSn
EXERCISE QUESTIONS
Consider the below tables:

Branch(branch No, street, city, postcode) igos


La StafstafNo, Name, IName, position, sex, DOB, salary, branchNo)ooa tirilbe
PropertyForRent{propertyNo, street, city, postcode, type, rooms, rent, ownerNo, staffNo, branekt
anchlo
Client(clientNo, fName, IName, telNo, prefTlype, maxRent, eMail)

PrivateOwner(ownerNo, fName, IName, address, telNo, eMail, password),


Viewing(clientNo, propertyNo, viewDate,
comien o io noiiogmess igleol pe
Registration(clientNo, brnachNo, staffNo, dateJointed)

(a) Insert the data into the above tables.


teo sd bau eorlomtri
(b)Insert a new row into the table supplying data for all columns.
(c) List full details of all staff.
43 anro p

(d) Produce a list of salaries for all


1ot to diogte tgiigozob gn
staff, showing only the staffNo, fName,
IName, and salary detlk
(e) List all cities where there is either
a branch office or a property
for rent.
( List all cities where there is a
branch óffice but no properties
for rent.
(g) List allcities where there
is both a branch office and
at least one property for rent.
(h) List the names and comments t onstb airt gnies botfanol
ofall clients who have viewed a property rent.
2. Write the use of commit
for
and rollback commands in
SQL.
3. What is the importance of
handling null values in a relation?

det Lou
the SIA GROUP LOGO on the TITLE COVER uy
Downloaded by Maansi Janardhan ([email protected]) before you Duy

You might also like