Dbms Unit 3 Dbms Unit 3
Dbms Unit 3 Dbms Unit 3
Marketed by:
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.
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
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.
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
Look for the SlA GROUP LOGO on the TITLE COVER before you buy ALLIN-ONE JOURNAL FOR
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
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
SIA GROUP
before you buy LLIN-ONE JOURNAL FOR ENGINEERING STUDENTS
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
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)
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
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;
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
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
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,
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
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
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
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
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
(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,
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
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
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
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)
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.
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
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
-
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
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
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
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
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
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
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,
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
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
IJNTU-HV
3.56 DATABASE MANAGEMENT SYSTEMS HYDERA
broqelhayovla MSn
EXERCISE QUESTIONS
Consider the below tables:
det Lou
the SIA GROUP LOGO on the TITLE COVER uy
Downloaded by Maansi Janardhan ([email protected]) before you Duy