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

23mca005 Dbms File

The document provides a lab workbook for the Database Management System course. It includes details about experiments to be performed on the COMPANY database such as designing an ER diagram, creating relational tables, using SQL queries and functions, implementing triggers, and comparing relational and NoSQL databases. The workbook also contains sections for student and faculty details as well as an index of the experiments and their outcomes.

Uploaded by

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

23mca005 Dbms File

The document provides a lab workbook for the Database Management System course. It includes details about experiments to be performed on the COMPANY database such as designing an ER diagram, creating relational tables, using SQL queries and functions, implementing triggers, and comparing relational and NoSQL databases. The workbook also contains sections for student and faculty details as well as an index of the experiments and their outcomes.

Uploaded by

Harsh Gandhi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 113

Database Management System

(CSL 214)

Lab Workbook

Faculty Name: Dr Nidhi Malik Student Name: Harsh Gandhi

Roll No.:23MCA008

Semester:1st

Department of Computer Science and Engineering

The NorthCap University, Gurugram- 122017, India

Session 2022-23
DBMS Lab Workbook (CSL214) | 2
2022-23

Student Name:

Student Roll No.:

INDEX

Date of Date of Sign CO Sign


S.No Experiment Title
Experiment Submission Student Covered Faculty
Design an ER/EER diagram for the
1 CO2
COMPANY database.
Design a Relational Database
Schema for the COMPANY
2 database from the ER/EER CO2
diagram.

To apply SQL integrity constraints


3 as per the DDL statements given CO3
below for COMPANY database.

To familiarize with SELECT-


FROM-WHERE SQL simple
4 queries on the COMPANY CO3
database.

To familiarize with JOIN


5 operations in SQL on the CO3
COMPANY database.

To understand Aggregate functions


6 using SQL queries on the CO3
COMPANY database.

7 To implement triggers in SQL CO4

To familiarize with nested SQL


queries on the COMPANY CO3/
8
database. CO4

Identifying contrast between


9 CO5
Relational Databases and NoSQL,
DBMS Lab Workbook (CSL214) | 3
2022-23

thereby recognizing their


applications.

Create COMPANY database using


10 NoSQL database - MongoDB. CO5

Retrieve data from NoSQL


11 database - MongoDB. CO5

VA - Design an ER/ EER CO2,


12 Diagram, relational schema.
CO5
DBMS Lab Workbook (CSL214) | 4
2022-23

Experiment No: 1
Student Name and Roll Number: Harsh Gandhi 23MCA008

Semester /Section: 1st

Link to Code:

Date:
Faculty Signature:

Marks:

Objective

Design an ER/EER diagram for the COMPANY database.

Program Outcome

 The students will be able to draw conceptual database design using ERD Plus.

Problem Statement

1. The COMPANY database keeps track of a company’s employees, departments, and projects.
Suppose that after the requirements collection and analysis phase, the database designers provide
the following description of the mini world—the part of the company that will be represented in
the database.

 A department controls several projects, each of which has a unique


name, a unique number, and a single location.
 The company is organized into departments. Each department has a unique
name, a unique number, and a particular employee who manages the
department. We keep track of the start date when that employee began managing the
department. A department may have several locations.
DBMS Lab Workbook (CSL214) | 5
2022-23

 We store each employee’s name, Social Security number, address, salary, sex
(gender), and birth date. An employee is assigned to one department, but
may work on several projects, which are not necessarily controlled by the
same department. We keep track of the current number of hours per week
that an employee works on each project. We also keep track of the direct
supervisor of each employee (who is another employee).
 We want to keep track of the dependents of each employee for insurance
purposes. We keep each dependent’s first name, sex, birth date, and relationship to the
employee.

2. Design an ER/EER diagram for keeping track of the exploits of your favourite sports team.
You should store the matches played, the scores in each match, the players in each match and
individual player statistics for each match. Summary statistics should be modelled as derived
attributes. Further, extend the E-R diagram of the previous question to track the same
information for all teams in a league.

Design the ER/EER model by identifying the following from the above requirements:

i) Entities (Strong and Weak)


ii) Relationships
iii) Participation constraints
iv) Various types of attributes
v) Recursive relations
vi) Mapping cardinalities
vii) Binary/Ternary relationship
viii) Specialization/Generalization etc.

Background Study

ER Diagram Symbols and Notations:

1) Entity:
o Real-world object distinguishable from other objects.
o An entity is described using a set of attributes.

2) Entity Set: A collection of similar entities. Eg: all employees.

o All entities in an entity set have the same set of attributes.


DBMS Lab Workbook (CSL214) | 6
2022-23

o Each entity set has a key.

o Each attribute has a domain.

3) .
o Attributes are properties used to describe an entity.
o Example: EMPLOYEE entity may have a Name, SSN, Address, Sex, BirthDate.

4) Relationship
o A relationship relates two or more distinct entities with a specific meaning.
o Relationships of the same type are grouped or typed into a relationship type.
o 3 types of relationships : Unary, Binary & Ternary.
5) Recursive Relationship
o A relationship with the same participating entity type in distinct roles.
o Example: the SUPERVISION relationship
6) Structural Constraints – Semantics of Relationships
o Cardinality Ratio : The number of instances of an entity from a relation that can
be associated with the relation.
o Participation Constraints
 Total Participation − Each entity is involved in the relationship.
DBMS Lab Workbook (CSL214) | 7
2022-23

 Partial participation − Not all entities are involved in the relationship.

ER Diagram

Preparatory Questions
DBMS Lab Workbook (CSL214) | 8
2022-23

Q1) Given the basic ER and relational models, which of the following is INCORRECT?

1) An attribute of an entity can have more than one value


2) An attribute of an entity can be composite
3) In a row of a relational table, an attribute can have more than one value
4) In a row of a relational table, an attribute can have exactly one value or a NULL value

Q2) Consider a directed line(-->) from the relationship set advisor to both entity sets instructor
and student. This indicates _________ cardinality
1) One to many
2) One to one
3) Many to many
4) Many to one

Q3) An entity set that does not have sufficient attributes to form a primary key is termed as :
1) Strong entity set
2) Variant set
3) Weak entity set
4) Variable set

Q4) Which of the following indicates the maximum number of entities can be involved in a
relationship?

1) Minimum cardinality
2) Maximum Cardinality
3) ERD
4) Greater Entity Count (GEC)

Q5) State true or false: Every weak entity must be associated with and identifying entity.

1) True
2) False
DBMS Lab Workbook (CSL214) | 9
2022-23

Experiment No: 2
Student Name and Roll Number: Harsh Gandhi 23MCA008

Semester /Section: 1st

Link to Code:

Date:
Faculty Signature:

Marks:

Program Outcome

 The students will be able to map the conceptual database design to logical (relational)
database design.

Problem Statement

Map the ER/EER diagram of the COMPANY database created in the previous experiment to
Relational Database Schema. Follow the below mentioned steps to successfully map ER/EER
model to relational tables:

Step 1: Mapping of Regular Entity Types

Step 2: Mapping of Weak Entity Types

Step 3: Mapping of Binary 1:1 Relation Types


DBMS Lab Workbook (CSL214) | 10
2022-23

Step 4: Mapping of Binary 1:N Relationship Types

Step 5: Mapping of Binary M:N Relationship Types

Step 6: Mapping of Multivalued attributes

Step 7: Mapping of N-ary Relationship Types

Step 8: Mapping EER Model Constructs to Relations

Step 9: Options for Mapping Specialization or Generalization

Step 10: Mapping of Union Types (Categories)

Background Study

1) Mapping of Regular Entity Types


o For each regular (strong) entity type E in the ER schema, 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 the chosen key of E is composite, the set of simple attributes that form it will
together form the primary key of R.

2) Mapping of Weak Entity Types


o For each weak entity type W in the ER schema with owner entity type E, create a
relation R and include all simple attributes (or simple components of composite
attributes) of W as attributes of R.
o Include as foreign key attributes of R the primary key attribute(s) of the relation(s) that
correspond to the owner entity type(s).

3) Mapping of Binary 1:1 Relationship Types


o For each binary 1:1 relationship type R in the ER schema, identify the relations S and T
that correspond to the entity types participating in R. This has 3 approaches :
 Foreign Key Approach
 Merged Relation Option
 Cross-reference or Relationship Relation Option

4) Mapping of Binary 1:N Relationship Types


DBMS Lab Workbook (CSL214) | 11
2022-23

