0% found this document useful (0 votes)
10 views

DBMS Tutorial - 2 Solutions Final

The document provides an overview of key concepts in database management systems, including characteristics of relations, definitions of relation state, schema, domain, and arity. It explains various constraints in the relational model, unary relational operations, join operations, and definitions of keys. Additionally, it discusses integrity constraint violations during insert and update operations with examples.

Uploaded by

tharunsanatani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

DBMS Tutorial - 2 Solutions Final

The document provides an overview of key concepts in database management systems, including characteristics of relations, definitions of relation state, schema, domain, and arity. It explains various constraints in the relational model, unary relational operations, join operations, and definitions of keys. Additionally, it discusses integrity constraint violations during insert and update operations with examples.

Uploaded by

tharunsanatani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

DBMS Tutorial – 2 Solutions

1) List and briefly explain the characteristics of Relations.


Soln:
There are 4 characteristics of Relations,
i) Ordering of Tuples within a Relation
ii) Ordering of values within a Tuple
iii) Values & Nulls in a Tuple
iv) Interpretation of a Relation

i) Ordering of Tuples within a Relation:


 A relation is defined as a set of tuples. Elements of a set have no order among them; hence, tuples in
a relation do not have any particular order.
 The definition of a relation does not specify any order: There is no preference for one ordering over
another.
 Ex:

ii) Ordering of values within a Tuple:


 The order of attributes and their values is not that important as long as the correspondence between
attributes and values is maintained.
 An alternative definition of a relation can be given, making the ordering of values in a tuple
unnecessary. In this definition, a relation schema R = {A1, A2, ..., An} is a set of attributes and a
relation state r(R) is a finite set of mapping sr = {t1, t2, ..., tm}, where each tuple ti is a mapping
from R to D, and D is the union (denoted by 𝖴) of the attribute domains. In this definition, t[Ai]
must be in dom(Ai) for 1 ≤i ≤n for each mapping t in r. Each mapping ti is called a tuple.
 According to this definition of tuple as a mapping, a tuple can be considered as a set of (<attribute>,
<value>) pairs. The ordering of attributes is not important, because the attribute name appears with
its value.
 Ex:
iii) Values & Nulls in a Tuple:
 Each value in a tuple is an atomic value; that means, it is not divisible. Hence, composite and
multivalued attributes are not allowed.
 The multivalued attributes must be represented by separate relations, and composite attributes are
represented only by their simple component attributes in the basic relational model.
 An important concept is that of NULL values, which are used to represent the values of attributes
that may be unknown or may not apply to a tuple.
 In general, we can have several meanings for NULL values, such as value unknown, value exists
but is not available, or attribute does not apply to this tuple.
 During database design, it is best to avoid NULL values as much as possible.
 Ex:

iv) Interpretation of a Relation:


 Each tuple in the relation can be interpreted as a fact or a particular instance of the assertion. For
example, a STUDENT relation whose Name is Alice, Ssn is 12345678, Age is 19, and so on.
 Relations may represent facts about entities, whereas other relations may represent facts about
relationships. For example, a relation schema MAJORS(Student_ssn, Department_code) asserts
that students major in academic disciplines. A tuple in this relation relates a student to his or her
major discipline. Hence, the relational model represents facts about both entities and relationships
uniformly as relations.
 Ex:
2) Define:
i) Relation State
ii) Relation Schema
iii) Domain
iv) Arity
Soln:
i) Relation State: A set of tuples at a given time or at a given instance is called relation state. It is also called as Relation
instance.

ii) Relation Schema: A relation schema R, denoted by R(A1, A2, ...,An)is made up of a relation name R and a
list of attributes A1, A2, ...,An. A relation schema is used to describe a relation where R is called the
name of this relation.
Ex:

iii) Domain: A domain D is a set of atomic values. Atomic means that each value in the domain is indivisible
as far as the formal relational model is concerned.
Ex:

iv) Arity: The degree or Arity of a relation is the number of attributes in a relation schema.
Ex:

