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

Final DBMS Manual

fj ftf fft ff tf esrd tessrre ss sws es r
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
274 views

Final DBMS Manual

fj ftf fft ff tf esrd tessrre ss sws es r
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 92

Database Management

System
Lab Manual
Department of Computer Science and Engineering
The NorthCap University, Gurugram
ii

Database Management System Lab


Manual (CSL 214)

2019-20

Database Management System Lab Manual


CSL 214

Dr. Priyanka Vashisht

Department of Computer Science and Engineering

The NorthCap University, Gurugram- 122017, India

Session 2019-20

Published by:
iii

Database Management System Lab


Manual (CSL 214)

2019-20

School of Engineering and Technology

Department of Computer Science & Engineering

The NorthCap University Gurugram

• Laboratory Manual is for Internal Circulation only

© 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

Database Management System Lab


Manual (CSL 214)

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

Database Management System Lab


Manual (CSL 214)

2019-20

Authors
The NorthCap University
Gurugram, India

CONTENTS

S.No. Details Page No.

Syllabus

1 Introduction

2 Lab Requirements

3 General Instructions

4 List of Experiments

5 Rubrics

6 Annexure 1 (Format of Lab Report)

7 Annexure 2 (Format of Lab Certificate)


vi

Database Management System Lab


Manual (CSL 214)

2019-20

SYLLABUS
1. Department: Department of Computer Science and Engineering

2. Course Name: Database Management 3. Course Code 4. L-T-P 5. Credits


Systems CSL214 3-0-2 4

6. Type of Course
(Check one): Programme Core  Programme Elective Open Elective

7. Pre-requisite(s), if any: None

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

Database Management System Lab


Manual (CSL 214)

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.

11. UNIT WISE DETAILS No. of Units: 7

Unit Number: 1 Title: Introduction to Database Systems No. of hours: 4

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.

Unit Number: 2 Title: Conceptual Database Design No. of hours: 8

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.

Unit Number: 3 Title: Relational Database Design No. of hours: 8

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

Unit Number: 4 Title: Query Languages No. of hours: 8


Content Summary:
Relational Algebra: relational operators (projection, selection , union, intersection, set difference, division, rename,
Cartesian product, generalized relational algebra operators, cross product, join operators : inner vs. outer join, theta
join, outer join, natural join, equijoin, self-join, complete set of relational algebra operations.
SQL- Queries, Constraints, Form of SQL query, UNION, INTERSECT and EXCEPT, Nested queries, Aggregate
viii

Database Management System Lab


Manual (CSL 214)

2019-20

Operators, Null values, Complex Integrity constraints in SQL and triggers.

Unit Number: 5 Title: Introduction to NoSQL (MongoDB) No. of hours: 4

Content Summary:
Introduction to MongoDB, Datatypes, Document Data Model-Creating, Inserting, Updating and Deleting
Documents, MongoDB Query Language, Sorting, Join Operations.

Unit Number: 6 Title: File Organization& Indexing No. of hours: 6


Content Summary:
Disk Storage, Basic File Structures and Hashing: Unordered, ordered and hashed files of records, Single and
multilevel indexes: primary index, secondary index, clustered, multilevel and dynamic multilevel indexes (B-Tree
and B+ Tree).

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.):

Aggregation and Pagination in MongoDB

13. Books Recommended:

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

Database Management System Lab


Manual (CSL 214)

2019-20

1. INTRODUCTION

That ‘learning is a continuous process’ cannot be over emphasized. The theoretical


knowledge gained during lecture sessions need to be strengthened through practical
experimentation. Thus, practical makes an integral part of a learning process.

The purpose of conducting experiments can be stated as follows:

 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.

 Hands on experience on the experimental setup and software.


x

Database Management System Lab


Manual (CSL 214)

2019-20

2. LAB REQUIREMENTS

S.No. Requirements Details


1 Software Requirements MySQL, MongoDB
2 Operating System Any
3 Hardware Requirements Windows and Linux: Intel 64/32 or AMD Athlon
64/32, or AMD Opteron processor 2 GB RAM
80 GB hard disk space

4 Required Bandwidth NA
xi

Database Management System Lab