o 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.
o Include as foreign key in S the primary key of the relation T that represents the other
entity type participating in R.

5) Mapping of Binary M:N Relationship Types


o For each regular binary M:N relationship type R, create a new relation S to represent R.
o 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.

6) Mapping of Multi-valued attributes


o For each multi-valued 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.

7) Mapping of N-ary Relationship Types


o For each n-ary relationship type R, where n>2, create a new relationship S to represent R.
o Include as foreign key attributes in S the primary keys of the relations that represent the
participating entity types.

8) Options for Mapping Specialization or Generalization


o Convert each specialization with m subclasses {S 1, S2,….,Sm} and generalized superclass
C, where the attributes of C are {k,a 1,…an} and k is the (primary) key, into relational
schemas using 1 of the following :
1) Multiple relations-Superclass and subclasses.
2) Multiple relations-Subclass relations only :
3) Single relation with one type attribute
4) Single relation with multiple type attributes.

9) Mapping of Union Types (Categories)


o For mapping a category whose defining superclass have different keys, it is customary to
specify a new key attribute, called a surrogate key, when creating a relation to
correspond to the category.
DBMS Lab Workbook (CSL214) | 12
2022-23

Relational Database Design

Employee:

Fname Minit Lname Ssn Bdate Address Sex Salary Super_ssn Dno

Department:

Dname Dnumber Mgr_ssn Mgr_start_date

Dept_Locations:

Dnumber Dlocation

Project:

Pname Pnumber Plocation Dnum

Works_on:

Essn Pno Hours


DBMS Lab Workbook (CSL214) | 13
2022-23

Dependent:

Essn Dependent_name Sex Bdate Relationship

Preparatory Questions

Q1) In which of the following, a separate schema is created consisting of that attribute and the
primary key of the entity set.
1) A many-to-many relationship set
2) A multivalued attribute of an entity set
3) A one-to-many relationship set
4) All of the mentioned

Q2) Consider the following ER diagram

The minimum number of tables needed to represent M, N, P, R1, R2 is

1) 2
2) 3
3) 4
4) 5

Q3) Consider the data given in above question. Which of the following is a correct attribute set
for one of the tables for the correct answer to the above question?

1) {M1, M2, M3, P1}


DBMS Lab Workbook (CSL214) | 14
2022-23

2) {M1, P1, N1, N2}


3) {M1, P1, N1}
4) {M1, P1}

Q4) Let E1 and E2 be two entities in an E/R diagram with simple single-valued attributes. R1
and R2 are two relationships between E1 and E2, where R1 is one-to-many and R2 is many-to-
many. R1 and R2 do not have any attributes of their own. What is the minimum number of tables
required to represent this situation in the relational model?

1) 2
2) 3
3) 4
4) 5

Q5) What is the min and max number of tables required to convert an ER diagram with 2 entities
and 1 relationship between them with partial participation constraints of both entities?

1) Min 1 and max 2


2) Min 1 and max 3
3) Min 2 and max 3
4) Min 2 and max 2
DBMS Lab Workbook (CSL214) | 15
2022-23

Experiment No: 3
Student Name and Roll Number: Harsh Gandhi 23MCA008

Semester /Section: 1st

Link to Code:

Date:
Faculty Signature:

Marks:

Objective

To apply SQL integrity constraints as per the DDL statements given below for COMPANY
database.

Program Outcome

 The students will understand how a database is created followed by insertion of relevant data.
DBMS Lab Workbook (CSL214) | 16
2022-23

 The students will understand the need of applying various types of integrity constraints such
as primary key, foreign key, unique key, NOT NULL, default and CHECK etc

Problem Statement
DBMS Lab Workbook (CSL214) | 17
2022-23

Implement the following types of integrity constraints:

1) Primary Key
2) Foreign Key
3) Unique
4) Default
5) Auto-increment
6) Check
7) Not Null

Background Study

1) Primary Key Constraint: A column or group of columns in a table which helps us to uniquely
identifies every row in that table is called a primary key. This DBMS can't be a duplicate.
The same value can't appear more than once in the table.

Syntax to define a Primary key at column level:


DBMS Lab Workbook (CSL214) | 18
2022-23

column name datatype [CONSTRAINT constraint_name] PRIMARY KEY

Syntax to define a Primary key at table level:


[CONSTRAINT constraint_name] PRIMARY KEY (column_name1,column_name2,..)

Rules for defining Primary key:

o Two rows can't have the same primary key value


o It must for every row to have a primary key value.
o The primary key field cannot be null.
o The value in a primary key column can never be modified or updated if any
foreign key refers to that primary key.

2) Foreign Key (Referential integrity constraint): This constraint identifies any column
referencing the PRIMARY KEY in another table. It establishes a relationship between two
columns in the same table or between different tables. For a column to be defined as a
Foreign Key, it should be a defined as a Primary Key in the table which it is referring. One
or more columns can be defined as Foreign key.
Syntax to define a Foreign key at column level:
[CONSTRAINT constraint_name] REFERENCES Referenced_Table_name(column_name)

Syntax to define a Foreign key at table level:


[CONSTRAINT constraint_name] FOREIGN KEY(column_name) REFERENCES
referenced_table_name(column_name);

3) SQL Not Null Constraint : This constraint ensures all rows in the table contain a definite
value for the column which is specified as not null. Which means a null value is not
allowed.

Syntax to define a Not Null constraint:


[CONSTRAINT constraint name] NOT NULL

4) SQL Unique Key: This constraint ensures that a column or a group of columns in each row
have a distinct value. A column(s) can have a null value but the values cannot be
duplicated.

Syntax to define a Unique key at column level:


DBMS Lab Workbook (CSL214) | 19
2022-23

[CONSTRAINT constraint_name] UNIQUE

Syntax to define a Unique key at table level:


[CONSTRAINT constraint_name] UNIQUE(column_name)

5) SQL Check Constraint : This constraint defines a business rule on a column. All the rows
must satisfy this rule. The constraint can be applied for a single column or a group of
columns.
Syntax to define a Check constraint:
[CONSTRAINT constraint_name] CHECK (condition)

Output: Screenshots

Creating Table Employee :


DBMS Lab Workbook (CSL214) | 20
2022-23

Creating Table Department :


DBMS Lab Workbook (CSL214) | 21
2022-23

Creating Table Dept_Locations :

Creating table Project :

Creating table works_on :

Creating table dependent :


DBMS Lab Workbook (CSL214) | 22
2022-23

Inserted Values :

Employee :

Department :
DBMS Lab Workbook (CSL214) | 23
2022-23

Dependent :

Dept_locations :
DBMS Lab Workbook (CSL214) | 24
2022-23

Project :

Works_on :
DBMS Lab Workbook (CSL214) | 25
2022-23

Preparatory Questions

1) Suppose (A, B) and (C,D) are two relation schemas. Let r1 and r2 be the corresponding
relation instances. B is a foreign key that refers to C in r2. If data in r1 and r2 satisfy
referential integrity constraints, which of the following is ALWAYS TRUE?

1) A
2) B
3) C
4) D

2) Given the following statements:


S1: A foreign key declaration can always be replaced by an equivalent check assertion in
SQL.
S2: Given the table R(a,b,c) where a and b together form the primary key, the following is a
valid table definition.

CREATE TABLE S (
a INTEGER,
DBMS Lab Workbook (CSL214) | 26
2022-23

d INTEGER,
e INTEGER,
PRIMARY KEY (d),
FOREIGN KEY (a) references R)

Which one of the following statements is CORRECT?


1) S1 is TRUE and S2 is FALSE.
2) Both S1 and S2 are TRUE.
3) S1 is FALSE and S2 is TRUE.
4) Both S1 and S2 are FALSE

Q3) Which of the following is not an integrity constraint?


1) Not null
2) Positive
3) Unique
4) Check ‘predicate’

Q4) CREATE TABLE Manager(ID NUMERIC,Name VARCHAR(20),budget NUMERIC,Details


VARCHAR(30));
In order to ensure that the value of budget is non-negative which of the following should be
used?
1)Check(budget>0)
2)Check(budget<0)
3)Alter(budget>0)
4) Alter(budget<0)

Q5) The following table has two attributes A and C where A is the primary key and C is the
foreign key referencing A with on-delete cascade.

A C
2 4
3 4
4 3
5 2
7 2
9 5
DBMS Lab Workbook (CSL214) | 27
2022-23

