Final DBMS Manual
Final DBMS Manual
System
Lab Manual
Department of Computer Science and Engineering
The NorthCap University, Gurugram
ii
2019-20
Session 2019-20
Published by:
iii
2019-20
© Copyright Reserved
No part of this Practical Record Book may be reproduced, used, stored without prior permission of The NorthCap
University
Copying or facilitating copying of lab work comes under cheating and is considered as use of
unfair means. Students indulging in copying or facilitating copying shall be awarded zero marks
for that particular experiment. Frequent cases of copying may lead to disciplinary action.
Attendance in lab classes is mandatory.
Labs are open up to 7 PM upon request. Students are encouraged to make full use of labs beyond
normal lab hours.
iv
2019-20
PREFACE
Database Management System Lab Manual is designed to meet the course and program
requirements of NCU curriculum for B.Tech II year students of CSE branch. The concept of the
lab work is to give practical experience for basic lab skills to students. It provides the space and
scope for self-study so that students can come up with new and creative ideas.
The Lab manual is written on the basis of “teach yourself pattern” and expected that students
who come with proper preparation should be able to perform the experiments without any
difficulty. Brief introduction to each experiment with information about self-study material is
provided. The laboratory exercises will include familiarization with SQL and NoSQL commands
to define, manipulate, retrieve and manage data in a database. The course will enable stduents to
create a database and devise queries for extracting information from the database using
Relational Algebra and SQL. The students will be able to appreciate the importance of handling
unstructured data using NoSQL and apply the concepts of DBMS for developing a backend for a
non-trivial project.
At the start of each experiment a question bank for preparation and practice is suggested which
may be used to test the basic understanding of the students about the experiment. Students are
expected to come thoroughly prepared for the lab. General disciplines, safety guidelines and
report writing are also discussed.
The lab manual is a part of curriculum for the TheNorthCap University, Gurugram. Teacher’s
copy of the experimental results and answer for the questions are available as sample guidelines.
We hope that lab manual would be useful to students of CSE, IT, ECE and BSc branches and
author requests the readers to kindly forward their suggestions / constructive criticism for further
improvement of the work book.
Author expresses deep gratitude to Members, Governing Body-NCU for encouragement and
motivation.
v
2019-20
Authors
The NorthCap University
Gurugram, India
CONTENTS
Syllabus
1 Introduction
2 Lab Requirements
3 General Instructions
4 List of Experiments
5 Rubrics
2019-20
SYLLABUS
1. Department: Department of Computer Science and Engineering
6. Type of Course
(Check one): Programme Core Programme Elective Open Elective
8. Frequency of offering (check one): Odd Even Either semester Every semester
9. Brief Syllabus:
Databases form the core of all major applications – finance, social, administrative, education etc. Organizations
work on large volumes of data every day, introducing the need to have database management systems to easily
identify, extract, store and transform details in the database. This course will explore concepts and principles of
DBMS, database design, data modeling, database implementation, and database management through various
assignments and projects. By the end of this course, the student will be able to work as a database engineer by
designing, developing and maintaining the database for any project application.
Total lecture, Tutorial and Practical Hours for this course (Take 15 teaching weeks per semester): 75
Practice
Lectures: 45hours
Tutorials:10 hours Lab Work: 20 hours
10. Course Outcomes (COs)
Possible usefulness of this course after its completion i.e. how this course will be practically useful to him once it
is completed.
Identifying contrast between traditional and modern Database Systems, thereby recognizing their
CO 1
applications.
vii
2019-20
Developing conceptual database design for any real time project by defining the relationship,
CO 2
constraints etc. on entities.
CO 3 Applying appropriate design techniques to design a good database that meets the user requirement.
Creating a database and devising queries for extracting information from the database using
CO 4
Relational Algebra and SQL.
CO 5 Applying the concepts of DBMS for developing a backend for a non-trivial project using NoSQL.
CO 6 Ability to improvise data fetching time by applying indexing concepts.
CO 7 Understanding the concepts of end-to-end transaction processing in a database.
Content Summary:
Overview of Database Management Systems, Advantages of DBMS over File Processing Systems, DBMS Vs.
RDBMS, DBA roles and responsibilities, Data Independence, Architecture of Database(3-Schema Architecture,
Complete architecture), Database Query Languages (DDL, DML, DCL), Relational Model Concepts: Primary Key,
Unique key, Foreign key, Super Key, Alternate key, Candidate key, Constraints used in Relational Data Model
including integrity constraints.
Content Summary:
Data Modeling Using the Entity Relationship (ER) Model, The Enhanced Entity-Relationship (EER) Model: Entity
Set, attributes and their types, Relationship Constraints (including Participation constraints and cardinality ratio), ER
Diagrams, constraints and design issues, Reduction of ER and EER diagram to relational schemas.
Content Summary:
Relational database design, Functional dependencies: Fully functional dependency, partial FD, trivial, non-trivial FD,
inference rules, canonical cover, lossless join, dependency preservation, multi value dependency, Normal Forms:
1NF, 2NF, 3NF, BCNF, 4NF, 5NF, Normalization and denormalization process
2019-20
Content Summary:
Introduction to MongoDB, Datatypes, Document Data Model-Creating, Inserting, Updating and Deleting
Documents, MongoDB Query Language, Sorting, Join Operations.
Unit Number: 7 Title: Transaction Management & Concurrency Control No. of hours: 7
Content Summary:
Introduction to transaction processing, ACID Properties, Concurrency control mechanisms: serializability, two phase
locking protocol, basic concept of deadlock, deadlock handling, timestamp-based protocols, precedence graph to
ensure serializability, different protocols in concurrency control. Database back-up and Recovery.
12. Brief Description of Self-learning components by students (through books/resource material etc.):
Textbooks:
1. Elmasri R. and Navathe S.B., Fundamentals of Database Management Systems. 6th ed. Pearson, 2010.
2. Silberschatz A., Korth H.F. and Sudarshan S., Database System Concepts. 6th ed. Mc.Graw Hill, 2010.
3. Chodorow K., MongoDB: The Definitive Guide. 2nd ed. O'Reilly Media, 2013.
Reference Books:
1. Ramakrishnan R. and Gehrke J., Database Management Systems. 3rd ed. McGraw-Hill Education, 2003.
2. Suehring S., My SQL Bible. Wiley Publishing, 2002.
Reference Websites: (nptel, swayam, coursera, edx, udemy, lms, official documentation weblink)
https://nptel.ac.in/courses/106105175/2
https://docs.mongodb.com/
ix
2019-20
1. INTRODUCTION
To familiarize the students with the basic concepts, programming skill development
and the take home laboratory assignments mainly implementation-oriented which
have to be coded in high level language. The lab sessions will be based on exploring
the concepts discussed in class.
Developing conceptual database design for any real time project by defining the
relationship, constraints etc. on entities.
Compare and contrast application of SQL and NoSQL for managing a database.
2019-20
2. LAB REQUIREMENTS
4 Required Bandwidth NA
xi
2019-20
3. GENERAL INSTRUCTIONS
Students must turn up in time and contact concerned faculty for the experiment they
are supposed to perform.
Students will not be allowed to enter late in the lab.
Students will not leave the class till the period is over.
Students should come prepared for their experiment.
Experimental results should be entered in the lab report format and certified/signed
by concerned faculty/ lab Instructor.
Students must get the connection of the hardware setup verified before switching on
the power supply.
Students should maintain silence while performing the experiments. If any necessity
arises for discussion amongst them, they should discuss with a very low pitch
without disturbing the adjacent groups.
Violating the above code of conduct may attract disciplinary action.
Damaging lab equipment or removing any component from the lab may invite
penalties and strict disciplinary action.
3.2 Attendance
xii
2019-20
Students should come to the lab thoroughly prepared on the experiments they are
assigned to perform on that day. Brief introduction to each experiment with
information about self study reference is provided on LMS.
Students must bring the lab report during each practical class with written records
of the last experiments performed complete in all respect.
Each student is required to write a complete report of the experiment he has
performed and bring to lab class for evaluation in the next working lab. Sufficient
space in work book is provided for independent writing of theory, observation,
calculation and conclusion.
Students should follow the Zero tolerance policy for copying / plagiarism. Zero
marks will be awarded if found copied. If caught further, it will lead to disciplinary
action.
Refer Annexure 1 for Lab Report Format
xiii
2019-20
4. LIST OF EXPERIMENTS
S.No Division of
List of Experiments
. Experiments
Design an ER diagram for the COMPANY database for the
1
following set of requirements.
Conceptual
Design a Relational Database Design for the COMPANY
Database Design
2 database from the ER/EER diagram for the following set of
requirements.
SQL To apply SQL integrity constraints as per the DDL statements
3
given below for COMPANY database.
To familiarize with SELECT-FROM-WHERE SQL simple
4
queries on the COMPANY database.
To familiarize with different JOIN operations in SQL on the
5
COMPANY database.
6 To understand Aggregate functions and Group by Clause using
xiv
2019-20
5. RUBRICS
Marks Distribution
2019-20
Annexure 1
2019-20
Roll No.:
Semester:
Group:
Session 2019-20
INDEX
Page Date of Date of CO
S.No Experiment Marks Signature
No. Experiment Submission Covered
xvii
2019-20
Experiment No: 1
Student Name and Roll Number:
Semester /Section:
Link to Code:
xviii
2019-20
Date:
Faculty Signature:
Remarks:
Objective
Design an ER diagram for the COMPANY database for the following set of requirements.
Program Outcome
The students will be able to draw conceptual database design using ERD Plus.
Problem Statement
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 miniworld—the part of the company that will be represented in
the database.
2019-20
Design the ER model by identifying the following from the above requirements:
Background Study
1) Entity:
o Real-world object distinguishable from other objects.
o An entity is described using a set of attributes.
3) Attributes
o Attributes are properties used to describe an entity.
o Example: EMPLOYEE entity may have a Name, SSN, Address, Sex, BirthDate.
xx
2019-20
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.
Partial participation − Not all entities are involved in the relationship.
7) Specialization - is the process of defining a set of subclasses of a superclass
8) Generalization
o the reverse of the specialization process .
o Several classes with common features are generalized into a superclass (original
classes become its subclasses)
xxi
2019-20
ER/EER Diagram
xxii
2019-20
Output: Screenshots
xxiii
2019-20
Preparatory Questions
Q1) Given the basic ER and relational models, which of the following is INCORRECT?
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) In which of the following cases an entity instance must be a member of only one subtype?
2019-20
Q5) 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)
1) Double ellipse
2) Dashed ellipse
3) Squared ellipse
4) Ellipse with attribute name underlined
Q9) For a weak entity set to be meaningful, it must be associated with another entity set in combi
nation with some of their attribute values, is called as:
1) Neighbour Set
xxv
2019-20
Q10) Which of the following statements is FALSE about weak entity set?
1) Weak entities can be deleted automatically when their strong entity is deleted.
2) Weak entity set avoids the data duplication and consequent possible inconsistencies
caused by duplicating the key of the strong entity.
3) A weak entity set has no primary keys unless attributes of the strong entity set on which it
depends are included
4) Tuples in a weak entity set are not partitioned according to their relationship with tuples
in a strong entity set
Experiment No: 2
Student Name and Roll Number:
Semester /Section:
Link to Code:
Date:
Faculty Signature:
Remarks:
Objective
Design a Relational Database Design for the COMPANY database from the ER/EER diagram
for the following set of requirements.
Program Outcome
The students will be able to map the conceptual database design to logical (relational)
database design.
xxvi
2019-20
Problem Statement
The COMPANY database keeps track of a company’s employees, departments, and projects.
Map the ER/EER diagram of the COMPANY database created in the previous experiment to
Relational Database Design. Follow the below mentioned steps to successfully map ER/EER to
relational tables:
Background Study
2019-20
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).
2019-20
o Include as foreign key attributes in S the primary keys of the relations that represent the
participating entity types.
2019-20
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
xxx
2019-20
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?
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?
xxxi
2019-20
Q6) Which of the following has each related entity set has its own schema and there is an
additional schema for the relationship 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
Q7) For each attribute of a relation, there is a set of permitted values, called the ________ of that
attribute.
1) Domain
2) Relation
3) Set
4) Schema
Q8) Let M and N be two entities in an E-R diagram with simple single value attributes. R1 and
R2 are two relationship between M and N, where as R1 is one-to-many and R2 is many-to-many.
The minimum number of tables required to represent M, N, R1 and R2 in the relational model
are _______.
1) 4
2) 6
3) 7
4) 3
Q9) Database __________ which is the logical design of the database, and the database _______
which is a snapshot of the data in the database at a given instant in time.
1) Instance, Schema
2) Relation, Schema
3) Relation, Domain
4) Schema, Instance
xxxii
2019-20
Q10) Which option only works for a specialization whose subclasses are total (every entity in
the superclass must belong to (at least) one of the subclasses) while the mapping of
specialisation / generalisation form EER diagram to relational table :
2019-20
Experiment No: 3
Student Name and Roll Number:
Semester /Section:
Link to Code:
Date:
Faculty Signature:
Remarks:
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.
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
xxxiv
2019-20
Problem Statement
xxxv
2019-20
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.
xxxvi
2019-20
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)
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.
2019-20
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.
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
xxxvii
i
2019-20
Preparatory Questions
xxxix
2019-20
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,
d INTEGER,
e INTEGER,
PRIMARY KEY (d),
FOREIGN KEY (a) references R)
2019-20
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
6 4
The set of all tuples that must be additionally deleted to preserve referential integrity when the
tuple (2,4) is deleted is:
2019-20
Q7) Domain constraints, functional dependency and referential integrity are special forms of ___
1) Foreign key
2) Primary key
3) Assertion
4) Referential constraint
SELECT DISTINCT w, x
FROM r, s
2019-20
Q10) In SQL, relations can contain null values, and comparisons with null values are treated as
unknown. Suppose all comparisons with a null value are treated as false. Which of the following
pairs is not equivalent?
2019-20
Experiment No: 4
Student Name and Roll Number:
Semester /Section:
Link to Code:
Date:
Faculty Signature:
Remarks:
Objective
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’.
SELECT BDATE, ADDRESS FROM EMPLOYEE WHERE FNAME = ‘John’ AND MINIT = ‘B’ AND
LNAME = ‘Smith’;
2) Retrieve the name and address of all employees who work for the ‘Research’ department.
xliv
2019-20
SELECT fname, lname, address FROM employee, department WHERE dname='Research' AND
dnumber=dno;
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
SELECT pnumber, dnum, lname, address, bdate FROM project, department, employee WHERE
dnum=dnumber AND mgr_ssn=ssn AND plocation='Stafford';
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.
SELECT * FROM EMPLOYEE WHERE DNO = 5;
6) Retrieve all distinct salary values.
SELECT DISTINCT SALARY FROM EMPLOYEE;
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.
(SELECT DISTINCT PNUMBER FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE DNUM =
DNUMBER AND MGRSSN = SSN AND LNAME = ‘Smith’) UNION (SELECT DISTINCT PNUMBER
FROM PROJECT, WORKS_ON, EMPLOYEE WHERE PNUMBER = PNO AND ESSN = SSN AND LNAME
= ‘Smith’);
8) Retrieve all employees whose address is in Houston, Texas.
SELECT FNAME, LNAME FROM EMPLOYEE WHERE ADDRESS LIKE ‘%Houston,TX%’;
9) Find all employees who were born during the 1950s
SELECT FNAME, LNAME FROM EMPLOYEE WHERE BDATE LIKE ‘_ _ _ _ _ _ _ 70’;
10) Show the resulting salaries if every employee working on the ‘ProductX’ project is given
a 10 percent raise.
SELECT FNAME, LNAME, 1.1*SALARY FROM EMPLOYEE, WORKS_ON, PROJECT WHERE SSN =
ESSN AND PNO = PNUMBER AND PNAME = ‘ProductX’;
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.
SELECT DNAME, LNAME, FNAME, PNAME FROM DEPARTMENT, EMPLOYEE,WORKS_ON,
PROJECT WHERE DNUMBER = DNO AND SSN = ESSN AND PNO = PNUMBER ORDER BY DNAME
DESC, LNAME ASC, FNAME ASC;
xlv
2019-20
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
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 :
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.
xlvi
2019-20
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.
2019-20
Output: Screenshots
xlviii
2019-20
Preparatory Questions
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
2019-20
1) Delete
2) Truncate
3) Remove
4) Drop
Q7) Which of the following commands makes the updates performed by the transaction
permanent in the database?
1) ROLLBACK
2) COMMIT
3) TRUNCATE
4) DELETE
2019-20
Experiment No: 5
Student Name and Roll Number:
Semester /Section:
Link to Code:
Date:
Faculty Signature:
Remarks:
Objective
Program Outcome
Problem Statement
Consider the Sample database given below and answer the queries as stated :
Pack_grades
2019-20
Customers
Packages
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 last name, first name and monthly discount for all customers whose monthly
discount is lower than the monthly discount of employee number 103 (Customers table).
lii
2019-20
11) 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.
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.
2019-20
Output: Screenshots
liv
2019-20
Preparatory Questions
SELECT Count(*)
FROM ( ( SELECT Borrower, Bank_Manager
FROM Loan_Records) AS S
lv
2019-20
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
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
2019-20
FROM CUSTOMER_T,ORDER_T
FROM CUSTOMER_T,ORDER_T ?
1) Equi-join
2) Natural join
3) Outer join
4) Cartesian join
Q9) Suppose ORACLE relation R(A, B) currently has tuples {(1, 2), (1, 3), (3, 4)} and relation
S(B, C) currently has {(2, 5), (4, 6), (7, 8)}. Consider the following two SQL queries SQ1 and
SQ2 :
The numbers of tuples in the result of the SQL query SQ1 and the SQL query SQ2 are given by:
1) 2 and 6 respectively
2) 6 and 2 respectively
3) 2 and 4 respectively
4) 4 and 2 respectively
lvii
2019-20
Q10) ) Which of the following is true ? I. Implementation of self-join is possible in SQL with
table alias. II. Outer-join operation is basic operation in relational algebra. III. Natural join and
outer join operations are equivalent.
1) I and II are correct.
2) II and III are correct.
3) Only III is correct.
4) Only I is correct.
Experiment No: 6
lviii
2019-20
Objective
To understand Aggregate functions and Group by Clause using SQL queries on the COMPANY
database.
Program Outcome
The students will understand the need of applying an aggregate function in order 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.
lix
2019-20
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
3) Built-in aggregate functions: COUNT, SUM, MAX, MIN, and AVG (NULL values
discarded when aggregate functions are applied to a particular column)
7) If NULLs exist in grouping attribute then separate group created for all tuples with a
NULL value in grouping attribute
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
lx
2019-20
Output: Screenshots
lxi
2019-20
Preparatory Questions
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?
2019-20
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
Q5) Observe the given SQL query and choose the correct option.
2019-20
Q7) Which keyword is used to rename the resulting attribute after the application of the
aggregation function?
1) rename
2) as
3) replace
4) to
R (A, B, C) = {<1, 2, 3>, <1, 2, 0>, <1, 3, 1>, <6, 2, 3>, <1, 4, 2>, <3, 1, 4> } S (B, C, D) = {<2,
3, 7>, <1, 4, 5>, <1, 2, 3>, <2, 3, 4>, <3, 1, 4>}.
SQ1 : SELECT R⋅B, AVG (S⋅B) FROM R, S WHERE R⋅A = S⋅C AND S⋅D < 7 GROUP BY
R⋅B;
SQ2 : SELECT DISTINCT S⋅B, MIN (S⋅C) FROM S GROUP BY S⋅B HAVING COUNT
(DISTINCT S⋅D) > 1;
If M is the number of tuples returned by SQ1 and N is the number of tuples returned by SQ2 then
lxiv
2019-20
1) M = 4, N = 2
2) M = 5, N = 3
3) M = 2, N = 2
4) M = 3, N = 3
Q10) State true or false: Any attribute which is present in the having clause without being
aggregated must not be present in the group by clause.
1) True
2) False
Experiment No: 7
Student Name and Roll Number:
Semester /Section:
Link to Code:
Date:
Faculty Signature:
Remarks:
Objective
Program Outcome
The students will understand how to devise independent and correlated nested queries.
Problem Statement
lxv
2019-20
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.
2) 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.
3) Return the names of employees whose salary is greater than the salary of all the
employees in department 5
4) Retrieve the name of each employee who has a dependent with the same first name and is
the same sex as the employee
5) Retrieve the names of employees who have no dependents
6) List the names of managers who have at least one dependent using EXISTS and NOT
EXISTS functions
7) Retrieve the name of each employee who works on all the projects controlled by
department number 5 using EXISTS and NOT EXISTS functions
8) Retrieve the names of all employees who have two or more dependents
9) Retrieves the names of all employees who work on only one project
Background Study
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)
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.
lxvi
2019-20
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
lxvii
2019-20
Preparatory Questions
2019-20
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
1 SC 8204
3 AC 8202
What pids are returned by the following SQL query for the above instance of the tables?
lxix
2019-20
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
2019-20
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?
Q1 : Select e.empId
From employee e
Where not exists
(Select * From employee s where s.department = “5” and
s.salary >=e.salary)
Q2 : 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
lxxi
2019-20
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.
Q6) The ______ clause allows us to select only those rows in the result relation of the ____
clause that satisfy a specified predicate.
1) Where, from
2) From, select
3) Select, from
4) From, where
Q7) The relation book (title, price) contains the titles and prices of different books. Assuming
that no two books have the same price, what does the following SQL query list?
select title
lxxii
2019-20
from book as B
where (select count(*)
from book as T
where T.price > B.price) < 5
1) Titles of the four most expensive books
2) Title of the fifth most inexpensive book
3) Titles of the five most expensive books
4) Titles of the five most expensive books
ID salary DeptName
1 10000 EC
2 40000 EC
3 30000 CS
4 40000 ME
5 50000 ME
6 60000 ME
7 70000 CS
How many rows are there in the result of following query?
SELECT E.ID
FROM Employee E
WHERE EXISTS (SELECT E2.salary
FROM Employee E2
WHERE E2.DeptName = 'CS'
AND E.salary > E2.salary)
lxxiii
2019-20
1) 0
2) 4
3) 5
4) 6
Q9) The ________ connective tests for set membership, where the set is a collection of values
produced by a select clause. The _________ connective tests for the absence of set membership.
1) Or, in
2) Not in, in
3) In, not in
4) In, or
Which of the following options will be needed at the end of the SQL query
FROM Cinema P1
Such that it always finds the addresses of theatres with maximum capacity?
1) WHERE P1. Capacity> = All (select P2. Capacity from Cinema P2)
2) WHERE P1. Capacity> = Any (select P2. Capacity from Cinema P2)
3) WHERE P1. Capacity > All (select max(P2. Capacity) from Cinema P2)
4) WHERE P1. Capacity > Any (select max (P2. Capacity) from Cinema P2)
lxxiv
2019-20
Experiment No: 8
Student Name and Roll Number:
Semester /Section:
Link to Code:
Date:
Faculty Signature:
Remarks:
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
Background Study
lxxv
2019-20
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.
lxxvi
2019-20
RDBMS MongoDB
Output: Screenshots
lxxvii
2019-20
Preparatory Questions
1) show db
2) show dbs
3) show data
4) display dbs
Q2) Which of the following operation is used to switch to new database mydb ?
lxxvii
i
2019-20
1) use dbs
2) use db
3) use mydb
4) use mydbs
1) show collection
2) show collections
3) show collect
4) None of the mentioned
1) tables
2) collections
3) rows
4) all of the mentioned
1) JSON
2) XML
3) JScript
4) All of the mentioned
lxxix
2019-20
Q7) MongoDB documents are composed of field-and-value pairs and have the following
structure:
1) <field1:; value1>
2) <field1: value1;>
3) <field1: value1>
4) none of the mentioned
Q8) The ______ field is always the first field in the document.
1) _id
2) id
3) Ob_id
4) None of the mentioned
1) 2 MB
2) 16 MB
3) 12 MB
4) There is no maximum size. It depends on RAM
Experiment No: 9
lxxx
2019-20
Objective
Program Outcome
Problem Statement
4) Retrieve the details of all projects that are being run in department number 50.
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”.
lxxxi
2019-20
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.
2019-20
Output: Screenshots
lxxxiii
2019-20
Preparatory Questions
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.
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 ?
lxxxiv
2019-20
1) sort()
2) order()
3) orderby()
4) all of the mentioned
Q6) A query may include a ___________ that specifies the fields from the matching documents
to return.
1) selection
2) projection
3) union
4) none of the mentioned
Q7) In MongoDB, _________ operations modify the data of a single collection.
1) CRUD
2) GRID
3) READ
4) All of the mentioned
Q8) Which of the following operation adds a new document to the users collection ?
1) add
2) insert
3) truncate
4) drop
Q9) Which of the following is a valid MongoDB JSON document:
1) {}
2) { "user_id"=1,
"user_name"="Joe Sanders",
"occupation"=["engineer","writer"]
}
3) { "user_id":1;
"user_name":"Joe Sanders";
"occupation":["engineer","writer"]
}
4) { "user_id":1,
"user_name":"Joe Sanders",
lxxxv
2019-20
Q10) Which of the following commands will return all the posts with number of likes greater
than 100 and less than 200, both inclusive?
Experiment No: 10
Student Name and Roll Number:
Semester /Section:
Link to Code:
Date:
Faculty Signature:
Remarks:
Objective
Program Outcome
The students will be able to perform advanced CRUD operations in MongoDB.
Problem Statement
Project
Possible Fields:
lxxxvi
2019-20
1) Insert multiple documents (2-3) together in the Project collection with atleast 1 project
location as a composite attribute
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.
2019-20
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>, ... } } }
lxxxvi
ii
2019-20
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
>db.project.find
>db.collection_name.find({$and: ({$and:[{Dnum:5},
AND
Operation [{key1: value1}, {key2:value2}]})
Syntax {Pname:"ProductZ“}]}).pretty
Example
();
>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
lxxxix
2019-20
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
xc
2019-20
Q2) In aggregation pipeline, the _______ pipeline stage provides access to MongoDB queries.
1) $catch
2) $match
3) $batch
4) All of the mentioned
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 } )
Q7) When inserts, updates and deletes have a _________ write concern, write operations return
quickly.
xci
2019-20
1) strong
2) weak
3) average
4) very strong
Q8) Which of the following MongoDB query is equivalent to the following SQL query:
UPDATE users SET status = "C" WHERE age > 25
1)
db.users.update(
{ age: { $gt: 25 } },
{ status: "C" })
2)
db.users.update(
{ age: { $gt: 25 } },
{ $set: { status: "C" } })
3)
db.users.update(
{ age: { $gt: 25 } },
{ $set: { status: "C" } },
{ multi: true })
4)
db.users.update(
{ age: { $gt: 25 } },
{ status: "C" },
{ multi: true })
Q9) Consider that you have a collection called population which has fields state and city. Which
of the following query will calculate the population grouped by state and city?
xcii
2019-20
Q10) Which of the following command is used to get all the indexes on a collection?
1) db.collection.getIndexes()
2) db.collection.showIndexes()
3) db.collection.findIndexes()
4) db.showIndexes()