Manual (CSL 214)

2019-20

3. GENERAL INSTRUCTIONS

3.1 General discipline in the lab

 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

Database Management System Lab


Manual (CSL 214)

2019-20

 Attendance in the lab class is compulsory.


 Students should not attend a different lab group/section other than the one assigned
at the beginning of the session.
 On account of illness or some family problems, if a student misses his/her lab
classes, he/she may be assigned a different group to make up the losses in
consultation with the concerned faculty / lab instructor. Or he/she may work in the
lab during spare/extra hours to complete the experiment. No attendance will be
granted for such case.

3.3 Preparation and Performance

 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

Database Management System Lab


Manual (CSL 214)

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

Database Management System Lab


Manual (CSL 214)

2019-20

SQL queries on the COMPANY database.


To familiarize with nested SQL queries on the COMPANY
7
database.
Identifying contrast between Relational Databases and NoSQL,
8
thereby recognizing their applications.
NoSQL Create COMPANY database using NoSQL database -
9
MongoDB.
10 Retrieve data from NoSQL database - MongoDB.

5. RUBRICS

Marks Distribution

Continuous Evaluation(50 Marks) End Semester Exam (20 Marks)


Each experiment shall be evaluated for 10
marks and at the end of the semester
proportional marks shall be awarded out of
50.
Following is the breakup of 10 marks for each End semester practical evaluation including
4 Marks: Observation & conduct of Mini project (if any) carries 20 marks.
experiment. Teacher may ask questions about
experiment.
3 Marks: For report writing
3 Marks: For the 15 minutes quiz to be
conducted in every lab.
xv

Database Management System Lab


Manual (CSL 214)

2019-20

Annexure 1

Database Management System


(CSL 214)

Lab Practical Report


xvi

Database Management System Lab


Manual (CSL 214)

2019-20

Faculty Name Student Name

Roll No.:

Semester:

Group:

Department of Computer Science and Engineering

The NorthCap University, Gurugram- 122017, India

Session 2019-20

INDEX
Page Date of Date of CO
S.No Experiment Marks Signature
No. Experiment Submission Covered
xvii

Database Management System Lab


Manual (CSL 214)

2019-20

Experiment No: 1
Student Name and Roll Number:
Semester /Section:
Link to Code:
xviii

Database Management System Lab


Manual (CSL 214)

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.

 A department controls a number of 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.
 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).
xix

Database Management System Lab


Manual (CSL 214)

2019-20

 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.

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

i) Entities (Strong and Weak)


ii) Relationships
iii) Participation constraints
iv) Various types of attribute
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.

o Each entity set has a key.

o Each attribute has a domain.

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

Database Management System Lab


Manual (CSL 214)

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

Database Management System Lab


Manual (CSL 214)

2019-20

ER/EER Diagram
xxii

Database Management System Lab


Manual (CSL 214)

2019-20

Output: Screenshots
xxiii

Database Management System Lab


Manual (CSL 214)

2019-20

Preparatory Questions

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) In which of the following cases an entity instance must be a member of only one subtype?

1) Disjoint with total specialisation


2) Disjoint with partial specialisation
3) Overlap with total specialisation
xxiv

Database Management System Lab


Manual (CSL 214)

2019-20

4) Overlap with Partial Specialisation

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)

Q6) In an Entity-Relationship (ER) model, suppose R is a many-to-one relationship from entity


set E1 to entity set E2. Assume that E1 and E2 participate totally in R and that the cardinality of
E1 is greater that the cardinality of E2. Which one of the following is true about R?
1) Every entity in E1 is associated with exactly one entity in E2.
2) Some entity in E1 is associated with more than one entity in E2.
3) Every entity in E2 is associated with exactly one entity in E1.
4) Every entity in E2 is associated with at most one entity in E1.

Q7) Which symbol denote derived attributes in ER Model?

1) Double ellipse
2) Dashed ellipse
3) Squared ellipse
4) Ellipse with attribute name underlined

Q8)  How are roles specified in an ER diagram


1) By labelling the rectangles
2) By labelling the diamonds
3) Roles cannot be specified in an ER diagram
4) By labelling the lines

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

Database Management System Lab