6 4

The set of all tuples that must be additionally deleted to preserve referential integrity when the
tuple (2,4) is deleted is:

1) (3,4) and (6,4)


2) (5,2) and (7,2)
3) (5,2), (7,2) and (9,5)
4) (3,4), (4,3) and (6,4)
DBMS Lab Workbook (CSL214) | 28
2022-23

Experiment No: 4
Student Name and Roll Number: Harsh Gandhi 23MCA008

Semester /Section: 1st

Link to Code:

Date:
Faculty Signature:

Marks:

Objective

To familiarize with SELECT-FROM-WHERE SQL simple queries on the COMPANY database.

Program Outcome

 The students will be able to retrieve zero or more rows from one or more database tables or
database views.

Problem Statement

From the COMPANY database as mentioned and described in the previous database :

1) Retrieve the birth date and address of the employee(s) whose name
is ‘John B. Smith’.
2) Retrieve the name and address of all employees who work for the ‘Research’ department.
DBMS Lab Workbook (CSL214) | 29
2022-23

3) For every project located in ‘Stafford’, list the project number, the
controlling department number, and the department manager’s last name,
address, and birth date
4) Select all combinations of EMPLOYEE Ssn and DEPARTMENT Dname in the database.
5) Retrieve all the attribute values of any EMPLOYEE who works in DEPARTMENT
number 5.
6) Retrieve all distinct salary values.
7) Make a list of all project numbers for projects that involve an employee whose last name
is ‘Smith’, either as a worker or as a manager of the department that controls the project.
8) Retrieve all employees whose address is in Houston, Texas.
9) Find all employees who were born during the 1950s
10) Show the resulting salaries if every employee working on the ‘ProductX’ project is given
a 10 percent raise.
11) Retrieve a list of employees and the projects they are working on, ordered by department
and, within each department, ordered alphabetically by last name, then first name.

Background Study

1) Structured Query Language SQL contains statements for data definitions, queries, and
updates (both DDL and DML)

2) Domain
o Name used with the attribute specification
o Makes it easier to change the data type for a domain that is used by numerous
attributes

3) Inserting values in our table using the commands :


INSERT INTO EMPLOYEE (Fname, Lname, Dno, Ssn)

VALUES (‘Richard’, ‘Marini’, 4, ‘653298653’)

4) Out of the complete Database we create we can easily pick out and filter certain amount
of data by using the SQL queries as :

SELECT <attribute list>


DBMS Lab Workbook (CSL214) | 30
2022-23

FROM <table list>

WHERE <condition>;

o <attribute list> is a list of attribute names whose values are to be retrieved by the
query.
o <table list> is a list of the relation names required to process the query.
o <condition> is a conditional (Boolean) expression that identifies the tuples to be
retrieved by the query.

5) Ambiguous Attribute Names: Same name can be used for two (or more) attributes as long
as the attributes are in different relations, these are made to differ by mentioning their
table names before the attribute names.
6) Aliasing, Renaming Tuple variables: We can rename the tables into some smaller easier
names as per choice when it has to be used multiple times in the query.

7) DISTINCT keyword is used when the query wishes to derive no two duplicate values.

8) SET operations such as UNION and INTERSECT can also be applied on the tables to
filter out the values as per choice.

9) Substring Pattern matching is carried out by the use of the keyword LIKE which helps in
retrieving the column values of the tuple matching our mentioned substring.

10) ORDERBY <attributes>


o Helps in sorting the tuple values of the attributes by default set to ascending and can
be changed to descending .

Output: Screenshots

1) Retrieve the birth date and address of the employee(s) whose name
is ‘John B. Smith’.
DBMS Lab Workbook (CSL214) | 31
2022-23

2) Retrieve the name and address of all employees who work for the ‘Research’ department.

3) For every project located in ‘Stafford’, list the project number, the
controlling department number, and the department manager’s last name,
address, and birth date

4) Select all combinations of EMPLOYEE Ssn and DEPARTMENT Dname in the database.
DBMS Lab Workbook (CSL214) | 32
2022-23

5) Retrieve all the attribute values of any EMPLOYEE who works in DEPARTMENT
number 5

6) Retrieve all distinct salary values.


DBMS Lab Workbook (CSL214) | 33
2022-23

7) Make a list of all project numbers for projects that involve an employee whose last name
is ‘Smith’, either as a worker or as a manager of the department that controls the
project.

8) Retrieve all employees whose address is in Houston, Texas


DBMS Lab Workbook (CSL214) | 34
2022-23

9) Find all employees who were born during the 1950s

10) Show the resulting salaries if every employee working on the ‘ProductX’ project is given
a 10 percent raise.

11) Retrieve a list of employees and the projects they are working on, ordered by department
and, within each department, ordered alphabetically by last name, then first name.
DBMS Lab Workbook (CSL214) | 35
2022-23
DBMS Lab Workbook (CSL214) | 36
2022-23

Preparatory Questions

Q1) Which operator performs Pattern matching ?

1) BETWEEN operator
2) LIKE operator
3) EXISTS operator
4) None of the above

Q2) In SQL which commands are used to change the storage characteristics of the table?

1) ALTER TABLE
2) MODIFY TABLE
3) CHANGE TABLE
4) All of the above

Q3) ___________removes all rows from a table without logging the individual row deletions.
1) DELETE
2) REMOVE
3) DROP
4) TRUNCATE

Q4) If you don’t specify ASC or DESC after a SQL ORDER BY clause, the following is used by
default :
1) ASC
2) DESC
3) There is no default value
4) None of the mentioned

Q5) What is the purpose of the SQL AS clause?


1) The AS SQL clause is used to change the name of a column in the result set or to assign a
name to a derived column
2) The AS clause is used with the JOIN clause only
3) The AS clause defines a search condition
4) All of the mentioned
DBMS Lab Workbook (CSL214) | 37
2022-23

Experiment No: 5
Student Name and Roll Number: Harsh Gandhi 23MCA008

Semester /Section: 1st

Link to Code:

Date:
Faculty Signature:

Marks:

Objective

To familiarize with JOIN operations in SQL on the COMPANY database.

Program Outcome

 The students will be to establish a connection between two or more database tables based on
matching columns, thereby creating a relationship between the tables.

Problem Statement

Consider the Sample database given below and answer the queries as stated:

Pack_grades

Grade_id Grade_name Min_price Max_price


Customers

Customer_i First_name Last_name Birth_date Join_date City Pack_id State


d

Packages
DBMS Lab Workbook (CSL214) | 38
2022-23

Pack_id Speed Start_date Monthly_payment Sector_id

Sectors

Sector_id Sector_name

1) Write a query to display first name, last name, package number and internet speed for all
customers.
2) Write a query to display first name, last name, package number and internet speed for all
customers whose package number equals 22 or 27. Order the query in ascending order by last
name.
3) Display the package number, internet speed, monthly payment and sector name for all
packages (Packages and Sectors tables).
4) Display the customer name, package number, internet speed, monthly payment and sector
name for all customers (Customers, Packages and Sectors tables).
5) Display the customer name, package number, internet speed, monthly payment and sector
name for all customers in the business sector (Customers, Packages and Sectors tables).
6) Display the last name, first name, join date, package number, internet speed and sector name
for all customers in the private sector who joined the company in the year 2006.
7) Display the package number, internet speed, monthly payment and package grade for all
packages (Packages and Pack_Grades tables).
8) Display the first name, last name, internet speed and monthly payment for all customers. Use
INNER JOIN to solve this exercise.
9) Display the last name, first name and package number for all customers who have the same
package number as customer named ‘Amado Taylor’ (Customers table).
10) Display the package number and internet speed for all packages whose internet speed is
equal to the internet speed of package number 10 (Packages table).

Background Study

1) JOINED TABLE: Permits users to specify a table resulting from a join operation in the
FROM clause of a query
o The attributes of such a table are all the attributes of the first table followed by all the
attributes of the second table.
DBMS Lab Workbook (CSL214) | 39
2022-23

o The default type of join in a joined table is called an inner join, where a tuple is included
in the result only if a matching tuple exists in the other relation.

2) NATURAL JOIN on two relations R and S


o No join condition specified.
o Implicit EQUIJOIN condition for each pair of attributes with same name from R & S

o It is possible to rename the attributes so that they match, if the names of the join attributes
are not the same in the base relations.

3) LEFT OUTER JOIN


