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

DBMS Question Bank

This pdf contains Dbms dds and de lab manuals

Uploaded by

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

DBMS Question Bank

This pdf contains Dbms dds and de lab manuals

Uploaded by

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

PARUL INSTITUTE OF

ENGINEERING AND TECHNOLOGY -


(DIPLOMA STUDIES)

COMPUTER ENGINEERING
DEPARTMENT

DATABASE MANAGEMENT SYSTEM


(03606207)

QUESTION BANK
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

Questions

Unit 1

1. Define following terms. [2 marks per definition] data, databse, information, DBMS,
metadata, records, data dictionary, field.

2. Explain ANSI Sparc architecture. [4 marks]

3. Give the advantages and applications of DBMS. [3 marks]

4. What is database administrator? What is the responsibility of dba? [4 marks]

5. Explain database environment. [4 marks]

6. What is data administrator? What is the responsibility ofda?[4


marks]

7. Give the difference between data and information. [3 marks]

8. What is file oriented system? What are the disadvantages of filesystem?[4


marks]

Unit 2

1. What is SQL? Why it is used? [3 marks]

2. Explain DDL commands in brief. [3 marks per each


statement]

3. Explain DML commands with example. [2 marks per each command]

4. Explain DCL commands with example. [2 marks per each command]

5. Explain TCL commands with example. [2 marks per each command]

6. Explain DQL select query with where clause. [3 marks]

Unit 3

1. Explain SQL operators with example. (3m)

2. Explain order by, group by and having clause with example. (4m)

3. Explain character functions with example. (3m)

4. Explain numeric function with example. (4m)


CE, PIET-DS 1
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

5. Explain conversion function with example. (3m)

6. List aggregate function and explain with example. (4m)

7. Explain types of joins with example. (4m)

8. Explain SQL constraints in brief. (4m)

9. Explain sub query in brief. (4m)

Unit 4

1. Explain types of attributes of entity relationship model. [marks 2 per attribute]

2. Explain entity and entity set in brief. [mark-4]

3. What is relationship? Explain degree of relationship. [mark-4]

4. Explain mapping cardinality with example. [mark-4]

5. Explain er diagram representation of entity and attributes. [mark-5]

6. Draw er diagram for hospital management. [mark-5]

7. Draw diagram for library management system. [mark-5]

8. Explain Enhanced ER Diagram with example. [marks-4]

Unit 5

1. Explain normalization for relational database. [mark-4]

2. Explain various normal forms of DBMS. [mark-4]

3. Explain functional dependency in DBMS. [mark-5]

4. List and explain various inference rules. [mark-5]

5. What is Normalization? Explain 1NF and 2NF with example. [mark-4]

6. Explain 3NF and 4NF with example. [mark-4]

CE, PIET-DS 2
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

Unit-1-introduction to database system


Q.1 Define following terms. [2 marks per definition] (Data, database,
information, DBMS, metadata, records, data dictionary, field.)
 Data: data are pieces of text or data are known facts that can be recorded
or stored. Example, person name, age, city, gender, weight etc.

 Information: information is processed form of data. When data is


processed, organized, structured or presented in a given context to make it
useful, is called information. Example, percentage in student mark sheet

 DBMS: database management system (DBMS) is a software where you can


store, retrieve, define and manage your data in a database. Example,
MYSQL, oracle, Microsoft SQL server, SQLite, mongo dB etc.

 Metadata: metadata is data about data. Example, data such as table name,
column name, data type, authorized users and user access privileges for any
table.

 Records: a record is a collection of logically related fields. Example,


collection of fields (id, name, age, city & pin) forms a record for Customer.

 Data dictionary: data dictionary is an information repository, which


contains metadata. It is usually a part of system catalog. Data dictionary
consists: name of the tables in the database, constraints of a table I.e. Keys,
relationships, etc., columns of the tables that related to each other, owner
of the table, and last accessed information of the object, last updated
information of the object.

 Field: a field is a character or set of characters that have a specific


meaning. It is represented in a database by a value.

Q.2 Explain ANSI Sparc Architecture. [4 marks]


ANSI Sparc - American national standards institute, standards planning and
requirements committee

The ANSI Sparc Architecture divided into three level:

Internal level (physical level) conceptual level (logical level) external level (view
level)
CE, PIET-DS 3
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

Three level ANSI SPARC architecture:

External • View A, View B, View C


Level

Concept • Conceptual View


ual
Level

Interna • Internal View


l Level

1) Internal level (physical level)

 It has an internal schema, which describes the physical storage structure of


the database.

 This schema is also known as a physical schema.

 It uses the physical data model. It is used to define that how the data will be
stored in a block.

 The physical level is used to describe complex low-level data structures in


detail.

2) Conceptual level (logical level)

 It describes the design of a database at the conceptual level. Conceptual


level is also known as logical level.

 It describes the structure of the whole database.

 It level describes what data are to be stored in the database and describes
what Relationship exists among those data.

 In the conceptual level, internal details such as an implementation of the


data structure are hidden.

 Programmers and database administrators work at this level.


CE, PIET-DS 4
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

3) External level (view level):

 At this, a database contains several schemas that sometimes called as


subschema. The subschema is used to describe the different view of the
database.

 An external schema is also known as view schema.

 It describes the database part that a particular user group is interested and
hides the remaining database from that user group.

 It describes the end user interaction with database systems.

Advantages of three level ANSI Sparc architecture:

 Same data can be accessed by different users with different customizes views.

 The user is not conserved about the physical data storage details.

 Physical storage structure can be changed without requiring changes in user’s


view.

 Conceptual structure of database can be changes without affecting end users.

Q.3 Give the advantages and applications of DBMS. [3 marks]


Advantages of DBMS:

 Minimal data redundancy

 Improve data consistency

 Efficient data access

 Improve data sharing

 Improve data integrity

 Improve concurrent access

 Improve data security

 Guarantee atomicity

Application of DBMS:
CE, PIET-DS 5
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

 Building of internet shops & distributed information system. Ex. Amazon

 Building of the virtual company office.

 Storage & requirement of graphic, images, video & audio.

 Creation of web-site allowed to unlimited opportunities. Ex. Banking.

Q.4 What is database administrator? What is the responsibility of DBA?


[4 marks]
Database administrator (DBA):

 It is a person in organization who design & the use of database.

 It must need technical support for implementing a database. DBA doesn’t


business person.

 It is involved more in the design, development, testing & operational phases.

Function & responsibilities of DBA:

 Schema definition

 Storage structure & access method definition

 Assisting application programmers

 Physical organization modification

 Approving data access

 Monitoring performance

 Back up & recovery

CE, PIET-DS 6
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

Q.5 Explain database environment. [4 marks]

A database environment is a collective system of components that comprise and regulates


the group of data, management, and use of data, which consist of software, hardware,
people, techniques of handling database, and the data also.

The hardware in a database environment means the computers and computer peripherals
that are being used to manage a database, and the software means the whole thing right
from the operating system (OS) to the application programs management software like
M.S. Access or SQL-Server.

The people in a database environment include those people who administrate and use the
System.

Q.6 What is data administrator? What are the responsibilities of DA?


[4marks]
Data administrator (DA):

 It is person in organization who control the data of the database.

 It determines what data to be stored in database on requirement of


organization.

 It is more involved more in the requirement gathering, analysis & design


CE, PIET-DS 7
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

phases.

 It is senior level person in an organization who understand requirements with


respect to data.

 It does not need to be a technical person. It is business focused person.