Degree of this STUDENT relation is 6.


3) Explain the constraints in the Relational model.
Soln:
In the relational model of databases, constraints are rules enforced on the data to ensure accuracy, consistency, and
integrity. The main types of constraints in the relational model are as follows:
i) Domain Constraints:
 Domain constraints specify the permissible values for a given attribute. They ensure that the data entered in a
column falls within a certain range or set of values.
 Type constraint: It ensures the data type (e.g., integer, string, date) of the attribute.
 Value constraint: It restricts the specific values or range of values that an attribute can take.

ii) Key Constraints and Constraints on NULL values:


 A unique constraint or Key constraint ensures that all values in a column (or a set of columns) are distinct
from one another, except for null values.
 Unique Key Constraint: It enforces the uniqueness of the values in one or more columns. Unlike the primary
key, a table can have multiple unique constraints, and columns with unique constraints can accept null
values.

iii) Entity integrity Constraint:


 Entity integrity constraint ensures that each table has a primary key and that the primary key uniquely
identifies each record in the table. This constraint prevents null values in the primary key column(s).
 Primary Key Constraint: It ensures that each row in a table is uniquely identifiable. No two rows can have the
same primary key value, and null values are not allowed in the primary key column(s).

iv) Referential integrity Constraint:


 Referential integrity ensures that a foreign key value in one table matches a primary key value in another table.
This maintains the logical consistency between related tables.
 Foreign Key Constraint: It ensures that a value in one table (child table) corresponds to a valid value in another
table (parent table). This prevents orphan records and ensures that relationships between tables are
maintained.

v) Check Constraint:
 Check constraints enforce specific conditions that each row must satisfy. This can involve comparisons or
logical operations.
 Check Constraint: It specifies a condition that must be true for every row in the table.

vi) Not Null Constraint:


 The not null constraint ensures that a column cannot have null values. Every row must contain a valid (non-
null) value for this column.
 Not Null Constraint: It ensures that a column cannot contain a null value, meaning every row must have a
value for this column.

Example: Consider a simple database table for storing employee information:


CREATE TABLE Employees (EmployeeID INT PRIMARY KEY, Entity integrity constraint
FirstName VARCHAR(50) NOT NULL, Not null constraint
LastName VARCHAR(50) NOT NULL, Not null constraint
Email VARCHAR(100) UNIQUE, Unique constraint
Age INT CHECK (Age > 0), Check constraint
DepartmentID INT,
FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID) Referential integrity constraint);
Here,
 “EmployeeID” must be unique and not null (Primary Key Constraint).
 “FirstName” and “LastName” cannot be null (Not Null Constraint).
 “Email” must be unique (Unique Constraint).
 “Age” must be greater than 0 (Check Constraint).
 “DepartmentID” must correspond to a valid “DepartmentID” in the “Departments” table (Foreign Key Constraint).
4) List Unary Relational operations and explain.
Soln:
There are 3 Unary relational operations. They are:
i) SELECT ()
ii) PROJECT ()
iii) RENAME ()

i) SELECT ():
 The SELECT operation acts as a filter, it is used to extract a subset of tuples or rows from a relation based on
a “selection condition”.
 It returns or displays only those tuples that satisfy the qualifying condition, remaining tuples are discarded.
 The number of tuples in the result of a SELECT operation is less than or equal to the number of tuples in the
input relation R.
 It is denoted by Greek symbol “Sigma - ”
 Syntax: <selection condition>(R)
ii) PROJECT ():
 The PROJECT operation acts as a filter, it is used to extract a subset of Attributes or Columns from a relation
based on “attribute list”.
 It returns or displays only those attributes that are given in the attribute list, remaining attributes are discarded.
 The number of attributes in the result of a PROJECT operation is less than or equal to the number of tuples in
the input relation R.
 It removes any duplicate entries and displays only once.
 It is denoted by Greek symbol “Pi - ”
 Syntax: <attribute list>(R)