o Every tuple in left table must appear in result
o If no matching tuple, padded with NULL values for attributes of right table

4) RIGHT OUTER JOIN


o Every tuple in right table must appear in result
o If no matching tuple, padded with NULL values for the attributes of left table

5) FULL OUTER JOIN


o Used when both the tables are taken completely

6) CROSS JOIN – for Cartesian Product

Output: Screenshots

1) Write a query to display first name, last name, package number and
internet speed for all customers.
DBMS Lab Workbook (CSL214) | 40
2022-23

2) Write a query to display first name, last name, package number and
internet speed for all customers whose package number equals 22 or 27.
Order the query in ascending order by last name.

3) Display the package number, internet speed, monthly payment and sector
name for all packages (Packages and Sectors tables).
DBMS Lab Workbook (CSL214) | 41
2022-23

4) Display the customer name, package number, internet speed, monthly


payment and sector name for all
customers (Customers, Packages and Sectors tables).

5) Display the last name, first name, join date, package number, internet
speed and sector name for all customers in the private sector who joined
the company in the year 2006.

6) Display the package number, internet speed, monthly payment and


package grade for all packages (Packages and Pack_Grades tables).
DBMS Lab Workbook (CSL214) | 42
2022-23


7) Display the first name, last name, internet speed and monthly payment for all
customers. Use INNER JOIN to solve this exercise.

8) Display the last name, first name and package number for all customers who have
the same package number as customer named ‘Amado Taylor’ (Customers table).
DBMS Lab Workbook (CSL214) | 43
2022-23

9) Display the package number and internet speed for all packages whose internet
speed is equal to the internet speed of package number 10 (Packages table).

Preparatory Questions

Q1) Database table by name Loan_Records is given below.

Borrower Bank_Manager Loan_Amount


Ramesh Sunderajan 10000.00
Suresh Ramgopal 5000.00
Mahesh Sunderajan 7000.00

What is the output of the following SQL query?

SELECT Count(*)
FROM ( ( SELECT Borrower, Bank_Manager
FROM Loan_Records) AS S
NATURAL JOIN ( SELECT Bank_Manager, Loan_Amount
DBMS Lab Workbook (CSL214) | 44
2022-23

FROM Loan_Records) AS T );

1) 3
2) 9
3) 5
4) 6

Q2) Which product is returned in a join query have no join condition:


1) Equijoins
2) Cartesian
3) Both Equijoins and Cartesian
4) None of the mentioned

Q3) Which join refers to join records from the write table that have no matching key in the left
table are include in the result set:
1) Left outer join
2) Right outer join
3) Full outer join
4) Half outer join

Q4) Which operation are allowed in a join view:


1) UPDATE
2) INSERT
3) DELETE
4) All of the mentioned

Q5) Which view that contains more than one table in the top-level FROM clause of the SELECT
statement:
1) Join view
2) Datable join view
3) Updatable join view
4) All of the mentioned
DBMS Lab Workbook (CSL214) | 45
2022-23

Experiment No: 6
Student Name and Roll Number: Harsh Gandhi 23MCA008

Semester /Section: 1st

Link to Code:

Date:
Faculty Signature:

Marks:

Objective

To understand Aggregate functions using SQL queries on the COMPANY database.

Program Outcome
DBMS Lab Workbook (CSL214) | 46
2022-23

 The students will understand the need of applying an aggregate function to get a single value
from a set of values, thus, expressing the significance of the data it is computed from.

Problem Statement

Consider the COMPANY database in Experiment 1 and execute the following queries:

1) Find the sum of the salaries of all employees, the maximum salary, the minimum salary,
and the average salary.
2) Find the sum of the salaries of all employees of the ‘Research’ department, as well as the
maximum salary, the minimum salary, and the average salary in this department.
3) Retrieve the total number of employees in the company.
4) Retrieve the number of employees in the ‘Research’ department.
5) Count the number of distinct salary values in the database
6) For each department, retrieve the department number, the number of employees in the
department, and their average salary.
7) For each project, retrieve the project number, the project name, and the number of
employees who work on that project.
8) For each project on which more than two employees work, retrieve the project number,
the project name, and the number of employees who work on the project
9) For each project, retrieve the project number, the project name, and the number of
employees from department 5 who work on the project.
10) For each department that has more than five employees, retrieve the department number
and the number of its employees who are making more than $40,000.

Background Study

1) Aggregate Functions: Used to summarize information from multiple tuples into a single-
tuple summary

2) Grouping: Create subgroups of tuples before summarizing

3) Built-in aggregate functions: COUNT, SUM, MAX, MIN, and AVG (NULL values
discarded when aggregate functions are applied to a particular column)

4) Functions can be used in the SELECT clause or in a HAVING clause

5) Partition relation into subsets of tuples


DBMS Lab Workbook (CSL214) | 47
2022-23

o Based on grouping attribute(s)


o Apply function to each such group independently

6) GROUP BY clause: Specifies grouping attributes

7) If NULLs exist in grouping attribute, then separate group created for all tuples with a
NULL value in grouping attribute

8) HAVING clause provides a condition on the summary information

9) SELECT clause includes only the grouping attribute and the aggregate functions to be
applied on each group of tuples.

10) WHERE clause limit the tuples to which functions are applied, the HAVING clause
serves to choose whole groups

Output: Screenshots

1) Find the sum of the salaries of all employees, the maximum salary, the minimum
salary, and the average salary.
DBMS Lab Workbook (CSL214) | 48
2022-23

2) Find the sum of the salaries of all employees of the ‘Research’ department, as well
as the maximum salary, the minimum salary, and the average salary in this
department.

3) Retrieve the total number of employees in the company.

4) Retrieve the number of employees in the ‘Research’ department.

5) Count the number of distinct salary values in the database


DBMS Lab Workbook (CSL214) | 49
2022-23

6) For each department, retrieve the department number, the number of employees in
the department, and their average salary.

1) 7) For each project, retrieve the project number, the project name, and the number
of employees who work on that project.

8) For each project on which more than two employees work, retrieve the project
number, the project name, and the number of employees who work on the project.
DBMS Lab Workbook (CSL214) | 50
2022-23

9. For each project, retrieve the project number, the project name, and the number
of employees from department 5 who work on the project.

10. For each department that has more than five employees, retrieve the
department number and the number of its employees who are making more
than $40,000.

Preparatory Questions
DBMS Lab Workbook (CSL214) | 51
2022-23

Q1) Which of the following statements are TRUE about an SQL query? P: An SQL query can
contain a HAVING clause even if it does not have a GROUP BY clause Q : An SQL query can
contain a HAVING clause only if it has a GROUP BY clause R : All attributes used in the
GROUP BY clause must appear in the SELECT clause S : Not all attributes used in the GROUP
BY clause need to appear in the SELECT clause

1) P and R
2) P and S
3) Q and R
4) Q and S

Q2) Consider a database table T containing two columns X and Y each of type integer. After the
creation of the table, one record (X=1, Y=1) is inserted in the table. Let MX and My denote the
respective maximum values of X and Y among all records in the table at any point in time. Using
MX and MY, new records are inserted in the table 128 times with X and Y values being MX+1,
2*MY+1 respectively. It may be noted that each time after the insertion, values of MX and MY
change. What will be the output of the following SQL query after the steps mentioned above are
carried out?

SELECT Y FROM T WHERE X=7;


1) 127
2) 255
3) 129
4) 257

Q3) The employee information in a company is stored in the relation

Employee (name, sex, salary, deptName)

Consider the following SQL query


select deptName
from Employee
where sex = 'M'
group by deptName
having avg (salary) > (select avg (salary) from Employee)
It returns the names of the department in which
DBMS Lab Workbook (CSL214) | 52
2022-23

1) the average salary is more than the average salary in the company
2) the average salary of male employees is more than the average salary of all
male employees in the company
3) the average salary of male employees is more than the average salary of
employees in the same department
4) the average salary of male employees is more than the average salary in the
company

Q4) Which of the following is aggregate function in SQL?


1) Avg
2) Select
3) Ordered by
4) distinct

Q5) Observe the given SQL query and choose the correct option.

SELECT branch_name, COUNT (DISTINCT customer_name)


FROM depositor, account
WHERE depositor.account_number = account.account_number
GROUP BY branch_id
1) The query is syntactically correct but gives the wrong answer
2) The query is syntactically wrong
3) The query is syntactically correct and gives the correct answer
4) The query contains one or more wrongly named clauses.
DBMS Lab Workbook (CSL214) | 53
2022-23