Responsibility of data administrator:

 Filters out relevant data

 Monitor the data flow throughout the organization

 Designs concept-based data model

 Analyze and break down the data to be understood by the non-tech person

Q.7 Give the difference between data and information. [3 marks]

Data Information

Data is the raw fact. It is a processed form of data.

It is not significant to a business. It is significant to a business.

Data is an atomic level piece of It is a collection of data.


information.

Example: product name, name of Example: report card of student.


student.

It is a phenomenal fact. It is organized data.

This is the primary level of intelligence. It is a secondary level of intelligence.

May or may not be meaningful. Always meaningful.

CE, PIET-DS 8
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

Understanding is difficult. Understanding is easy.

Q.8 What is file-oriented system? What are the disadvantages of file


system? [4marks]
File-oriented system:

 It is providing useful information about how data & managed earlier.

 Characteristics of this system that provide understanding complexities in


designing a database.

 It provides useful knowledge for converting a file system to a database system.

Disadvantages of file-oriented system:

 Data redundancy:

It is possible that same information may be duplicated in different fields.

 Data inconsistency:

Due to redundancy, it is possible that data may not be in consistent sate.

 Difficulty in accessing data:

Accessing data is not convenient & efficient in file processing system.

 Limited sharing:

Data stored in different formats, different folder & different computers, due
to this data isolation. It is difficult to share data among different application.

CE, PIET-DS 9
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

Unit – 2- Introduction to SQL


Q.1 What is SQL? Why it Is used? [3 MARKS]
SQL (Structured Query Language) is a domain-specific language used for managing and
manipulating data in a relational database. SQL allows users to create, modify, and query
databases, as well as define relationships between different tables in the database.

SQL is widely used because it provides a standard way to interact with a database,
regardless of the specific database management system being used. SQL is also highly
efficient at managing large amounts of data, making it a popular choice for organizations
that need to store and analyze large datasets.

SQL is used in a variety of applications, including financial systems, healthcare


databases, e-commerce platforms, and more. Some common uses of SQL include:

1. Data retrieval: SQL is used to retrieve specific data from a database, such as
customer information or product inventory.
2. Data manipulation: SQL allows users to add, delete, or modify data within a
database.
3. Database management: SQL is used to manage the structure and relationships
between tables within a database.
4. Data analysis: SQL can be used to perform complex queries and aggregate data
from multiple tables, making it a powerful tool for data analysis and reporting.

CE, PIET-DS 10
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

Q.2 Explain DDL Commands in brief. [3 MARKS PER EACH


STATEMENT]
DDL (Data Definition Language) commands are used to define the structure of a
database, including creating, altering, and dropping database objects. Here are some
examples of DDL commands and their purposes:

1. CREATE: This command is used to create a new database object, such as a table,
view, or index. The syntax for the CREATE command varies depending on the
type of object being created.

Syntax:

CREATE TABLE table_name (


column1 datatype [ NULL | NOT NULL ],
column2 datatype [ NULL | NOT NULL ],
...
columnN datatype [ NULL | NOT NULL ]
);

Example:

CREATE TABLE employees (


id INT PRIMARY KEY,
name VARCHAR(50),
age INT,
department VARCHAR(50)
);

2. ALTER: This command is used to modify the structure of an existing database


object. For example, you can use the ALTER command to add or remove columns
from a table, change the data type of a column, or rename a table.
Syntax:
ALTER TABLE table_name
ADD column_name datatype;
Example:
ALTER TABLE employees
ADD salary DECIMAL(10,2);

CE, PIET-DS 11
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

3. DROP: This command is used to delete an existing database object. The DROP
command can be used to delete a table, view, index, or other object from the
database.
Syntax:
DROP TABLE table_name;
Example:
DROP TABLE employees;

4. TRUNCATE: This command is used to delete all data from a table without deleting
the table structure itself. TRUNCATE is faster than using the DELETE command
because it does not log each row deletion.
Syntax:
TRUNCATE TABLE table_name;
Example:
TRUNCATE TABLE employees;

5. RENAME: This command is used to change the name of an existing database


object. For example, you can use the RENAME command to change the name of
a table or view.
Syntax:
ALTER TABLE old_table_name RENAME TO new_table_name;

Example:

ALTER TABLE employees RENAME TO staff;

6. COMMENT: This command is used to add comments to a database object.


Comments can be used to document the purpose of the object or provide
information about its structure.
Syntax:
COMMENT ON TABLE table_name IS 'comment';
Example:
COMMENT ON TABLE staff IS 'This table contains information about the
company employees.';

7. GRANT: This command is used to grant privileges or permissions to a user or


group of users. For example, you can use the GRANT command to allow a user to
access a table or view.
Syntax:
GRANT permission(s) ON object_name TO user_name;

CE, PIET-DS 12
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

Example:

CE, PIET-DS 13
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

GRANT SELECT, INSERT, UPDATE ON employees TO john;

Q.3 Explain DML commands with example. [2 MARKS PER EACH


COMMAND]
Table: employees

CREATE TABLE employees (

id INT PRIMARY KEY,

name VARCHAR(50),

age INT,

department VARCHAR(50),

salary DECIMAL(10,2)

);

Output:

DML (Data Manipulation Language) commands are used to manipulate data within a
database. Here are some common DML commands along with their syntax and examples:

1. INSERT: This command is used to insert data into a table.


Syntax:

INSERT INTO table_name (column1, column2, column3, ...) VALUES


(value1, value2, value3, ...);

Example:

INSERT INTO employees (id, name, age, department, salary) VALUES (1,
'John Doe', 30, 'Sales', 50000);

INSERT INTO employees (id, name, age, department, salary) VALUES (2,
'arti', 28, 'Sales', 51000);
CE, PIET-DS 14
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

INSERT INTO employees (id, name, age, department, salary) VALUES (3,
'sidddhi', 20, 'Sales', 52000);

Output:

2. UPDATE: This command is used to update existing data in a table.

Syntax:

UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE


condition;

Example:

UPDATE employees SET salary = 55000 WHERE id = 1;

Output:

3. DELETE: This command is used to delete data from a table.

Syntax:

DELETE FROM table_name WHERE condition;

Example:

DELETE FROM employees WHERE id = 1;


CE, PIET-DS 15
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

Output:

4. SELECT: This command is used to retrieve data from a table.

Syntax:

SELECT column1, column2, ... FROM table_name WHERE condition;

Example:

SELECT name, age, department FROM employees WHERE salary >


51000;

Output:

5. MERGE: This command is used to insert, update, or delete data in a table based
on a specified condition.

Syntax:

MERGE INTO target_table

USING source_table ON condition

WHEN MATCHED THEN UPDATE SET column1 = value1, column2 = value2,


...

WHEN NOT MATCHED THEN INSERT (column1, column2, ...) VALUES


(value1, value2, ...)

WHEN NOT MATCHED BY SOURCE THEN DELETE;


CE, PIET-DS 16
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

Example:

MERGE INTO employees e

USING new_employees n ON (e.id = n.id)

WHEN MATCHED THEN UPDATE SET e.salary = n.salary

WHEN NOT MATCHED THEN INSERT (id, name, age, department, salary)
VALUES (n.id, n.name, n.age, n.department, n.salary)

WHEN NOT MATCHED BY SOURCE THEN

DELETE;

Q.4 Explain DCL commands with example. [2 MARKS PER


EACHCOMMAND]
DCL (Data Control Language) commands are used to control access to data within a
database. Here are some common DCL commands along with their syntax and examples:

1. GRANT: This command is used to grant privileges to a user or a group of users.


Syntax:

GRANT privilege ON object TO user;

Example:

GRANT SELECT, INSERT, UPDATE ON employees TO john;

2. REVOKE: This command is used to revoke privileges from a user or a group of


users.

Syntax:

REVOKE privilege ON object FROM user;

Example:

REVOKE INSERT, UPDATE ON employees FROM john;

Q.5 Explain TCL commands with example. [2 MARKS PER


EACHCOMMAND]

CE, PIET-DS 17
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

TCL (Transaction Control Language) commands are used to control transactions in a


database. Here are some common TCL commands along with their syntax and examples:

1. COMMIT: This command is used to permanently save the changes made in a


transaction to the database.

Syntax:

COMMIT;

Example:

START TRANSACTION; UPDATE employees SET salary = 55000


WHERE id = 1; COMMIT;

2. ROLLBACK: This command is used to undo the changes made in a transaction


and return the database to its previous state.

Syntax:

ROLLBACK;

Example:

START TRANSACTION; UPDATE employees SET salary = 55000


WHERE id = 1; ROLLBACK;

3. SAVEPOINT: This command is used to create a savepoint within a transaction,


which allows you to rollback to that point if necessary.

Syntax:

SAVEPOINT savepoint_name;

Example:

START TRANSACTION; UPDATE employees SET salary = 55000 WHERE


id = 1; SAVEPOINT salary_update; UPDATE employees SET salary = 60000
WHERE id = 2; ROLLBACK TO salary_update;

4. SET TRANSACTION: This command is used to set the properties of a transaction,


such as its isolation level or its access mode.

Syntax:

CE, PIET-DS 18
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

SET TRANSACTION isolation_level, access_mode;

Example:

START TRANSACTION; SET TRANSACTION ISOLATION LEVEL


READ COMMITTED, READ WRITE; UPDATE employees SET salary =
55000 WHERE id = 1; COMMIT;

Q.6 Explain DQL Select Query with Where clause. [3 MARKS]


DQL (Data Query Language) is used to retrieve data from a database. The SELECT
statement is used to retrieve data from one or more tables in a database. The WHERE
clause is used to filter the results of a SELECT statement based on a specified condition.

The syntax for a SELECT statement with a WHERE clause is as follows:

SELECT column1, column2, ... FROM table_name WHERE condition;

Here, column1, column2, ... are the names of the columns that you want to retrieve data
from, and table_name is the name of the table from which you want to retrieve data. The
WHERE clause specifies the condition that must be met in order for a row to be included
in the result set.

For example, suppose you have a table called employees with columns id, name,
department, and salary. You can use the following SELECT statement to retrieve the
names and salaries of all employees who work in the "Sales" department and earn more
than $50,000:

Example:

SELECT name, salary FROM employees WHERE department = 'Sales' AND salary >
50000;

Output:

In this example, the WHERE clause specifies that only rows where the department is
CE, PIET-DS 19
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

"Sales" and the salary is greater than 50,000 should be included in the result set. The
SELECT statement retrieves the name and salary columns from these rows.

Unit – 3- Working with SQL functions and Operators


Q.1 Explain SQL operators with example.
 Arithmetic operators:

We can use various arithmetic operators on the data stored in the tables.
Arithmetic Operators are:

Operator

1 + The addition is used to perform an addition operation on the data


values.

2 – This operator is used for the subtraction of the data values.

3 / This operator works with the ‘ALL’ keyword and it calculates

division operations.

4 * This operator is used for multiply data values.

5 % Modulus is used to get the remainder when data is divided by


another.

 Comparison operators:

Another important operator in SQL is a comparison operator, which is used to


compare one expression’s value to other expressions. SQL supports different
types of the comparison operator, which is described below: S.No.
Operator Description

1 = Equal to.

2 > Greater than.

3 < Less than.

4 >= Greater than equal to.

5 <= Less than equal to.

CE, PIET-DS 20
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

6 <> Not equal to.

 Logical operators:

The Logical operators are those that are true or false. They return true or false values to
combine one or more true or false values.

1. AND: Logical AND compares between two Booleans as expressions and returns
true when both expressions are true.

2. OR: Logical OR compares between two Booleans as expressions and returns true
when one of the expressions is true.

3. NOT: Not takes a single Boolean as an argument and changes its value from false
to true or from true to false.

 SQL BETWEEN (RANGE SEARCHING OPERATOR)

The SQL BETWEEN operator tests an expression against a range. The range consists of
a beginning, followed by an AND keyword and an end expression.

The operator returns TRUE when the search value present within the range otherwise
returns FALSE.

The results are NULL if any of the range values are NULL.

Syntax:

SELECT [column_name... | expression1] FROM [table_name]

WHERE expression2 [NOT] BETWEEN value_from AND value_to;

Example:

CREATE TABLE employees (

id INT PRIMARY KEY,

name VARCHAR(50),

age INT,

department VARCHAR(50),
CE, PIET-DS 21
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

salary DECIMAL(10,2)

);

INSERT INTO employees (id, name, age, department, salary) VALUES (1, 'John Doe',
30, 'Sales', 50000);

INSERT INTO employees (id, name, age, department, salary) VALUES (2, 'arti', 28,
'Sales', 51000);

INSERT INTO employees (id, name, age, department, salary) VALUES (3, 'sidddhi',
20, 'Sales', 52000);

SELECT * FROM employees

WHERE salary BETWEEN 51000 AND 55000;

Output:

 SQL LIKE (CHARACTER OPERATOR)

The LIKE command is used in a WHERE clause to search for a specified pattern in a
column.

You can use two wildcards with LIKE:

% - Represents zero, one, or multiple characters

_ - Represents a single character (MS Access uses a question mark (?) instead)

The following SQL selects all customers with a CustomerName starting with "a":

Syntax:

Columnname LIKE pattern;

Example:
CE, PIET-DS 22
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

SELECT * FROM employees WHERE name LIKE 'a%';

CE, PIET-DS 23
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

Output:

 SQL IN (SET SEARCHINGOPERATOR)

The IN command allows you to specify multiple values in a WHERE clause.

The IN operator is a shorthand for multiple OR conditions.

The following SQL selects all customers that are located in "Germany", "France" and
"UK":

Syntax:

Columnname IN (valueset1, valuesset2…. valuesetN);

Example:

CREATE TABLE employees (

id INT PRIMARY KEY,

name VARCHAR(50),

age INT,

department VARCHAR(50),

salary DECIMAL(10,2)

);

INSERT INTO employees (id, name, age, department, salary) VALUES (1, 'John Doe',
30, 'A', 50000);

INSERT INTO employees (id, name, age, department, salary) VALUES (2, 'arti', 28,
'B', 51000);

INSERT INTO employees (id, name, age, department, salary) VALUES (3, 'sidddhi',
20, 'C', 52000);
CE, PIET-DS 24
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

SELECT * FROM employees

WHERE department IN ('A','B');

Output:

Q. 2 Explain Order by, Group by and having clause with example.


 GROUP BY:

The GROUP BY command is used to group the result set (used with aggregate functions:
COUNT, MAX, MIN, SUM, AVG).

The following SQL lists the number of customers in each country: Example

SELECT COUNT(CustomerID), Country FROM Customers

GROUP BY Country;

Example:

CREATE TABLE employees (

id INT PRIMARY KEY,

name VARCHAR(50),

age INT,

department VARCHAR(50),

salary DECIMAL(10,2)

);