Manual (CSL 214)

2019-20

2) Strong Entity Set


3) Owner Entity Set
4) Weak Set

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

Database Management System Lab


Manual (CSL 214)

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:

Step 1: Mapping of Regular Entity Types

Step 2: Mapping of Weak Entity Types

Step 3: Mapping of Binary 1:1 Relation Types

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


xxvii

Database Management System Lab


Manual (CSL 214)

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).

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


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.
xxviii

Database Management System Lab


Manual (CSL 214)

2019-20

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 {S1, 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.

Relational Database Design


xxix

Database Management System Lab


Manual (CSL 214)

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

Database Management System Lab


Manual (CSL 214)

2019-20

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}


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?
xxxi

Database Management System Lab


Manual (CSL 214)

2019-20

1) Min 1 and max 2


2) Min 1 and max 3
3) Min 2 and max 3
4) Min 2 and max 2

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

Database Management System Lab


Manual (CSL 214)

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 :

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.
xxxiii

Database Management System Lab


Manual (CSL 214)

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

Database Management System Lab


Manual (CSL 214)

2019-20

Problem Statement
xxxv

Database Management System Lab


Manual (CSL 214)

2019-20

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.
xxxvi

Database Management System Lab


Manual (CSL 214)

2019-20

Syntax to define a Primary key at column level:


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
xxxvii

Database Management System Lab


Manual (CSL 214)

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.

Syntax to define a Unique key at column level:


[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
xxxvii
i

Database Management System Lab


Manual (CSL 214)

2019-20

Preparatory Questions
xxxix

Database Management System Lab


Manual (CSL 214)

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)

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
xl

Database Management System Lab


Manual (CSL 214)

2019-20

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
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)
xli

Database Management System Lab


Manual (CSL 214)

2019-20

Q6) CREATE TABLE course


(...
FOREIGN KEY (dept name) REFERENCES department. . . );
Which of the following is used to delete the entries in the referenced table when the tuple is
deleted in course table?
1) Delete
2) Delete cascade
3) Set null
4) All of the mentioned

Q7) Domain constraints, functional dependency and referential integrity are special forms of ___
1) Foreign key
2) Primary key
3) Assertion
4) Referential constraint

Q8 ) Which of the following can be addressed by enforcing a referential integrity constraint?


1) All phone numbers must include the area code
2) Certain fields are required (such as the email address, or phone number) before the record
is accepted
3) Information on the customer must be known before anything can be sold to that customer
4) When entering an order quantity, the user must input a number and not some text (i.e., 12
rather than ‘a dozen’)

Q9) Given relations r(w, x) and s(y, z), the result of

SELECT DISTINCT w, x

FROM r, s

is guaranteed to be same as r, provided

1) r has no duplicates and s is non-empty


2) r and s have no duplicates
xlii

Database Management System Lab


Manual (CSL 214)

2019-20

3) s has no duplicates and r is non-empty


4) r and s have the same number of tuples

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?

1) x = 5 AND not(not(x = 5))


2) x = 5 AND x> 4 and x < 6, where x is an integer
3) x ≠ 5 AND not (x = 5)
4) None of the above
xliii

Database Management System Lab


Manual (CSL 214)

2019-20

Experiment No: 4
Student Name and Roll Number:
Semester /Section:
Link to Code:
Date:
Faculty Signature:
Remarks:

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’.
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

Database Management System Lab


Manual (CSL 214)

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.

select e.fname,e.lname,d.dname from employee e, department d;

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

Database Management System Lab


Manual (CSL 214)

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

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>

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.
xlvi

Database Management System Lab


Manual (CSL 214)

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.

10) ORDERBY <attributes>


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

Database Management System Lab


Manual (CSL 214)

2019-20

Output: Screenshots
xlviii

Database Management System Lab


Manual (CSL 214)

2019-20

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
xlix

Database Management System Lab


Manual (CSL 214)

2019-20

3) The AS clause defines a search condition


4) All of the mentioned

Q6) Which of the following command is used to delete a table in SQL?

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

Q8) Select operation in SQL is equivalent to

1) the selection operation in relational algebra