Experiment No: 7
Student Name and Roll Number: Harsh Gandhi 23MCA008

Semester /Section: 1st

Link to Code:

Date:
Faculty Signature:

Marks:

Objective

To implement triggers in sql


DBMS Lab Workbook (CSL214) | 54
2022-23

Program Outcome

Trigger is a statement that a system executes automatically when there is any


modification to the database. In a trigger, we first specify when the trigger is to be
executed and then the action to be performed when the trigger executes. Triggers are
used to specify certain integrity constraints and referential constraints that cannot be
specified using the constraint mechanism of SQL.
Example –
Suppose, we are adding a tuple to the ‘Donors’ table that is some person has donated
blood. So, we can design a trigger that will automatically add the value of donated
blood to the ‘Blood_record’ table.

Types of Triggers –
We can define 6 types of triggers for each table:
1. AFTER INSERT activated after data is inserted into the table.

2. AFTER UPDATE: activated after data in the table is modified.

3. AFTER DELETE: activated after data is deleted/removed from the table.

4. BEFORE INSERT: activated before data is inserted into the table.

5. BEFORE UPDATE: activated before data in the table is modified.

6. BEFORE DELETE: activated before data is deleted/removed from the


table.

The students will understand how to implement triggers in sql.

Background study

CREATE [OR REPLACE] TRIGGER trigger_name

{BEFORE | AFTER | INSTEAD OF} {INSERT | UPDATE | DELETE}

ON table_name

[REFERENCING OLD AS old NEW AS new]

[FOR EACH ROW]


DBMS Lab Workbook (CSL214) | 55
2022-23

WHEN (condition)

BEGIN

-- Trigger body (SQL statements or PL/SQL block)

END;

OR REPLACE: This optional clause allows you to modify an existing trigger.


BEFORE | AFTER | INSTEAD OF: Specifies when the trigger should be executed.
INSERT | UPDATE | DELETE: Specifies the triggering event(s).
ON table_name: Specifies the table on which the trigger operates.
REFERENCING OLD AS old NEW AS new: Provides access to old and new values in
case of UPDATE or DELETE operations.
FOR EACH ROW: Indicates that the trigger is row-level, meaning it fires once for
each affected row.
WHEN (condition): Specifies a condition that must be true for the trigger to
execute.
BEGIN...END: Contains the SQL statements or PL/SQL block to be executed when
the trigger fires.

Output screen
DBMS Lab Workbook (CSL214) | 56
2022-23

Experiment No: 8
Student Name and Roll Number: Harsh Gandhi 23MCA008

Semester /Section: 1st

Link to Code:

Date:
DBMS Lab Workbook (CSL214) | 57
2022-23

Faculty Signature:

Marks:

Objective

To familiarize with nested SQL queries on the COMPANY database.

Program Outcome

 The students will understand how to devise independent and correlated nested queries.

Problem Statement

Consider the COMPANY database in Experiment 1 and execute the following queries:

1) Make a list of all project numbers for projects that involve an employee whose last name is
‘Smith’, either as a worker or as a manager of the department that controls the project.
a. Select the Essns of all employees who work on the same project and hours as some
project that employee ‘John Smith’ (whose Ssn = ‘123456789’) works on.
2) Return the names of employees whose salary is greater than the salary of all the employees in
department 5
3) Retrieve the name of each employee who has a dependent with the same first name and is the
same sex as the employee
4) Retrieve the names of employees who have no dependents
5) List the names of managers who have at least one dependent using EXISTS and NOT
EXISTS functions
6) Retrieve the name of each employee who works on all the projects controlled by department
number 5 using EXISTS and NOT EXISTS functions
7) Retrieve the names of all employees who have two or more dependents
8) Retrieves the names of all employees who work on only one project

Background Study
DBMS Lab Workbook (CSL214) | 58
2022-23

1) SQL allows queries that check whether an attribute value is NULL: IS or IS NOT NULL

2) Nested Queries: Complete select-from-where blocks within WHERE clause of another query
o Nested Queries generally return a table (relation)

3) Comparison Operator IN:


o Compares value v with a set (or multiset) of values V
o Evaluates to TRUE if v is one of the elements in V

4) = ANY (or = SOME) Operator: Returns TRUE if the value v is equal to some value in the set
V (equivalent to IN)

5) ALL Operator: (v > ALL V) returns TRUE if the value v is greater than all the values in the
set (or multiset) V.
o Other operators that can be combined with ANY (or SOME) and ALL: >, >=, <, <=,
and <>

6) Possible ambiguity among attribute names if attributes of the same name exist—one in a
relation in the FROM clause of the outer query, and another in a relation in the FROM clause
of the nested query.
o Thumb Rule: reference to an unqualified attribute refers to the relation declared in the
innermost nested query.

7) Whenever a condition in the WHERE clause of a nested query references some attribute of a
relation declared in the outer query, the two queries are said to be correlated.
o In a correlated query, the nested query is evaluated once for each tuple (or
combination of tuples) in the outer query

8) EXISTS function: Check whether the result of a correlated nested query is empty or not.

9) EXISTS and NOT EXISTS are typically used in conjunction with a correlated nested query.

10) EXISTS(Q): returns TRUE if there is at least one tuple in the result of the nested query Q,
and it returns FALSE otherwise.

11) NOT EXISTS(Q): returns TRUE if there are no tuples in the result of nested query Q, and it
returns FALSE otherwise.

Output: Screenshots
DBMS Lab Workbook (CSL214) | 59
2022-23

Preparatory Questions
DBMS Lab Workbook (CSL214) | 60
2022-23

Q1) Database table by name Loan_Records is given below.

Borrower Bank_Manager Loan_Amount


Ramesh Sunderajan 10000.00
Suresh Ramgopal 5000.00
Mahesh Sunderajan 7000.00

What is the output of the following SQL query?

SELECT Count(*)
FROM ( ( SELECT Borrower, Bank_Manager
FROM Loan_Records) AS S
NATURAL JOIN ( SELECT Bank_Manager, Loan_Amount
FROM Loan_Records) AS T );

1) 3
2) 9
3) 5
4) 6

Q2) A relational schema for a train reservation database is given below. Passenger (pid, pname,
age) Reservation (pid, class, tid)

Table: Passenger
pid pname age
-----------------
0 Sachin 65
1 Rahul 66
2 Sourav 67
3 Anil 69

Table : Reservation
pid class tid
---------------
0 AC 8200
1 AC 8201
2 SC 8201
5 AC 8203
DBMS Lab Workbook (CSL214) | 61
2022-23

1 SC 8204
3 AC 8202
What pids are returned by the following SQL query for the above instance of the tables?

SELECT pid
FROM Reservation ,
WHERE class ‘AC’ AND
EXISTS (SELECT *
FROM Passenger
WHERE age > 65 AND
Passenger. pid = Reservation.pid)
1) 1,0
2) 1,2
3) 1,3
4) 1,5

Q3) Consider the following relational schema:

Suppliers(sid:integer, sname:string, city:string, street:string)


Parts(pid:integer, pname:string, color:string)
Catalog(sid:integer, pid:integer, cost:real)

Consider the following relational query on the above database:


SELECT S.sname
FROM Suppliers S
WHERE S.sid NOT IN (SELECT C.sid
FROM Catalog C
WHERE C.pid NOT IN (SELECT P.pid
FROM Parts P
WHERE P.color<> 'blue'))
Assume that relations corresponding to the above schema are not empty. Which one of the
following is the correct interpretation of the above query?
DBMS Lab Workbook (CSL214) | 62
2022-23

1) Find the names of all suppliers who have supplied a non-blue part.
2) Find the names of all suppliers who have not supplied a non-blue part.
3) Find the names of all suppliers who have supplied only blue parts.
4) Find the names of all suppliers who have not supplied only blue parts.
5) None

Q4) Consider the table employee(empId, name, department, salary) and the two queries Q1 ,Q2
below. Assuming that department 5 has more than one employee, and we want to find the
employees who get higher salary than anyone in the department 5, which one of the statements is
TRUE for any arbitrary employee table?

Query1: Select e.empId


From employee e
Where not exists
(Select * From employee s where s.department = “5” and s.salary >=e.salary)

Query2: Select e.empId