INSERT INTO employees (id, name, age, department, salary) VALUES (1, 'John Doe',
28, 'A', 50000);

CE, PIET-DS 25
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

INSERT INTO employees (id, name, age, department, salary) VALUES (2, 'arti', 28, 'B',
51000);

INSERT INTO employees (id, name, age, department, salary) VALUES (3, 'sidddhi', 20,
'C', 52000);

SELECT COUNT(id), age

FROM employees

GROUP BY age;

Output:

 HAVING:

The HAVING command is used instead of WHERE with aggregate functions.

The following SQL lists the number of customers in each country. Only include countries
with more than 5 customers:

Example

CREATE TABLE employees (

id INT PRIMARY KEY,

name VARCHAR(50),

age INT,

department VARCHAR(50),

salary DECIMAL(10,2)

);

INSERT INTO employees (id, name, age, department, salary) VALUES (1, 'John Doe',
CE, PIET-DS 26
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

28, 'A', 50000);

INSERT INTO employees (id, name, age, department, salary) VALUES (2, 'arti', 28, 'B',
51000);

INSERT INTO employees (id, name, age, department, salary) VALUES (3, 'sidddhi', 20,
'C', 52000);

SELECT COUNT(id), age FROM employees

GROUP BY age

HAVING COUNT(id) < 2;

Output:

 ORDER BY

The ORDER BY command is used to sort the result set in ascending or descending order.

The ORDER BY command sorts the result set in ascending order by default. To sort the
records in descending order, use the DESC keyword. The following SQL statement
selects all the columns from the "Customers" table, sorted by the "CustomerName"
column:

Example:

SELECT * FROM Customers ORDER BY CustomerName;

1)ASC

The ASC command is used to sort the data returned in ascending order. The following
SQL statement selects all the columns from the "Customers" table, sorted by the
"CustomerName" column:

Example:

CREATE TABLE employees (


CE, PIET-DS 27
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

id INT PRIMARY KEY,

name VARCHAR(50),

age INT,

department VARCHAR(50),

salary DECIMAL(10,2)

);

INSERT INTO employees (id, name, age, department, salary) VALUES (1, 'John Doe',
28, 'A', 50000);

INSERT INTO employees (id, name, age, department, salary) VALUES (2, 'arti', 28, 'B',
51000);

INSERT INTO employees (id, name, age, department, salary) VALUES (3, 'sidddhi', 20,
'C', 52000);

SELECT * FROM employees ORDER BY department asc;

Output:

2)DESC

The DESC command is used to sort the data returned in descending order. The following
SQL statement selects all the columns from the "Customers" table, sorted descending by
the "CustomerName" column:

Example:

CREATE TABLE employees (

id INT PRIMARY KEY,


CE, PIET-DS 28
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

name VARCHAR(50),

age INT,

department VARCHAR(50),

salary DECIMAL(10,2)

);

INSERT INTO employees (id, name, age, department, salary) VALUES (1, 'John Doe',
28, 'A', 50000);

INSERT INTO employees (id, name, age, department, salary) VALUES (2, 'arti', 28, 'B',
51000);

INSERT INTO employees (id, name, age, department, salary) VALUES (3, 'sidddhi', 20,
'C', 52000);

SELECT * FROM employees ORDER BY department desc;

Output:

Q. 3 Explain Character functions with example.


 LOWER: This function converts alpha character values to lowercase. LOWER will
actually return a fixed-length string if the incoming string is fixed-length.

LOWER will not change any characters in the string that are not letters, since case is
irrelevant for numbers and special characters, such as the dollar sign ( $ ) or modulus ( %
).

Syntax:

LOWER (string)

CE, PIET-DS 29
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

Input1: SELECT LOWER('HELLO') FROM DUAL;

Output1: hello

 UPPER: This function converts alpha character values to uppercase. Also, UPPER
function too, will actually return a fixed-length string if the incoming string is fixed-
length. UPPER will not change any characters in the string that are not letters, since
case is irrelevant for numbers and special characters, such as the dollar sign ( $ ) or
modulus ( % ).

Syntax:

UPPER (string)

Input1: SELECT UPPER('hello') FROM DUAL;

Output1: HELLO

 INITCAP: This function converts alpha character values to uppercase for the first letter
of each word and all others in lowercase.

The words in the string is must be separated by either # or _ or space.

Syntax:

INITCAP (string)

Input1: SELECT INITCAP ('web port is a computer science portal') FROM DUAL;

Output1: Web Port Is A Computer Science Portal

 CONCAT: This function always appends (concatenates ) string2 to the end of string1.

If either of the string is NULL, CONCAT function returns the non-NULL argument.
If both strings are NULL, CONCAT returns NULL.

Syntax:

CONCAT ('String1', 'String2')

Input1: SELECT CONCAT ('computer’, ‘science') FROM DUAL; Output1: computer


science

 LENGTH: This function returns the length of the input string.

CE, PIET-DS 30
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

If the input string is NULL, then LENGTH function returns NULL and not Zero. Also,
if the input string contains extra spaces at the start, or in between or at the end of the
string, then the LENGTH function includes the extra spaces too and returns the
complete length of the string.

Syntax:

LENGTH (Column|Expression)

Input1: SELECT LENGTH ('Learning Is Fun') FROM DUAL; Output1: 15

 LPAD and RPAD: These functions return the strings padded to the left or right (as per
the use);

hence the “L” in “LPAD” and the “R” in “RPAD”; to a specified length,

and with a specified pad string.

If the pad string is not specified, then the given string is padded on the left or right (as
per the use) with spaces.

Syntax:

LPAD (Column|Expression, n, 'String')

Syntax: RPAD (Column|Expression, n, 'String')

LPAD Input1: SELECT LPAD ('100',5,'*') FROM DUAL;

LPAD Output1: **100

RPAD Input1: SELECT RPAD ('5000',7,'*') FROM DUAL;

RPAD Output1: 5000***

 TRIM: This function trims the string input from the start or end (or both).

If no string or char is specified to be trimmed from the string and there exists some
extra space at start or end of the string, then those extra spaces are trimmed off.

Syntax:

TRIM (Leading|Trailing|Both, trim_character FROM trim_source) Input1: SELECT


TRIM ('G' FROM 'GEEKS') FROM DUAL;

CE, PIET-DS 31
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

Output1: EEKS

Q. 4 Explain Numeric function with example.


Numeric Functions are used to perform operations on numbers and return numbers.

Following are the numeric functions defined in SQL:

 ABS (): It returns the absolute value of a number. Syntax: SELECT ABS (-
243.5);

Output: 243.5

 ACOS (): It returns the cosine of a number. Syntax: SELECT ACOS (0.25);

Output: 1.318116071652818

 ASIN (): It returns the arc sine of a number. Syntax: SELECT ASIN (0.25);

Output: 0.25268025514207865

 ATAN (): It returns the arc tangent of a number. Syntax: SELECT ATAN (2.5);

Output: 1.1902899496825317

 CEIL (): It returns the smallest integer value that is greater than or equal to a
number.

Syntax: SELECT CEIL (25.75);

Output: 26

 DIV (): It is used for integer division. Syntax: SELECT 10 DIV 5;

Output: 2

 EXP (): It returns be raised to the power of number. Syntax: SELECT EXP (1);

Output: 2.718281828459045

 FLOOR (): It returns the largest integer value that is less than or equal to a
number.