iii) RENAME ():
 The RENAME operation is used to rename the attributes or table or both.
 It renames the input relation attributes or relation name as provided by the user.
 It is denoted by Greek symbol “Rho - ”
 Syntax: S(B1, B2, …, Bn)(R) or S(R) or (B1, B2, …, Bn)(R)

Consider an example of EMPLOYEE Table


EMPLOYEE
EID ENAME AGE DEPT SALARY
1001 Alice 30 HR 50000
1002 Bob 25 IT 30000
1003 Charles 28 HR 40000
1004 David 35 IT 48000

SELECT: DEPT=HR(EMPLOYEE)
EMPLOYEE
EID ENAME AGE DEPT SALARY
1001 Alice 30 HR 50000
1003 Charles 28 HR 40000

PROJECT: EID, ENAME, AGE (EMPLOYEE)


EMPLOYEE
EID ENAME AGE
1001 Alice 30
1002 Bob 25
1003 Charles 28
1004 David 35

RENAME: EMP(EMPLOYEE)
The above query will rename the EMPLOYEE table as EMP
5) Discuss the various types of Join operations with an example. Why theta join is required.
Soln:
In relational databases, join operations are used to combine rows from two or more tables based on a related column
between them. There are several types of join operations, each serving different purposes and producing different results.
The various types of join operations along with examples are as follows:

Consider two tables: Employee and Department


Employee
Eid Ename Did
1001 Alice 101
1002 Bob 102
1003 Charles 103

Department
Did Dname
101 HR
102 IT
104 Finance

i) Inner Join:
 The inner join returns only the rows that matches the given condition values in both tables.
 Ex: Department Employee.Did=Departments.DidEmployee
Eid Ename Dname
1001 Alice HR
1002 Bob IT

ii) Left Outer Join:


 A left join returns all rows from the left table (Employees), and the matched rows from the right table
(Departments). If no match is found, NULL values are returned for columns from the right table.
 Ex: Employee Employee.Did=Departments.DidDepartment
Eid Ename Dname
1001 Alice HR
1002 Bob IT
1003 Charles NULL

iii) Right Outer Join:


 A right join returns all rows from the right table (Departments), and the matched rows from the left table
(Employees). If no match is found, NULL values are returned for columns from the left table.
 Ex: Employee Employee.Did=Departments.DidDepartment
Eid Ename Dname
1001 Alice HR
1002 Bob IT
NULL NULL Finance

iv) Full Outer Join:


 A full join returns all rows when there is a match in either left or right table. Rows without a match in either
table will have NULL values.
 Ex: Employee Employee.Did=Departments.DidDepartment
Eid Ename Dname
1001 Alice HR
1002 Bob IT
1003 Charles NULL
NULL NULL Finance
v) Theta Join:
 A theta join allows for the joining of tables based on a condition that is not necessarily equality. The condition
can be any comparison operator such as <, >, <=, >=, !=, etc.

vi) EQUIJOIN:
 The join operation where only = operator is used is called EQUIJOIN.
 In the result of EQUIJOIN we always have one or more pairs of attributes that have identical value.
 Ex:

vii) Natural Join:


 A Natural join returns all rows of both tables based on a common attribute that is matching in both the tables.
We do not want to explicitly specify the join condition.
 This join can only be performed if there is a common attribute in between the relations
 Ex:

Why Theta Join is required?


Theta joins are required because they provide the flexibility to join tables based on conditions other than
simple equality. This allows for more complex and varied queries, accommodating a wider range of business
logic and analytical requirements. Without theta joins, it would be impossible to express certain types of
queries directly within the relational algebra framework.
6) Define the following:
i) Key
ii) Super Key
iii) Candidate Key
iv) Primary Key
v) Foreign Key
n
Sol :
i) Key: A key in a relational database is an attribute or a set of attributes that uniquely identifies a tuple (row) in a
relation (table). Keys are essential for ensuring that each record in the table can be uniquely identified, which
helps maintain data integrity and enables efficient data retrieval and relationships between tables.