2) the selection operation in relational algebra, except that select in SQL retains duplicates
3) the projection operation in relational algebra
4) the projection operation in relational algebra, except that select in SQL retains duplicates
l

Database Management System Lab


Manual (CSL 214)

2019-20

Experiment No: 5
Student Name and Roll Number:
Semester /Section:
Link to Code:
Date:
Faculty Signature:
Remarks:

Objective

To familiarize with different 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


li

Database Management System Lab


Manual (CSL 214)

2019-20

Customers

Customer_i First_name Last_name Birth_date Join_date City Pack_id State


d

Packages

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 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

Database Management System Lab


Manual (CSL 214)

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.

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


liii

Database Management System Lab


Manual (CSL 214)

2019-20

Output: Screenshots
liv

Database Management System Lab


Manual (CSL 214)

2019-20

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
lv

Database Management System Lab


Manual (CSL 214)

2019-20

NATURAL JOIN ( SELECT Bank_Manager, Loan_Amount


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

Q6) The following SQL is which type of join:

SELECT CUSTOMER_T. CUSTOMER_ID, ORDER_T. CUSTOMER_ID, NAME, ORDER_ID


lvi

Database Management System Lab


Manual (CSL 214)

2019-20

FROM CUSTOMER_T,ORDER_T

WHERE CUSTOMER_T. CUSTOMER_ID = ORDER_T. CUSTOMER_ID ?


1) Equi-join
2) Natural join
3) Outer join
4) Cartesian join

Q7) The following SQL is which type of join:

SELECT CUSTOMER_T. CUSTOMER_ID, ORDER_T. CUSTOMER_ID, NAME, ORDER_ID

FROM CUSTOMER_T,ORDER_T ?
1) Equi-join
2) Natural join
3) Outer join
4) Cartesian join

Q8) Which of the following statements is true concerning subqueries?


1) Involves the use of an inner and outer query
2) Cannot return the same result as a query that is not a subquery
3) Does not start with the word SELECT
4) All of the mentioned

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 :

SQ1 : Select * From R Full Join S On R.B = S.B;

SQ2 : Select * From R Inner Join S On R.B = S.B;

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

Database Management System Lab


Manual (CSL 214)

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

Database Management System Lab


Manual (CSL 214)

2019-20

Student Name and Roll Number:


Semester /Section:
Link to Code:
Date:
Faculty Signature:
Remarks:

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

Database Management System Lab


Manual (CSL 214)

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

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


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
lx

Database Management System Lab


Manual (CSL 214)

2019-20

Output: Screenshots
lxi

Database Management System Lab


Manual (CSL 214)

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?

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


lxii

Database Management System Lab


Manual (CSL 214)

2019-20

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

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
lxiii

Database Management System Lab


Manual (CSL 214)

2019-20

3) The query is syntactically correct and gives the correct answer


4) The query contains one or more wrongly named clauses.

Q6) Choose the correct option regarding the query

SELECT branch_name, COUNT (DISTINCT customer_name)


FROM depositor, account
WHERE depositor.account_number = account.account_number
GROUP BY branch_id
HAVING avg(balance) = 10000;
1) The having clause checks whether the query result is true or not
2) The having clause does not check for any condition
3) The having clause allows only those tuples that have average balance 10000
4) None of the mentioned

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

Q8) Consider the following ORACLE relations :

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>}.

Consider the following two SQL queries SQ1 and SQ2 :

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

Database Management System Lab


Manual (CSL 214)

2019-20

1) M = 4, N = 2
2) M = 5, N = 3
3) M = 2, N = 2
4) M = 3, N = 3

Q9) What values does the count(*) function ignore?


1) Repetitive values
2) Null values
3) Characters
4) Integers

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

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
lxv

Database Management System Lab


Manual (CSL 214)

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)

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.
lxvi

Database Management System Lab


Manual (CSL 214)

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

Database Management System Lab


Manual (CSL 214)

2019-20

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
lxviii

Database Management System Lab


Manual (CSL 214)

2019-20

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
1 SC 8204
3 AC 8202
What pids are returned by the following SQL query for the above instance of the tables?
lxix

Database Management System Lab


Manual (CSL 214)

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

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?
lxx

Database Management System Lab