Syntax: SELECT FLOOR (25.75);

Output: 2
CE, PIET-DS 32
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

 GREATEST (): It returns the greatest value in a list of expressions. Syntax:


SELECT GREATEST (30, 2, 36, 81, 125);

Output: 125

 LEAST (): It returns the smallest value in a list of expressions. Syntax: SELECT
LEAST (30, 2, 36, 81, 125);

Output: 2

 LN (): It returns the natural logarithm of a number. Syntax: SELECT LN (2);

Output: 0.6931471805599453

 MOD (): It returns the remainder of n divided by m. Syntax: SELECT MOD (18,
4);

Output: 2

 PI(): It returns the value of PI displayed with 6 decimal places. Syntax: SELECT
PI();

Output: 3.141593

 POW(): It returns m raised to the nth power. Syntax: SELECT POW(4, 2);

Output: 16

 ROUND(): It returns a number rounded to a certain number of decimal places.

Syntax: SELECT ROUND(5.553);

Output: 6

 SIN(): It returns the sine of a number. Syntax: SELECT SIN(2);

Output: 0.9092974268256817

 SQRT(): It returns the square root of a number. Syntax: SELECT SQRT(25);

Output: 5

 TAN(): It returns the tangent of a number. Syntax: SELECT TAN(1.75);

Output: -5.52037992250933

CE, PIET-DS 33
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

 TRUNCATE(): This doesn’t work for SQL Server. It returns 7.53635

truncated to 2 places right of the decimal point.

Syntax: SELECT TRUNCATE(7.53635, 2);

Output: 7.53

Q. 5 Explain conversion function with example.


 TO_CHAR Function :

TO_CHAR function is used to typecast a numeric or date input to character type with a
format model (optional).

SYNTAX :

TO_CHAR(date, ’format_model’)

example:

SELECT employee_id, TO_CHAR(hire_date, ’MM/YY’) Month_Hired

FROM employees

WHERE last_name = ’Higgins’;

OUTPUT :

EMPLOYEE_ID MONTH_HIRED 205 06/94

 TO_NUMBER: (char[, ’format_model’])

Convert a character string to a date format using the TO_DATE function:

TO_DATE:(char[, ’format_model’])

These functions have an fx modifier. This modifier specifies the exact matching for the
character argument and date format model of a TO_DATE function.

EXAMPLE :

SELECT last_name, hire_date FROM employees

WHERE hire_date = TO_DATE(’May 24, 1999’, ’fxMonth DD, YYYY’);

CE, PIET-DS 34
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

OUTPUT :

LASTNAME HIREDATE Kumar 24-MAY-99

Q. 6 List Aggregate function and explain with example.


 Count():

Count(*): Returns total number of records .i.e 6.

Count(salary): Return number of Non Null values over the column salary.

i.e 5.

Count(Distinct Salary): Return number of distinct Non Null values over the column
salary .i.e 4

Example:

Select count(total_sal) from employee;

Output: 5

 Sum():

sum(salary): Sum all Non Null values of Column salary i.e., 310 sum(Distinct salary):
Sum of all distinct Non-Null values i.e., 250. Example:

Select sum(total_sal) from employee;

Output: 456000

 Avg():

Avg(salary) = Sum(salary) / count(salary) = 310/5

Avg(Distinct salary) = sum(Distinct salary) / Count(Distinct Salary) = 250/4

Example:

Select avg(total_sal) from employee;

Output: 50.56

 Min():

CE, PIET-DS 35
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

Min(salary): Minimum value in the salary column except NULL i.e., 40. Max(salary):
Maximum value in the salary i.e., 80.

Example:

Select max(total_sal) from employee;

Output: 50000

Select min(total_sal) from employee; Output: 20000

Q. 7 Explain types of joins with example.


 INNER JOIN

The INNER JOIN keyword selects all rows from both the tables as long as the condition
is satisfied.

This keyword will create the result-set by combining all rows from both the tables
where the condition satisfies i.e value of the common field will be the same.

Syntax:

SELECT table1.column1,table1.column2,table2.column1,....

FROM table1 INNER JOIN table2

ON table1.matching_column = table2.matching_column;

Example Queries(INNER JOIN)

SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM Student

INNER JOIN StudentCourse

ON Student.ROLL_NO = StudentCourse.ROLL_NO; Output:

CE, PIET-DS 36
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

 LEFT JOIN

This join returns all the rows of the table on the left side of the join and matches rows
for the table on the right side of the join.

For the rows for which there is no matching row on the right side, the result-set will
contain null. LEFT JOIN is also known as LEFT OUTER JOIN.

Syntax:

SELECT table1.column1,table1.column2,table2.column1,....

FROM table1 LEFT JOIN table2

ON table1.matching_column = table2.matching_column;

Example Queries(LEFT JOIN):

SELECT Student.NAME,StudentCourse.COURSE_ID FROM Student

LEFT JOIN StudentCourse

ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output:

CE, PIET-DS 37
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

 RIGHT JOIN

RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of the table on the
right side of the join and matching rows for the table on the left side of the join.

For the rows for which there is no matching row on the left side, the result- set will
contain null. RIGHT JOIN is also known as RIGHT OUTER JOIN. Syntax:

SELECT table1.column1,table1.column2,table2.column1,....

FROM table1 RIGHT JOIN table2

ON table1.matching_column = table2.matching_column;

Example Queries(RIGHT JOIN):

SELECT Student.NAME,StudentCourse.COURSE_ID FROM Student

RIGHT JOIN StudentCourse

ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output:

CE, PIET-DS 38
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

 FULL JOIN

FULL JOIN creates the result-set by combining results of both LEFT JOIN and RIGHT
JOIN.

The result-set will contain all the rows from both tables. For the rows for which there is
no matching, the result-set will contain NULL values.

Syntax:

SELECT table1.column1,table1.column2,table2.column1,....

FROM table1 FULL JOIN table2

ON table1.matching_column = table2.matching_column;

Example Queries(FULL JOIN):

SELECT Student.NAME,StudentCourse.COURSE_ID FROM Student

FULL JOIN StudentCourse

ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output:

Q. 8 Explain SQL constraints in brief.


 NOT NULL

CE, PIET-DS 39
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

If we specify a field in a table to be NOT NULL. Then the field will never accept null
value.

That is, you will be not allowed to insert a new row in the table without specifying any
value to this field.

For example, the below query creates a table Student with the fields ID and NAME as
NOT NULL.

That is, we are bound to specify values for these two fields every time we wish to insert
a new row.

EXAMPLE:

CREATE TABLE Student (

ID int(6) NOT NULL,

NAME varchar(10) NOT NULL,

ADDRESS varchar(20)

 UNIQUE

This constraint helps to uniquely identify each row in the table. i.e. for a particular
column, all the rows should have unique values.

We can have more than one UNIQUE columns in a table.

For example, the below query creates a table Student where the field ID is specified as
UNIQUE. i.e, no two students can have the same ID. Unique constraint in detail.

Example:

CREATE TABLE Student

(ID int(6) NOT NULL UNIQUE,

NAME varchar(10), ADDRESS varchar(20)

);

 PRIMARY KEY

Primary Key is a field which uniquely identifies each row in the table.
CE, PIET-DS 40
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

If a field in a table as primary key, then the field will not be able to contain NULL values
as well as all the rows should have unique values for this field.

So, in other words we can say that this is combination of NOT NULL and UNIQUE
constraints.

A table can have only one field as primary key. Below query will create a table named
Student and specifies the field ID as primary key.

Example:

CREATE TABLE Student

(ID int(6) NOT NULL UNIQUE,

NAME varchar(10),

ADDRESS varchar(20), PRIMARY KEY(ID)

 FOREIGN KEY

Foreign Key is a field in a table which uniquely identifies each row of a another table.

That is, this field points to primary key of another table. This usually creates a kind of
link between the tables.

Consider the two tables as shown below:

C_ID NAME ADDRESS

1 RAMESH DELHI

2 SURESH NOIDA

3 DHARMESH GURGAON

As we can see clearly that the field C_ID in Orders table is the primary key in
Customers table, i.e. it uniquely identifies each row in the Customers table. Therefore, it
is a Foreign Key in Orders table.

Query:

CREATE TABLE Orders (O_ID int NOT NULL, ORDER_NO int NOT NULL,

C_ID int,
CE, PIET-DS 41
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

PRIMARY KEY (O_ID),

FOREIGN KEY (C_ID) REFERENCES Customers(C_ID));

 CHECK

Using the CHECK constraint we can specify a condition for a field, which should be
satisfied at the time of entering values for this field.

For example, the below query creates a table Student and specifies the condition for the
field AGE as (AGE >= 18 ).

That is, the user will not be allowed to enter any record in the table with AGE <18.
Check constraint in detail

Example:

CREATE TABLE Student

ID int(6) NOT NULL,

NAME varchar(10) NOT NULL,

AGE int NOT NULL CHECK (AGE >= 18)

);

Q. 9 Explain sub query in brief.


In SQL a Subquery can be simply defined as a query within another query. In other
words we can say that a Subquery is a query that is embedded in WHERE clause of
another SQL query.

Important rules for Subqueries:

 You can place the Subquery in a number of SQL clauses: WHERE clause, HAVING
clause, FROM clause.

 Subqueries can be used with SELECT, UPDATE, INSERT, DELETE statements


along with expression operator. It could be equality operator or comparison operator
such as =, >, =, <= and Like operator.

 A subquery is a query within another query. The outer query is called as main query
CE, PIET-DS 42
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

and inner query is called as subquery.

 ORDER BY command cannot be used in a Subquery. GROUPBY command can be


used to perform same function as ORDER BY command.

Syntax:

There is not any general syntax for Subqueries.

However, Subqueries are seen to be used most frequently with SELECT statement as
shown below:

SELECT column_name

FROM table_name

WHERE column_name expression operator

(SELECT COLUMN_NAME from TABLE_NAME WHERE ... );

To display NAME, LOCATION, PHONE_NUMBER of the students from


DATABASE table whose section is A:

Example:

Select NAME, LOCATION, PHONE_NUMBER from DATABASE WHERE


ROLL_NO IN

(SELECT ROLL_NO from STUDENT where SECTION=’A’);

Output:

NAME ROLL_NO LOCATION PHONE_NUMBER

Ravi 104 delhi 8989898989

CE, PIET-DS 43
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

Unit – 4-Introduction to Data models


Q.1 Explain types of attributes of Entity relationship model.
An attribute is a property or characteristic of an entity.

An entity may contain any number of attributes.

One of the attributes is considered as the primary key. In an Entity-Relation model,


attributes are represented in an elliptical shape.

Example:

 Student has attributes like name, age, roll number, and many more. To uniquely
identify the student, we use the primary key as a roll number as it is not repeated.
Attributes can also be subdivided into another set of attributes.

 There are five such types of attributes: Simple, Composite, Single-valued, Multi-
valued, and Derived attribute. One more attribute is their, i.e. Complex Attribute,
this is the rarely used attribute.

CE, PIET-DS 44
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

1)Simple attribute:

 An attribute that cannot be further subdivided into components is a simple


attribute.

Example:

 The roll number of a student, the id number of an employee.

2)Composite attribute:

 An attribute that can be split into components is a composite attribute.

Example:

 The address can be further split into house number, street number, city, state,
country, and pin code, the name can also be split into first name middle name, and
last name.

3)Single-valued attribute:

 The attribute which takes up only a single value for each entity instance is a single-
valued attribute.

Example:

 The age of a student.

4)multi-valued attribute:

 The attribute which takes up more than a single value for each entity instance is a
multi-valued attribute.

Example:

 Phone number of a student: Landline and mobile.

5)Derived attribute:

 An attribute that can be derived from other attributes is derived attributes.

Example:

 Total and average marks of a student.

CE, PIET-DS 45
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

6)Complex attribute:

 Those attributes, which can be formed by the nesting of composite and multi-
valued attributes, are called “Complex Attributes”. These attributes are rarely used
in DBMS(DataBase Management System). That’s why they are not so popular.

Example:

 Let us consider a person having multiple phone numbers, emails, and an address.

 Here, phone number and email are examples of multi-valued attributes and address
is an example of the composite attribute, because it can be divided into house
number, street, city, and state.

Q.2 Explain Entity and Entity set in brief. [MARK-4]


Entity:

 An entity is a thing in a real-world with independent existence. An entity can exist


independently and is distinguishable from other objects. It can be identified
uniquely.

Example:

 A student with a particular roll number is an entity.

 A company with a particular registration number is an entity.

Entity Set:
CE, PIET-DS 46
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

 An entity set is a collection or set of all entities of a particular entity type at any
point in time. The type of all the entities should be the same.

Example:

 The collection of all the students from the student table at a particular instant of
time is an example of an entity set.

 The collection of all the employees from the employee table at a particular instant
of time is an example of an entity set.

Q.3 What is relationship? Explain degree of relationship. [MARK-4]


Relationship

 In DBMS, a degree of relationship represents the number of entity types that


associate in a relationship.

For example:

 We have two entities, one is a student and the other is a bag and they are connected
with the primary key and foreign key. So, here we can see that the degree of
relationship is 2 as 2 entities are associating in a relationship.

Types of degree

 Now, based on the number of linked entity types, we have 4 types of degrees of
relationships.

1) Unary

2) Binary
CE, PIET-DS 47
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

3) Ternary

4) N-ARY

1)Unary

 In this type of relationship, both the associating entity type are the same.

 So, we can say that unary relationships exist when both entity types are the same
and we call them the degree of relationship is 1. Or in other words, in a relation
only one entity set is participating then such type of relationship is known as a
unary relationship.

Example:

 In a particular class, we have many students, there are monitors too. So, here class
monitors are also students. Thus, we can say that only students are participating
here.

 So the degree of such type of relationship is 1.

2)Binary (degree 2)

 In a Binary relationship, there are two types of entity associates. So, we can say
that a Binary relationship exists when there are two types of entity and we call
them a degree of relationship is 2.

 Or in other words, in a relation when two entity sets are participating then such
type of relationship is known as a binary relationship.

 This is the most used relationship and one can easily be converted into a relational
table.
CE, PIET-DS 48
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

Example:

 We have two entity types ‘Student’ and ‘ID’ where each ‘Student’ has his ‘ID’.
So, here two entity types are associating we can say it is a binary relationship.

 Also, one ‘Student’ can have many ‘daughters’ but each ‘daughter’ should belong
to only one ‘father. We can say that it is a one-to-many binary relationship.

3)Ternary(degree 3)

 In the Ternary relationship, there are three types of entity associates. So, we can
say that a Ternary relationship exists when there are three types of entity and we
call them a degree of relationship is 3.

 Since the number of entities increases due to this, it becomes very complex to turn
E-R into a relational table. Now let’s understand with the examples.