ii) Super Key: A super key is a set of one or more attributes that, taken collectively, uniquely identify a tuple in a
relation. A super key may contain additional attributes that are not necessary for unique identification (i.e., it
may have redundant attributes).

iii) Candidate Key: A candidate key is a minimal super key, meaning it is a super key with no redundant attributes. In
other words, it is a set of attributes that uniquely identify a tuple, and no subset of these attributes can uniquely
identify a tuple.

iv) Primary Key: A primary key is a candidate key that is chosen by the database designer to uniquely identify tuples
in a relation. It must contain unique values and cannot contain null values. Each table can have only one primary
key.

v) Foreign Key: A foreign key is an attribute or a set of attributes in one table that refers to the primary key in another
table. The foreign key establishes a relationship between the two tables, ensuring that the value in the foreign
key column(s) corresponds to a valid value in the referenced primary key column(s).
7) Explain with an example the violation of the integrity constraint in each of the three types of update operations.
Soln:
Consider two tables Employee and Department,
Employee Department
Eid Ename Did Did Dname
1001 Alice 101 101 HR
1002 Bob 102 102 IT
1003 Charles 103 104 Finance

i) Insert Operation:
 Violation of Entity Integrity: Entity integrity ensures that the primary key of a table must be unique and not
null.
 Example: If we attempt to insert a row with a null value in the `EmployeeID` column, it violates the entity
integrity constraint.
 INSERT INTO Employee (Eid, Ename, Did) VALUES (NULL, 'David', 104);
 This insert operation will fail because the primary key cannot be null.
 Violation of Referential Integrity: Referential integrity ensures that a foreign key value must match a
primary key value in another table or be null.
 Example: If we insert a row into `Employees` with a `DepartmentID` that doesn't exist in the `Departments`
table, it violates referential integrity.
INSERT INTO Employees (Eid, Ename, Did) VALUES (1004, 'David', 999);
 This insert operation will fail because `DepartmentID` 999 does not exist in the `Departments` table.

ii) Update Operation:


 Violation of Entity Integrity: Entity integrity ensures that the primary key of a table must be unique and not
null.
 Example: If we attempt to update the `Eid` of one row to a value to null, it violates the entity integrity
constraint.
UPDATE Employee SET Eid = 'NULL' WHERE Ename = ‘Bob’;
 This update operation will fail because primary key cannot be null.
 Violation of Referential Integrity: Referential integrity can also be violated through updates if a foreign key
value is changed to a value that doesn't exist in the referenced table.
 Example:
UPDATE Employee SET Did = 999 WHERE Eid = 1002;
 This update operation will fail if `DepartmentID` 999 does not exist in the `Departments` table.

iii) Delete Operation:


 Violation of Referential Integrity: Deleting a row that is referenced by a foreign key in another table can
violate referential integrity.
 Example: If we delete a department from the `Departments` table that is still referenced by employees in the
`Employees` table, it violates referential integrity.
DELETE FROM Department WHERE Did = 101;
 This delete operation will fail if there are any employees with `DepartmentID` 101 in the `Employee` table.
 Violation of Entity Integrity: Although rare, deleting a primary key can indirectly lead to a situation where
a table lacks a unique identifier, particularly if it's part of a composite key.
 Example: If any of the `DepartmentID` of the Department is deleted or set to null , it would violate the entity
integrity constraint by leaving incomplete keys.
 DELETE Eid FROM Employee WHERE Did = 103;
 This operation would result in rows with incomplete primary key if not handled correctly.
8) Articulate the steps involved in converting the ER constructs to corresponding relational tables.
Soln:
There are 7 steps involved in converting the ER constructs to corresponding relational tables. They are,

i) Step 1: Mapping of regular entity types


 For each regular entity type E in the ER diagram, create a relation R that includes all the simple attributes of