Manual (CSL 214)

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

Database Management System Lab


Manual (CSL 214)

2019-20

Q5) Consider the following relational schema:

employee(empId, empName, empDept)


customer(custId, custName, salesRepId, rating)

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

Database Management System Lab


Manual (CSL 214)

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

Q8) Consider the following Employee table

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

Database Management System Lab


Manual (CSL 214)

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

Q10) Consider the following relation: Cinema (theatre, address, capacity)

Which of the following options will be needed at the end of the SQL query

SELECT P1. address

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

Database Management System Lab


Manual (CSL 214)

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

MongoDB installation and shell familiarity.

Background Study
lxxv

Database Management System Lab


Manual (CSL 214)

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

Database Management System Lab


Manual (CSL 214)

2019-20

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

Output: Screenshots
lxxvii

Database Management System Lab


Manual (CSL 214)

2019-20

Preparatory Questions

Q1) ___________ command displays the list of databases.

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

Database Management System Lab


Manual (CSL 214)

2019-20

1) use dbs
2) use db
3) use mydb
4) use mydbs

Q3) The command to check existence of collection is :

1) show collection
2) show collections
3) show collect
4) None of the mentioned

Q4) 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

Q5) MongoDB stores all documents in:

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

Q6) BSON is a binary representation of ________ documents,

1) JSON
2) XML
3) JScript
4) All of the mentioned
lxxix

Database Management System Lab


Manual (CSL 214)

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

Q9) 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

Q10) 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

Experiment No: 9
lxxx

Database Management System Lab


Manual (CSL 214)

2019-20

Student Name and Roll Number:


Semester /Section:
Link to Code:
Date:
Faculty Signature:
Remarks:

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.

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

Database Management System Lab


Manual (CSL 214)

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.

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.


lxxxii

Database Management System Lab


Manual (CSL 214)

2019-20

Output: Screenshots
lxxxiii

Database Management System Lab


Manual (CSL 214)

2019-20

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.

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

Database Management System Lab


Manual (CSL 214)

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

Database Management System Lab


Manual (CSL 214)

2019-20

"occupation":[ "occupation1":"engineer", "occupation2":"writer"]


}

Q10) Which of the following commands will return all the posts with number of likes greater
than 100 and less than 200, both inclusive?

1) db.posts.find({ likes : { $gt : 100, $lt : 200 } } );


2) db.posts.find({ likes : { $gte : 100, $lt : 200 } } );
3) db.posts.find({ likes : { $gt : 100 , $lte : 200 } } );
4) db.posts.find({ likes : { $gte : 100 , $lte : 200 } } );

Experiment No: 10
Student Name and Roll Number:
Semester /Section:
Link to Code:
Date:
Faculty Signature:
Remarks:

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:
lxxxvi

Database Management System Lab


Manual (CSL 214)

2019-20

 Project Name (Pname)


 Project Number (Pnumber)
 Department Number in which project is being run (Dnum)
 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}
lxxxvi
i

Database Management System Lab


Manual (CSL 214)

2019-20

{ "_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.

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

Database Management System Lab


Manual (CSL 214)

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

Database Management System Lab


Manual (CSL 214)

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

Database Management System Lab


Manual (CSL 214)

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

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

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

Q6)  ____________ is a client or database-generated identifier that uniquely identifies this


message.
1) messageLength
2) responseTo
3) requestID
4) all of the mentioned

Q7) When inserts, updates and deletes have a _________ write concern, write operations return
quickly.
xci

Database Management System Lab


Manual (CSL 214)

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

Database Management System Lab


Manual (CSL 214)

2019-20

1) db.population.aggregate( [{ $group: { _id: { state: "$state", city: "$city" },pop: {


$sum: "$pop" } } }] )
2) db.population.aggregate( [{ $group: { _id: { state: "$state", city: "$city" },pop: {
$sum: 1 } } }] )
3) db.population.aggregate( [{ $group: { _id: { state: "$state", city: "$city" },pop: {
“$pop”: 1 } } }] )
4) db.population.aggregate( [{ $group: { _id: { city: "$city" },pop: { $sum: "$pop" } } }]
)

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()

You might also like