From employee e
Where e.salary > Any
(Select distinct salary From employee s Where s.department = “5”)
1) Q1 is the correct query
2) Q2 is the correct query
3) Both Q1 and Q2 produce the same answer.
4) Neither Q1 nor Q2 is the correct query

Q5) Consider the following relational schema:

employee(empId, empName, empDept)


customer(custId, custName, salesRepId, rating)
DBMS Lab Workbook (CSL214) | 63
2022-23

salesRepId is a foreign key referring to empId of the employee relation. Assume that each
employee makes a sale to at least one customer. What does the following query return?

SELECT empName
FROM employee E
WHERE NOT EXISTS ( SELECT custId
FROM customer C
WHERE C.salesRepId = E.empId
AND C.rating <> `GOOD`);
1) Names of all the employees with at least one of their customers having a ‘GOOD’ rating.
2) Names of all the employees with at most one of their customers having a ‘GOOD’ rating.
3) Names of all the employees with none of their customers having a ‘GOOD’ rating.
4) Names of all the employees with all their customers having a ‘GOOD’ rating.

Experiment 9
Student Name and Roll Number: Harsh Gandhi 23MCA008
DBMS Lab Workbook (CSL214) | 64
2022-23

Semester /Section: 1st

Link to Code:

Date:
Faculty Signature:

Marks:

Objective

Identifying contrast between Relational Databases and NoSQL, thereby recognizing their
applications.

Program Outcome

 The students will install MongoDB shell and familiarize themselves with it.

Problem Statement

MongoDB installation and shell familiarity.

Background Study

MongoDB is a Schema less database. A database in MongoDB contains collections and inside
collections we have documents.

 Database is a physical container for collections. A single MongoDB server typically has
multiple databases.
 Collection is a group of MongoDB documents.
 Documents within a collection can have different fields. A document is a set of key-value
pairs and have dynamic schema. Dynamic schema means that documents in the same
collection do not need to have the same set of fields or structure, and common fields in a
collection's documents may hold different types of data.
DBMS Lab Workbook (CSL214) | 65
2022-23

RDBMS MongoDB

Relational database Non-relational and document-oriented


database
Need to design your tables, data structure, You can start coding without worrying
relations first. about tables and modify your objects at
a lesser cost of development.

Supports SQL query language Supports JSON query language


Table based Collection based and key-value pair
Row based Document based
Column based Field based
Each row will have same number of Each document can have different
columns number of fields
Primary Key Primary Key (Default key _id provided
by MongoDB itself)
Contains schema which is predefined Contains dynamic schema
DBMS Lab Workbook (CSL214) | 66
2022-23

Output: Screenshots
DBMS Lab Workbook (CSL214) | 67
2022-23
DBMS Lab Workbook (CSL214) | 68
2022-23

Preparatory Questions

Q1) Point out the correct statement:

1) A database is a set of key-value pairs


2) A MongoDB deployment hosts a number of databases
3) A document holds a set of collections
4) All of the mentioned

Q2) MongoDB stores all documents in:

1) tables
2) collections
3) rows
4) all the mentioned

Q3) BSON is a binary representation of ________ documents,

1) JSON
2) XML
3) JScript
4) All of the mentioned
DBMS Lab Workbook (CSL214) | 69
2022-23

Q4) The maximum size of a MongoDB document is

1) 2 MB
2) 16 MB
3) 12 MB
4) There is no maximum size. It depends on RAM

Q5) Which of the following statements is true?

1) MongoDB cannot be used as a file system.


2) MongoDB can run over single servers only.
3) Embedded documents and arrays reduce need for joins.
4) None
DBMS Lab Workbook (CSL214) | 70
2022-23

Experiment 10
Student Name and Roll Number: Harsh Gandhi 23MCA008

Semester /Section: 1st

Link to Code:

Date:
Faculty Signature:

Marks:

Objective

Create COMPANY database using NoSQL database - MongoDB.

Program Outcome

 The students will be able to perform basic CRUD operations in MongoDB.

Problem Statement

1) Create a COMPANY database with the following collections:


 Employee with fields Emp ID, Ename, Age, Mobile, Email, Address, Dno
 Department with fields Dnumber, Dname, Dlocation
 Project with fields Pname, Pnumber, Plocation, ControlDept

2) Insert 5 documents in each collection using different versions of “Insert” command.

3) Select all documents in a collection.

4) Retrieve the details of all projects that are being run in department number 50.
DBMS Lab Workbook (CSL214) | 71
2022-23

5) Retrieve the details of the first project that is being run in department number 50 in
formatted manner.

6) Return the formatted/structured project details of all projects in department number “5”
and project name as “ProductZ”.

7) Return the project details (including project name, project number and department
number and excluding project location and default primary key) of all projects with
department number “5” or project name as “ProductZ”.

8) Return the formatted/structured project details of all projects with department number
less than “10” and project name as “ProductZ” or project location as “Delhi”.

Background Study

1) use: This command is used to create a database in MongoDB. It will return an existing
database or will create a new database if it dosen’t exist.

2) createCollection( ): To create a collections in a database

3) MongoDB provides the following methods to insert documents into a collection:

4) db.collection.insert(): used to insert one or multiple documents. To insert multiple


documents in a single query, pass an array of documents in insert() command.

5) db.collection.insertOne(): used to insert only one document.

6) db.collection.insertMany(): used to insert multiple documents. To insert multiple


documents in a single query, pass an array of documents in insert() command.

7) db.collection.find(): this method is provided in MongoDB to read documents from a


collection. It returns a cursor to the matching documents. db.collection.find(<query
filter>, <projection>) accepts second optional parameter that is list of fields that you want
to retrieve in the form { field1: <value>, field2: <value> ... }.

8) db.collection.findOne(): it returns the first occurrence of document, otherwise null.


DBMS Lab Workbook (CSL214) | 72
2022-23

Output: Screenshots

1)

2) Employee
DBMS Lab Workbook (CSL214) | 73
2022-23

Department :

Project :

Preparatory Questions

Q1) Which of the following method is used to query documents in collections?

1) find
2) move
3) shell
4) replace

Q2) When you query a collection, MongoDB returns a ________ object that contains the results
of the query.
DBMS Lab Workbook (CSL214) | 74
2022-23

1) row
2) cursor
3) colums
4) none of the mentioned

Q3) Which of the following method is called while accessing documents using the array index
notation ?

1) cur.toArray()
2) cursor.toArray()
3) doc.toArray()
4) all of the mentioned

Q4) The mongo shell and the drivers provide several cursor methods that call on the cursor
returned by the _______ method to modify its behavior.

1) cursor()
2) find()
3) findc()
4) none of the mentioned

Q5) Which of the following method corresponds to Order by clause in SQL?

1) sort()
2) order()
3) orderby()
4) all of the mentioned
DBMS Lab Workbook (CSL214) | 75
2022-23

Experiment 11
Student Name and Roll Number: Harsh Gandhi 23MCA008

Semester /Section: 1st

Link to Code:

Date:
Faculty Signature:

Marks:

Objective

Retrieve data from NoSQL database - MongoDB.

Program Outcome
 The students will be able to perform advanced CRUD operations in MongoDB.

Problem Statement

Create a database with the following collections:

Project
Possible Fields:
 Project Name (Pname)
 Project Number (Pnumber)
 Department Number in which project is being run (Dnum)
DBMS Lab Workbook (CSL214) | 76
2022-23

 Project Locations (Plocation)


 Plocation can be an array of multiple locations (or)
 Plocation can be a composite field with sub-fields – city, state, country
Department
Possible Fields:
 Department Number (Dno)
 Department Name (Dname)
 Department Manager (Dmanager)

Execute the following queries:

1) Insert multiple documents (2-3) together in the Project collection with atleast 1 project
location as a composite attribute

2) Write the “Select * from Project” equivalent query in MongoDB.

3) Write a MongoDB query to update the project location of all projects to “Pune” and
department number to “20” with project name “ProjectX”.

4) Write a MongoDB query to delete all the documents of collection “Project” with
department number “4”.

5) Write a MongoDB query to retrieve the project details of all projects with project location
as “Delhi” and “Mumbai” both assuming the following documents exist.