E.
 Choose one of the key attributes of E as the primary key for R.
 If chosen key of E is composite, the set of simple attributes that form it will together form the primary key
of R.

ii) Step 2: Mapping of weak entity types


 For each weak entity type W in the ER schema with owner entity type E, create a relation R & include all
simple attributes of W as attributes of R.
 Also, include as foreign key attributes of R the primary key attribute(s) of the relation(s) that correspond to
the owner entity type(s).
 The primary key of R is the combination of primary key(s) of the owner(s) and the partial key of the weak
entity type W, if any.

iii) Step 3: Mapping of binary 1:1 relationship types


 For each binary 1:1 relationship type R in the schema, identify the relations S and T that correspond to the
entity types participating in R.
 Choose one of the relations, say S and include a foreign key in S the primary key of T. It is better to choose
an entity type with total participation in R in the role of S.

iv) Step 4: Mapping of binary 1:N relationship types


 For each regular binary 1:N relationship type R, identify the relation S that represent the participating entity
type at the N-side of the relationship type.
 Include as foreign key in S the primary key of the relation T that represents the other entity type participating
in R.
 Include any simple attributes of the 1:N relation type as attribute of S.

v) Step 5: Mapping of binary M:N relationship types


 For each regular binary M:N relationship type R, create a new relation S to represent R.
 Include as foreign key attributes in S the primary keys of the relations that represent the participating entity
types, their combination will form the primary key of S.
 Also include any simple attributes of the M:N relationship type as attribute of S.

vi) Step 6: Mapping of multivalued attributes


 For each multivalued attribute A, create a new relation R.
 This relation R will include an attribute corresponding to A, plus the primary key attribute K as a foreign key
in R of the relation that represents the entity type of relationship type that has A as an attribute.
 The primary key of R is the combination of A and K. If the multivalued attribute is composite, we include
its simple components.

vii) Step 7: Mapping of N-ary relationship types


 For each N-ary relationship type R, where n>2, create a new relationship S to represent R.
 Include as foreign key attributes in S the primary keys of the relations that represent the participating entity
types.
 Also include any simple attributes of N-ary relationship type as attribute of S.
Consider an Example:
9) List and briefly explain the various attribute data types and constraints in SQL while creating table.
Soln:
There are 6 attribute data types in SQL. They are,
i) Numeric: These data types include integer numbers of various sizes (INTEGER or INT and SMALLINT) and
floating-point numbers of various precisions (FLOAT or REAL and DOUBLE PRECISION). Formatted
numbers can be declared by using DECIMAL(i,j) or DEC(i,j) – where i is the precision i.e, the total number of
decimal digits and j is the scale i.e, the number of digits after the decimal point.
ii) Character-string: These data types are either fixed length CHAR(n) or CHARACTER(n), where n is the number of
characters or varying length VARCHAR(n) or CHAR VARYING(n) or CHARACTER VARYING(n), where n
is the maximum number of characters.
iii) Bit-string: These data types are either of fixed length n - BIT(n) or varying length – BIT VARYING(n), where n is
the maximum number of bits.
iv) Boolean: This data type has the traditional values of TRUE or FALSE. In SQL, because of the presence of NULL
values, a three-valued logic is used, a third possible value for a Boolean data type is UNKNOWN.
v) Date: This data type has ten positions and its components are YEAR, MONTH and DAY in the form YYYY-MM-
DD.
vi) TIME: This data type has atleast eight positions, with the components HOUR, MINUTE and SECOND in the form
HH:MM:SS.
vii) Timestamp: This data type includes the DATE and TIME fields, plus a maximum of six positions for decimal
fractions of seconds and an optional WITH TIME ZONE qualifier.

The following constraints are commonly used in SQL:


 NOT NULL: It ensures that a column cannot have a NULL value.
 UNIQUE: It ensures that all values in a column are different
 PRIMARY KEY: It is combination of NOT NULL and UNIQUE. It Uniquely identifies each row in a table.
 FOREIGN KEY: It prevents actions that would destroy links between tables.
 CHECK: It ensures that the values in a column satisfies a specific condition.
 DEFAULT: It sets a default value for a column if no value is specified
 CREATE INDEX: It is used to create and retrieve data from the database very quickly.