Example:

 We have three entity types ‘Teacher’, ‘Course’, and ‘Class’. The relationship
between these entities is defined as the teacher teaching a particular course, also
the teacher teaches a particular class.

 So, here three entity types are associating we can say it is a ternary relationship.

4)N-ARY (n degree)
CE, PIET-DS 49
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

 In the N-ary relationship, there are n types of entity that associates. So, we can say
that an N-ary relationship exists when there are n types of entities.

 There is one limitation of the N-ary relationship, as there are many entities so it is
very hard to convert into an entity, rational table.

 So, this is very uncommon, unlike binary which is very much popular.

Example:

 We have 5 entities Teacher, Class, Location, Salary, Course. So, here five entity
types are associating we can say an n-ary relationship is 5.

CE, PIET-DS 50
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

Q.4 Explain mapping cardinality with example. [MARK-4]


A mapping cardinality is a data constraint that specifies how many entities an entity can
be related to in a relationship set.

Example:

Each customer can purchase as many kinds of flyrods as they want (a constraint on
Purchased), but can have only one favorite flyrod/fly combination (a constraint on Fave-
Combo).

A binary relationship set is a relationship set on two entity sets. Mapping cardinalities on
binary relationship sets are simplest.

Consider a binary relationship set R on entity sets A and B. There are four possible
mapping cardinalities in this case:

1) One-to-one:

An entity in A is related to at most one entity in B, and an entity in B is related to at most


one entity in A.

2) One-to-many:

an entity in A is related to any number of entities in B, but an entity in B is related to at


most one entity in A.
CE, PIET-DS 51
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

3) Many-to-one:

An entity in A is related to at most one entity in B, but an entity in B is related to any


number of entities in A

4) Many-to-many:

An entity in A is related to any number of entities in B, but an entity in B is related to


any number of entities in A.

Q.5 Explain ER Diagram representation of Entity and Attributes.


 An Entity–relationship model (ER model) describes the structure of a database
with the help of a diagram, which is known as Entity Relationship Diagram (ER
Diagram).

CE, PIET-DS 52
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

 An ER model is a design or blueprint of a database that can later be implemented


as a database. The main components of E-R model are: entity set and relationship
set.

Attribute

 An attribute describes the property of an entity. An attribute is represented as


Oval in an ER diagram. There are four types of attributes:

1.Key attribute
2. Composite attribute
3. Multivalued attribute
4. Derived attribute

1. Key attribute:

 A key attribute can uniquely identify an entity from an entity set.

 For example, student roll number can uniquely identify a student from a set of
students. Key attribute is represented by oval same as other attributes however,
the text of key attribute is underlined.

2. Composite attribute:

CE, PIET-DS 53
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

 An attribute that is a combination of other attributes is known as composite


attribute.

 For example, In student entity, the student address is a composite attribute as an


address is composed of other attributes such as pin code, state, country.

3. Multivalued attribute:

 An attribute that can hold multiple values is known as multivalued attribute. It is


represented with double ovals in an ER Diagram.

 For example – A person can have more than one phone numbers so the phone
number attribute is multivalued.

4. Derived attribute:

 A derived attribute is one whose value is dynamic and derived from another
attribute.

 It is represented by dashed oval in an ER Diagram. For example – Person age is a


derived attribute as it changes over time and can be derived from another attribute
(Date of birth).

E-R diagram with multivalued and derived attributes:

CE, PIET-DS 54
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

Q.6 Draw ER diagram for Hospital Management

CE, PIET-DS 55
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

Q.7 Draw an ER Diagram for Library Management System.

CE, PIET-DS 56
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

Q.8 Explain Enhanced ER Diagram with example.

 It is getting harder and harder to apply the conventional ER paradigm for database
modeling as data complexity rises today.

 The existing ER model needs to be enhanced or improved in order for it to better


handle the complicated application in order to reduce the modeling complexity.

 The requirements and complexity of complicated databases are represented using


enhanced entity-relationship diagrams, which are sophisticated database diagrams
very similar to standard ER diagrams.

 The SubClass and SuperClass, Specialization and Generalization, Union or


Category, Aggregation, etc., are displayed using this diagrammatic style.

Generalization and Specialization

 These are two normal kinds of relationships that were added to the normal ER
model for enhancement.
 These are inspired by the object-oriented paradigm, where we divide the code into
classes and objects, and in the same way, we have divided entities into subclass
and superclasses.
 Specialized classes are called subclasses, and generalized classes are called
superclasses or base classes.
 We can learn the concept of subclass by 'IS-A' analysis. For example, 'Laptop IS-
A computer.' Or 'Clerk IS-A employee.'
 In this relationship, one entity is a subclass or superclass of another entity. For
example, in a university, a faculty member or clerk is a specialized class of
employees. So an employee is a generalized class, and all others are its subclass.
 We can draw the ER diagram for these relationships. Let's suppose we have a
superclass Employee and subclasses as a clerk, engineer, and lab assistant.

CE, PIET-DS 57
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

The Enhanced ER diagram of the above example will look like this:

In the above example, we have one superclass and three subclasses. Each subclass
inherits all the attributes from its superclass so that a lab assistant will have all its
attributes, like its name, salary, etc.

CE, PIET-DS 58
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

Unit – 5- Functional Dependency & Normalization


Q.1 Explain Normalization for relational database. [MARK-4]
 Normalization is the process of organizing the data in the database.

 Normalization is used to minimize the redundancy from a relation or set of


relations. It is also used to eliminate undesirable characteristics like Insertion,
Update, and Deletion Anomalies.

 Normalization divides the larger table into smaller and links them using

relationships.

 The normal form is used to reduce redundancy from the database table.

There are several levels of normalization, referred to as normal forms. The most
commonly used normal forms are first normal form (1NF), second normal form
(2NF), and third normal form (3NF).

1NF requires that each column in a table contain atomic values, meaning that the
data in each column cannot be further broken down into smaller pieces.

2NF builds on 1NF by requiring that each non-key column be functionally


dependent on the table's primary key. This means that every column in a table that
is not part of the primary key must be dependent on the entire key and not just part
of it.

3NF goes further by requiring that every non-key column be dependent only on the
primary key, and not on any other non-key column. This helps to eliminate
transitive dependencies, where the value of one non-key column is dependent on
another non-key column.

Normalization ensures that a database is designed in a way that reduces redundancy


and improves data integrity, making it easier to maintain and update the database
over time.

CE, PIET-DS 59
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

Q.2 Explain various normal forms of DBMS. [MARK-4]


 Normalization works through a series of stages called Normal forms.

The normal forms apply to individual relations.

Following are the various types of Normal forms:

Normal Form Description

All columns in a table contain atomic values and have


First Normal Form (1NF) unique names.

All non-key attributes are functionally dependent on the


Second Normal Form (2NF) primary key and not on a subset of the key.

All non-key attributes are not transitively dependent on


Third Normal Form (3NF) the primary key.

Fourth Normal Form (4NF) There should be no multi-valued dependencies in a table.

There should be no lossless join dependencies between


Fifth Normal Form (5NF) two or more tables.

All constraints on a table are based on domains (sets of


Domain/Key Normal Form values), and all constraints that do not depend on the key
(DK/NF) are removed.

Q.3 Explain Functional Dependency in DBMS. [MARK-5]


 The functional dependency is a relationship that exists between two attributes. It
typically exists between the primary key and non-key attribute within a table.

1. X  Y

 The left side of FD is known as a determinant, the right side of the production is