{ "_id" : ObjectId("5cc7fe36e37496f1a5e7e268"),"Pname" : "ProductK", "Pnumber" :


45,"Plocation" : ["Delhi","Mumbai","Pune"], "Dnum" : 3}
{ "_id" : ObjectId("5cc7fe36e37496f1a5e7e268"),"Pname" : "ProductT", "Pnumber" :
56,"Plocation" : ["Delhi","Mumbai"], "Dnum" : 15}
{ "_id" : ObjectId("5cc7fe36e37496f1a5e7e268"),"Pname" : "ProductU", "Pnumber" :
5,"Plocation" : "Delhi", "Dnum" : 6}
{ "_id" : ObjectId("5cc7fe36e37496f1a5e7e268"),"Pname" : "ProductL", "Pnumber" :
4,"Plocation" : "Mumbai", "Dnum" : 7}

6) Write a MongoDB query creating a One to Many Relation between a document of


“Project” Collection and “Department” Collection.
DBMS Lab Workbook (CSL214) | 77
2022-23

7) Write a MongoDB query to retrieve the project details  project name, department
number, department name and department manager of projects with department manager
(for department in which the project is being run) as “ABC”.

Background Study

1) pretty() is used to display the query obtained in a neat manner with all the fields clearly
depicted one below the other.

2) Data for a particular field can also be stored as an array with multiple values for the field.

3) $all is used to match the array items for the particular field.
o db.project.find({Plocation:{$all:["Delhi","Mumbai"]}}).pretty()

4) $elemMatch: This operator matches documents that contain an array field with at least
one element that matches all the specified query criteria.
o Syntax: { <field>: { $elemMatch: { <query1>, <query2>, ... } } }

5) Fields can be embedded in the field too and while using find in such a case, always refer
the field embedded in another field by using a dot notation and in quotes.

6) AND/OR Operations
DBMS Lab Workbook (CSL214) | 78
2022-23

Operation Syntax Example

>db.project.find
>db.collection_name.find({$and: ({$and:[{Dnum:5},
AND
[{key1: value1}, {key2:value2}]}) {Pname:"ProductZ“}]}).pretty
();

>db.project.find
>db.collection_name.find({$or: ({$or:[{Dnum:5},
OR
[{key1: value1}, {key2:value2}]}) {Pname:"ProductZ“}]}).pretty
();

7) Documents can either be embedded in one to one relation or one to many relation
o In one to one, the new field contains only a single embedded document.
o In one to many, the new field contains an array of multiple embedded documents.

Output: Screenshots

1. Insert multiple documents (2-3) together in the Project collection with atleast 1
project location as a composite attribute
DBMS Lab Workbook (CSL214) | 79
2022-23

2) Write the “Select * from Project” equivalent query in MongoDB.

3.Write a MongoDB query to update the project location of all projects to “Pune” and
department number to “20” with project name “ProjectX”.
DBMS Lab Workbook (CSL214) | 80
2022-23

4.Write a MongoDB query to delete all the documents of collection “Project” with
department number “4”.

5.Write a MongoDB query to retrieve the project details of all projects with project
location as “Delhi” and “Mumbai” both assuming the following documents exist.

{ "_id" : ObjectId("5cc7fe36e37496f1a5e7e268"),"Pname" : "ProductK", "Pnumber" :


45,"Plocation" : ["Delhi","Mumbai","Pune"], "Dnum" : 3}
{ "_id" : ObjectId("5cc7fe36e37496f1a5e7e268"),"Pname" : "ProductT", "Pnumber" :
56,"Plocation" : ["Delhi","Mumbai"], "Dnum" : 15}
{ "_id" : ObjectId("5cc7fe36e37496f1a5e7e268"),"Pname" : "ProductU", "Pnumber" :
5,"Plocation" : "Delhi", "Dnum" : 6}
{ "_id" : ObjectId("5cc7fe36e37496f1a5e7e268"),"Pname" : "ProductL", "Pnumber" :
4,"Plocation" : "Mumbai", "Dnum" : 7}

6.Write a MongoDB query creating a One to Many Relation between a document of


“Project” Collection and “Department” Collection.
DBMS Lab Workbook (CSL214) | 81
2022-23

7. Write a MongoDB query to retrieve the project details  project name, department
number, department name and department manager of projects with department manager
(for department in which the project is being run) as “ABC”.
DBMS Lab Workbook (CSL214) | 82
2022-23

Preparatory Questions

Q1) The order of documents returned by a query is not defined unless you specify a ______
1) sortfind()
2) sortelse()
3) sort()
4) none of the mentioned

Q2) In aggregation pipeline, the _______ pipeline stage provides access to MongoDB queries.
1) $catch
2) $match
3) $batch
4) All of the mentioned

Q3) Point out the wrong statement.


1) sort() modifier sorts the results by age in ascending order
2) Queries in MongoDB return all fields in all matching documents by default
3) To scale the amount of data that MongoDB sends to applications, include a projection
in the queries.
4) None of the mentioned
DBMS Lab Workbook (CSL214) | 83
2022-23

Q4) Which of the following query selects documents in the records collection that match the
condition { “user_id”: { $lt: 42 } }?
1) db.records.findOne( { “user_id”: { $lt: 42 } }, { “history”: 0 } )
2) db.records.find( { “user_id”: { $lt: 42 } }, { “history”: 0 } )
3) db.records.findOne( { “user_id”: { $lt: 42 } }, { “history”: 1 } )
4) db.records.select( { “user_id”: { $lt: 42 } }, { “history”: 0 } )

Q5) Which of the following is not a projection operator?


1) $slice
2) $elemMatch
3) $
4) None of the mentioned

Value Added Experiment


Student Name and Roll Number: Harsh Gandhi 23MCA008

Semester /Section: 1st


DBMS Lab Workbook (CSL214) | 84
2022-23

Link to Code:

Date:
Faculty Signature:

Marks:

Objective

Design an ER/ EER Diagram, relational schema.

Program Outcome

 The students will design and implement DBMS concepts on a real-world project.

What are the ER diagrams?

ER diagram is a visual representation of data based on the ER


model, and it describes how entities are related to each other in the
database.

What are EER diagrams?

EER diagram is a visual representation of data, based on the EER


model that is an extension of the original entity-
relationship (ER) model.
DBMS Lab Workbook (CSL214) | 85
2022-23

When you read this article you will find these words.”Entity,

Attribute, Relationship, Cardinality, and Participation”.🤔

Okay, Let’s see what are these.

Entity

An entity is any singular, identifiable and separate object. It refers to


individuals, organizations, systems, bits of data or even distinct system
components that are considered significant in and of themselves.
For example, People, Property, Organizations, Agreements and, etc.
In the ER diagram, the entity is represented by a rectangle.

Weak Entity

A weak entity is an entity that depends on the existence of another


entity. In more technical terms it can be defined as an entity that
cannot be identified by its own attributes.

Attributes

Attributes are the properties that define the entity type.


For example, Roll_No, Name, DOB, Age, Address, Mobile_No are
the attributes that define entity type Student. In the ER diagram,
the attribute is represented by an oval.
DBMS Lab Workbook (CSL214) | 86
2022-23

Multi-valued Attribute

If an attribute can have more than one value it is called a multi-valued


attribute.

Derived Attribute

An attribute-based on another attribute.

Relationships

A relationship is an association that describes the interaction


between entities.

Recursive Relationship

If the same entity participates more than once in a relationship it is


known as a recursive relationship.

The following are the types of entities, attributes, and


relationships.
DBMS Lab Workbook (CSL214) | 87
2022-23

Cardinality

Cardinality refers to the maximum number of times an instance in


one entity can relate to instances of another entity. There are three
types of cardinalities.

1. one to one (1 to 1)
2. one to many(1 to N)
3. many to many (M to N)
DBMS Lab Workbook (CSL214) | 88
2022-23

Participation

Participation constraint specifies the existence of an entity when it is


related to another entity in a relationship type. There are two types.
Partial and Total participation.

Total Participation − Each entity is involved in the relationship.


Total participation is represented by double lines.

Partial participation − Not all entities are involved in the


relationship. Partial participation is represented by single lines.

There are three steps in database development.

1. Requirements Analysis- Understand the data problem


through user interviews, forms, reports, observation and etc.
2. Component design stage- Create a data model that is a
graphical representation of what will be finally will be
implemented.
DBMS Lab Workbook (CSL214) | 89
2022-23

3. Implementation stage- Actual development of the


database which leads to database actually being used in the
real environment.

In the above stages after the first stage(Requirements analysis) you


have to follow the database design stages.

1. Conceptual design
2. Logical design
3. Physical design

In the Conceptual design, we identify all entities, we define


attributes and their properties and we define relationships between
entities.
DBMS Lab Workbook (CSL214) | 90
2022-23