10) Describe the different clauses of select statement with suitable example.
Soln:

11) Explain informal design guidelines for relational schemas.


Soln:
There are 4 informal design guidelines. They are,
i) Semantics of relations attributes
 It specifies how to interpret the attributes values stored in a tuple of the relation. In other words, how the
attribute value in a tuple relate to one another.
 Guideline 1: Design a relation schema so that it is easy to explain its meaning. Do not combine attributes
from multiple entity types and relationship types into a single relation.

ii) Reducing redundant values in tuples


 It saves storage space and avoid update anomalies.
 Insertion Anomalies: To insert a new employee tuple into EMP_DEPT, it must include either the attribute
values for that department that the employee works for, or nulls. It’s difficult to insert a new department that
has no employee as yet in the EMP_DEPT relation. The only way to do this is to place null values in the
attributes for employee. This causes a problem because SSN in the primary key of EMP_DEPT and each
tuple is supposed to represent an employee entity, not a department entity.
 Deletion Anomalies: If an employee tuple is deleted from EMP_DEPT that happens to represent the last
employee working for a particular department and the information concerning that department is lost from
the database.
 Modification Anomalies: In EMP_DEPT, if the value of one of the attributes of a particular department is
changed, say the manager of department 5, then all employees in the tuple who work in that department
have to be updated.
 Guideline 2: Design the base relation schemas so that no insertion, deletion, or modification anomalies occur,
thereby reducing the null values in tuples.

iii) Reducing the null values in tuples


 Null’s can have multiple interpretations such as, the attribute does not apply to this tuple (or) The attribute
value for this tuple is unknown (or) the value known, but absent i.e, it has not been recorded yet.
 Guideline 3: Avoid placing attributes in a base relation whose values are mostly null.

iv) Generation of spurious tuples


 Spurious tuples are the tuples that are not in the original relation but generated by natural join of decomposed
sub-relations.
 Guideline 4: Design relation schemas so that they can be naturally joined on primary keys or foreign keys in
a way that guarantees no spurious tuples are generated.
12) What is the need of Normalization. Explain 1NF, 2NF, 3NF with an example.
Soln:
The process of decomposing a relation with anomalies into small relations is called Normalization.
The need for Normalization is,
i) To ensure data integrity: The relation should satisfy all integrity constraints.
ii) To remove data redundancy: Prevent insert, delete, update anomalies… since the data is available in one table in
the database.
13) Consider the following company database:
EMP(Name, SSN, Salary, SuperSSN, Gender, Dno)
DEPT(DNum, Dname, MgrSSN, Dno)
DEPT_LOC(Dnum, Dlocation)
DEPENDENT(ESSN, Dep_name, Sex)
WORKS_ON(ESSN, Pno, Hours)
PROJECT(Pname, Pnumber, Plocation, Dnum)
Write the relational algebra queries for the following:
i) Retrieve the name, address, salary of employees who work for the Research department.
ii) Find the names of employees who work on all projects controlled by department number 4.
iii) List all projects that Raj Yadav works on by project name.
iv) List all pair of employee names and project numbers they work on.
v) Retrieve each department number, the number of employees in the department and their average salary.
Soln:
14) Considering the schema:
Sailors(sid, sname, rating, age)
Boats(bid, bname, color)
Reserves(sid, bid, day)
Write relational algebra queries for the following:
i) Retrieve the sailor name with age over 20 years and reserved black boat.
ii) Retrieve the sailor name who have reserved all boats.
iii) Retrieve the sailor name who have reserved green boat on Monday.
iv) Retrieve the number of boats which are reserved
v) Retrieve the sailor names who is the oldest sailor with rating 10.
Soln:

You might also like