known as a dependent.

CE, PIET-DS 60
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

For Example:

 Assume we have an employee table with attributes: Emp_Id, Emp_Name,


Emp_Address.

 Here Emp_Id attribute can uniquely identify the Emp_Name attribute of employee
table because if we know the Emp_Id, we can tell that employee name associated
with it.

 Functional dependency can be written as:

1. Emp_Id → Emp_Name

 We can say that Emp_Name is functionally dependent on Emp_Id.

Types of Functional Dependency

1. Trivial functional dependency

 A → B has trivial functional dependency if B is a subset of A.

 The following dependencies are also trivial like: A → A, B → B

Example:

1. Consider a table with two columns Employee_Id and Employee_Name.

2. {Employee_id, Employee_Name} → Employee_Id is a trivial functional


dependency as

3. Employee_Id is a subset of {Employee_Id, Employee_Name}.

CE, PIET-DS 61
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

4. Also, Employee_Id → Employee_Id and Employee_Name →


Employee_Name are trivial dependencies too.

2. Non-trivial functional dependency

 A → B has a non-trivial functional dependency if B is not a subset of A.

 When A intersection B is NULL, then A → B is called as complete non-trivial.

Example:

1. ID → Name,

2. Name → DOB

Q.4 List and explain various Inference Rules. [MARK-5]


Inference Rule (IR):

 The Armstrong's axioms are the basic inference rule.

 Armstrong's axioms are used to conclude functional dependencies on a relational


database.

 The inference rule is a type of assertion. It can apply to a set of FD(functional


dependency) to derive other FD.

 Using the inference rule, we can derive additional functional dependency from the
initial set.

The Functional dependency has 6 types of inference rule:

1. Reflexive Rule (IR1)

In the reflexive rule, if Y is a subset of X, then X determines Y.

If X ⊇ Y then X → Y

Example:

1. X = {a, b, c, d, e}

2. Y = {a, b, c}

2. Augmentation Rule (IR2)


CE, PIET-DS 62
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

The augmentation is also called as a partial dependency. In augmentation, if X


determines Y, then XZ determines YZ for any Z.

1. If X → Y then XZ → YZ

Example:

1. For R(ABCD), if A → B then AC → BC

3. Transitive Rule (IR3)

In the transitive rule, if X determines Y and Y determine Z, then X must also determine
Z.

1. If X → Y and Y → Z then X → Z

4. Union Rule (IR4)

Union rule says, if X determines Y and X determines Z, then X must also determine
Y and Z.

1. If X → Y and X → Z then X → YZ

Proof:

1. X → Y (given)

2. X → Z (given)

3. X → XY (using IR2 on 1 by augmentation with X. Where XX = X)

4. XY → YZ (using IR2 on 2 by augmentation with Y)

5. X → YZ (using IR3 on 3 and 4)

5. Decomposition Rule (IR5)

Decomposition rule is also known as project rule. It is the reverse of union rule.

This Rule says, if X determines Y and Z, then X determines Y and X

determines Z separately.

1. If X → YZ then X → Y and X → Z

Proof:
CE, PIET-DS 63
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

1. X → YZ (given)

2. YZ → Y (using IR1 Rule)

3. X → Y (using IR3 on 1 and 2)

6. Pseudo transitive Rule (IR6)

In Pseudo transitive Rule, if X determines Y and YZ determines W, then XZ


determines W.

Q.5 What is Normalization? Explain 1NF and 2NF with example.


[MARK-4]
 Normalization is the process of organizing the data in the database.

 Normalization divides the larger table into smaller and links them using
relationships.

 The normal form is used to reduce redundancy from the database table.

First Normal Form (1NF)

 A relation will be 1NF if it contains an atomic value.

 It states that an attribute of a table cannot hold multiple values.

 It must hold only single-valued attribute.

 First normal form disallows the multi-valued attribute, composite attribute, and
their combinations.

Employee Table:

 Relation EMPLOYEE is not in 1NF because of multi-valued attribute


EMP_PHONE.

EMP_ID EMP_NAME EMP_PHONE

CE, PIET-DS 64
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

14 John 7272826385,
9064738238

20 Harry 8574783832

The decomposition of the EMPLOYEE table into 1NF has been shown below:

EMP_ID EMP_NAME EMP_PHONE

14 John 7272826385

14 John 9064738238

20 Harry 8574783832

Second Normal Form (2NF)

 In the 2NF, relational must be in 1NF.

 In the second normal form, all non-key attributes are fully functional dependent on
the primary key

Example: Let us assume, a school can store the data of teachers and the subjects
they teach. In a school, a teacher can teach more than one subject.

Teacher Table:

 In the given table, non-primary attribute TEACHER_AGE is dependent on


TEACHER_ID, which is a proper subset of a candidate key. That is why it violates
the rule for 2NF.

TEACHER_ID SUBJECT TEACHER_AGE

25 Chemistry 30
25 Biology 30
47 English 35
83 Math 38
83 Computer 38
CE, PIET-DS 65
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

 To convert the given table into 2NF, we decompose it into two tables:

TEACHER_DETAIL table:

TEACHER_ID TEACHER_AGE

25 30
47 35
83 38

Q.6 Explain 3NF and 4NF with example. [MARK-4]


Third Normal Form (3NF)

 The first condition for the table to be in Third Normal Form is that the table should
be in the Second Normal Form.

 The second condition is that there should be no transitive dependency for non-
prime attributes, which indicates that non-prime attributes (which are not a part of
the candidate key) should not depend on other non-prime attributes in a table.

 Therefore, a transitive dependency is a functional dependency in which A → C (A


determines C) indirectly, because of A → B and B → C.

 Below is a student table that has student id, student name, subject id, subject name,
and address of the student as its columns.

 In the above student table, stu_id determines subid, and subid determines sub.

 Therefore, stu_id determines sub via subid. This implies that the table possesses a
transitive functional dependency, and it does not fulfill the third normal form
criteria.

CE, PIET-DS 66
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

 Now to change the table to the third normal form, you need to divide the table as
shown below:

 In the first table, columns name, subid, and addresses only depend on stu_id.

 In the second table, the sub only depends on subid.

Fourth Normal Form (4NF)

 A relation will be in 4NF if it is in Boyce Codd normal form and has no multi-
valued dependency.

 For a dependency A → B, if for a single value of A, multiple values of B exists,


then the relation will be a multi-valued dependency.

Example:

 The given STUDENT table is in 3NF, but the COURSE and HOBBY are two
independent entity. Hence, there is no relationship between COURSE and
HOBBY.

 In the STUDENT relation, a student with STU_ID, 21 contains two


courses, Computer and Math and two hobbies, Dancing and Singing. So there is a
Multi-valued dependency on STU_ID, which leads to unnecessary repetition of
data.

CE, PIET-DS 67
INTRODUCTION TO DATABASE MANAGEMENT SYSTEM(DBMS) (03606207)

STUDENT table:

 So to make above table into 4NF, we can decompose into two tables:

STU_ID COURSE HOBBY

21 Computer Dancing
21 Math Singing
34 Chemistry Dancing
74 Biology Cricket
59 Physics Hockey

STUDENT_COURSE table:

STU_ID COURSE

21 Computer
21 Math
34 Chemistry
74 Biology
59 Physics

STUDENT_HOBBY table:

STU_ID HOBBY

21 Dancing
21 Singing
34 Dancing
74 Cricket
59 Hockey

CE, PIET-DS 68

You might also like