In the Logical design, we transform the conceptual design into


relational, transform entities as tables, transform entity attributes into
table column, and normalization.

In the Physical design, we specify internal storage structure and


paths, assign one or more indexes and tune indexes.

At the conceptual design stage, we design the ER or EER diagrams.

Here are some rules for drawing ER and EER diagrams

 Write all entities in the singular form


 Write all relationships in a singular form.
 Write all attributes in the singular form.
 If you want to separate words use underscore mark.

Now, let’s see how to draw ER diagrams and EER diagrams.


DBMS Lab Workbook (CSL214) | 91
2022-23

Drawing ER and EER diagrams

Below points show how to go about creating an ER


diagram.

1. Identify all the entities in the system. An entity should


appear only once in a particular diagram. Create rectangles
for all entities and name them properly.
2. Identify relationships between entities. Connect them
using a line and add a diamond in the middle describing the
relationship.
3. Add attributes for entities. Give meaningful attribute names
so they can be understood easily.
4. Mark the cardinalities and participation between the
entities.

Here is an example of ER diagrams.


DBMS Lab Workbook (CSL214) | 92
2022-23

Now let’s see how to draw EER diagrams.

Here we just need to add a few things to above.

1. As in drawing ER diagrams first, we have to identify all entities.

After we found entities from the scenario you should check whether
those entities have sub-entities. If so you have to mark sub-entities in
your diagram.

Dividing entities into sub-entities we called as specialization. And


combining sub-entities to one entity is called a generalization.
DBMS Lab Workbook (CSL214) | 93
2022-23

2. Then you have to identify relationships between entities and


mark them.

3. Add attributes for entities. Give meaningful attribute names so


they can be understood easily.

4.Mark the cardinalities and participation

If it is an EER diagram you have to add a few to your diagram.


DBMS Lab Workbook (CSL214) | 94
2022-23

Here also we have to check whether sub-entities totally depend on the


main entity or not. And you should mark it.

If all members in the superclass(main entity) participate in either one


subclass it is known as total participation. It marks by double lines.

Total Participation

If at least one member in the superclass does not participate in


subclass it is known as partial participation. It is denoted by one
single line.
DBMS Lab Workbook (CSL214) | 95
2022-23

Partial Participation

If all the members in the superclass participate for only one subclass it
is known as disjoint and denoted by “d”. If all the members in the
superclass participate in more than one subclass it is known
as overlap and denoted by “o”.
DBMS Lab Workbook (CSL214) | 96
2022-23

Now it ends, after following all the above steps


you can come up with your ER and EER

diagrams.😍

Benefits of ER and EER diagrams.

 Easy to understand and does not require a person to undergo


extensive recently training to be able to work with it and
accurately.
 Readily translatable to relational tables which can be used to
quickly build databases
 Can directly be used by database developers as the blueprint
for implementing databases in specific software application
 It can be applied in other contexts such as describing the
different relationships and operations within an organization.

Now let’s move on. Our next topic is map ER and EER diagrams into
relational schemas.

Mapping ER and EER diagrams into relational


schemas

First I’ll tell you how to map the ER diagram into a relational schema.
DBMS Lab Workbook (CSL214) | 97
2022-23

Mapping ER diagrams into relational schemas

Follow the steps one by one to get it done.🤞

1. Mapping strong entities.


2. Mapping weak entities.
3. Map binary one-to-one relations.
4. Map binary one-to-many relations
5. Map binary many-to-many relations.
6. Map multivalued attributes.
7. Map N-ary relations

Let’s go deep with the examples.


DBMS Lab Workbook (CSL214) | 98
2022-23

1. Mapping strong entities.

2. Mapping weak entities.

Above it shows an ER diagram with its relationships. You can see there
are two strong entities with relationships and a weak entity with a weak
relationship.

When you going to make a relational schema first you have to identify
all entities with their attributes. You have to write attributes in
DBMS Lab Workbook (CSL214) | 99
2022-23

brackets as shown below. Definitely you have to underline the primary


keys. In the above DEPENDENT is a weak entity. To make it strong
go through the weak relationship and identify the entity which
connects with this. Then you have written that entity’s primary key
inside the weak entity bracket.

Then you have to map the primary key to where you took from as
shown below.

3. Map binary one to one relations.

Let’s assume that the relationship between CUSTOMER and CARD is


one to one.

There are three occasions where one to one relations take place
according to the participation constraints.
DBMS Lab Workbook (CSL214) | 100
2022-23

I. Both sides have partial participation.

When both sides have partial participation you can send any of the
entity’s primary key to others. At the same time, if there are attributes
in the relationship between those two entities, it is also sent to other
entity as shown above.

So, now let us see how we write the relational schema.


DBMS Lab Workbook (CSL214) | 101
2022-23

Here you can see I have written CUSTID and STARTDATE inside
the CARD table. Now you have to map CUSTID from where it comes.

That’s it.🤩

II. One side has partial participation.

You can see between the relationship and CARD entity it has total
participation.

When there is total participation definitely the primary of others comes


to this. And also if there are attributes in the relationship it also comes
to total participation side.

Then you have to map them as below.


DBMS Lab Workbook (CSL214) | 102
2022-23

III. Both sides have total participation

If both sides have total participation you need to make a new


relationship with a suitable name and merge entities and the
relationship.

Following it shows how we should write the relation.


DBMS Lab Workbook (CSL214) | 103
2022-23

Now let us see how to map one to many relations.

4. Map binary one-to-many relations

If it is one-to-many, always to the many side other entities' primary


keys and the attributes in the relationship go to the many side. No
matter about participation. And then you have to map the primary key.
DBMS Lab Workbook (CSL214) | 104
2022-23

5. Map binary many to many relations.

If it is many to many relations you should always make a new


relationship with the name of the relationship between the entities.

And there you should write both primary keys of the entities and
attributes in the relationship and map them to the initials as shown
below.
DBMS Lab Workbook (CSL214) | 105
2022-23

6. Map multivalued attributes.

If there are multivalued attributes you have to make a new relationship


with a suitable name and write the primary key of the entity which
belongs to the multivalued attribute and also the name of the
multivalued attribute as shown below.
DBMS Lab Workbook (CSL214) | 106
2022-23

7. Map N-ary relations.

First, let us consider unary relationships.

We categorized them into two.

I. one-to-one and one to many relations.


DBMS Lab Workbook (CSL214) | 107
2022-23

If it is unary and one to one or one to many relations you do not need
to make a new relationship you just want to add a new primary key to
the current entity as shown below and map it to the initial. For
example, in the above diagram, the employee is supervised by the
supervisor. Therefore we need to make a new primary key as SID and
map it to EMPID. Because of SID also an EMPID.

II. many-to-many relations.


DBMS Lab Workbook (CSL214) | 108
2022-23

If it is unary and many to many relations you need to make a new


relationship with a suitable name. Then you have to give it a proper
primary key and it should map to where it comes as shown below.
DBMS Lab Workbook (CSL214) | 109
2022-23

Now let us see how to map relations with more than two entities.
DBMS Lab Workbook (CSL214) | 110
2022-23

If there are more than three entities for a relationship


you have to make a new relation table and put all
primary keys of connected entities and all attributes in
the relationship. And in the end, you have to map them
as shown below.

👍 That’s how we map ER diagrams into relational


schemas.

Now let us see how to map EER diagrams.

Mapping EER diagrams into relational schemas.

Let us go through the following diagram.


DBMS Lab Workbook (CSL214) | 111
2022-23

There are four ways to draw relational schema for an EER. You have to
choose the most suitable one. In the end, I'll give you the guidelines on
how to choose the best and most suitable way.

First method
DBMS Lab Workbook (CSL214) | 112
2022-23

Here we write separate relations to all superclass entities and subclass


entities. And here we have to write the superclass entities' primary key
to all subclass entities and then map them as shown above. Note that
we write only the attributes belongs to each entity.

Second method

Here we do not write the superclass entity but in each subclass entity,
we write all attributes that are in superclass entity.

Third method
DBMS Lab Workbook (CSL214) | 113
2022-23

Here we write only the superclass entity and write all the attributes
which belong to subclass entities. Specialty in here is that to identify
that PERSON is an EMPLOYEE or STUDENT we add a column
as PERSONTYPE. After the table creates we can mark as
a STUDENT or EMPLOYEE.

Fourth method

You might also like