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

DBMS-Question and Answer Bank - SOCET-CE-Department - 211127 - 223259

The document discusses database management systems and includes questions and answers about key concepts. It provides a 3-level architecture of DBMS including the external, conceptual, and internal levels. It also defines the role of a database administrator (DBA) who is responsible for controlling, maintaining, and operating the database management system. Common DBMS languages are explained with examples including data definition language (DDL) for creating and modifying database structures, data manipulation language (DML) for manipulating data, and data control language (DCL) for controlling access to data.

Uploaded by

Dhruv Shah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
208 views

DBMS-Question and Answer Bank - SOCET-CE-Department - 211127 - 223259

The document discusses database management systems and includes questions and answers about key concepts. It provides a 3-level architecture of DBMS including the external, conceptual, and internal levels. It also defines the role of a database administrator (DBA) who is responsible for controlling, maintaining, and operating the database management system. Common DBMS languages are explained with examples including data definition language (DDL) for creating and modifying database structures, data manipulation language (DML) for manipulating data, and data control language (DCL) for controlling access to data.

Uploaded by

Dhruv Shah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

SILVER OAK UNIVERSITY

SILVER COLLEGE OF ENGINEERING AND TECHNOLOGY

COMPUTER ENGINEERING DEPARTMENT


B.E 3rd SEMESTER
DATABASE MANAGEMENT SYSTEM (1010043217)- Question bank

SR.NO and
Questions
ANSWERS Unit
No.

1
Compare Basis File System DBMS
Traditional
File File system is a software
processing that manages and
system and organizes the files in a DBMS is a software
database storage medium within a for managing the
management 1. Structure computer. database.
system.
2. Data Redundant data can be In DBMS there is no
Redundancy present in a file system. redundant data.

It doesn’t provide It provides backup 1


3.Backup and backup and recovery of and recovery of data
Recovery data if it is lost. even if it is lost.

There is no efficient Efficient query


4. Query query processing in file processing is there
processing system. in DBMS.

There is more data


There is less data consistency because
consistency in file of the process of
5.Consistency system. normalization.

It has more
complexity in
handling as
It is less complex as compared to file
6. Complexity compared to DBMS. system.
This architecture has three levels:
1. External level
2. Conceptual level
3. Internal level

1. External level

It is also called view level. The reason this level is called “view” is because several users can view
their desired data from this level which is internally fetched from database with the help of
conceptual and internal level mapping.

The user doesn’t need to know the database schema details such as data structure, table definition
etc. user is only concerned about data which is what returned back to the view level after it has been
fetched from database (present at the internal level).

External level is the “top level” of the Three Level DBMS Architecture.

2. Conceptual level

It is also called logical level. The whole design of the database such as relationship among data,
schema of data etc. are described in this level.
2.
Draw and Database constraints and security are also implemented in this level of architecture. This level is
explain maintained by DBA (database administrator).
1
three level
architecture 3. Internal level
of DBMS This level is also known as physical level. This level describes how the data is actually stored in the
storage devices. This level is also responsible for allocating space to the data. This is the lowest
level of the architecture.
A Database Administrator (DBA) is individual or person
responsible for controlling, maintenance, coordinating, and operation
of database management system. Managing, securing, and taking
care of database system is prime responsibility.
They are responsible and in charge for authorizing access to
database, coordinating, capacity, planning, installation, and
monitoring uses and for acquiring and gathering software and
hardware resources as and when needed. Their role also varies from
configuration, database design, migration, security, troubleshooting,
backup, and data recovery. Database administration is major and
key function in any firm or organization that is relying on one or more
databases. They are overall commander of Database system.
Role and Duties of Database Administrator (DBA) :
• Decides hardware –
They decides economical hardware, based upon cost,
performance and efficiency of hardware, and best suits
organisation. It is hardware which is interface between end
users and database.
• Manages data integrity and security –
3 Data integrity need to be checked and managed accurately
Who is DBA? as it protects and restricts data from unauthorized use. DBA
Discuss the eyes on relationship within data to maintain data integrity.
role of • Database design – 1
Database DBA is held responsible and accountable for logical,
Administrator physical design, external model design, and integrity and
(DBA) security control.
• Database implementation –
DBA implements DBMS and checks database loading at
time of its implementation.
• Query processing performance –
DBA enhances query processing by improving their speed,
performance and accuracy.
• Tuning Database Performance –
If user is not able to get data speedily and accurately then it
may loss organization business. So by tuning SQL
commands DBA can enhance performance of database.
There are mainly 3 levels of data abstraction:
Physical: This is the lowest level of data abstraction. It tells us how
the data is actually stored in memory. The access methods like
sequential or random access and file organization methods like B+
trees, hashing used for the same. Usability, size of memory, and the
number of times the records are factors that we need to know while
designing the database.
Suppose we need to store the details of an employee. Blocks of
storage and the amount of memory used for these purposes are kept
hidden from the user.
Logical: This level comprises the information that is actually stored
in the database in the form of tables. It also stores the relationship
among the data entities in relatively simple structures. At this level,
the information available to the user at the view level is unknown.
We can store the various attributes of an employee and
relationships, e.g. with the manager can also be stored.

View: This is the highest level of abstraction. Only a part of the


4 actual database is viewed by the users. This level exists to ease the
Explain accessibility of the database by an individual user. Users view data
different levels in the form of rows and columns. Tables and relations are used to 1
of data store data. Multiple views of the same database may exist. Users
abstraction
can just view the data and interact with the database, storage and
implementation details are hidden from them.
1. Data Definition Language (DDL)
o DDL changes the structure of the table like creating a table, deleting a table, altering a table, etc.

o All the command of DDL are auto-committed that means it permanently save all the changes in the

database.

Here are some commands that come under DDL:

o CREATE

o ALTER

o DROP

o TRUNCATE

a. CREATE It is used to create a new table in the database.

1. Syntax:

CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);


5
Example:
Explain
the DBMS
1. CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(10
languages
with 0), DOB DATE); 1

examples:
b. DROP: It is used to delete both the structure and record stored in the table.
DDL, DML,
and DCL
Syntax

1. DROP TABLE table_name;

Example

1. DROP TABLE EMPLOYEE;

c. ALTER: It is used to alter the structure of the database. This change could
be either to modify the characteristics of an existing attribute or probably to
add a new attribute.

Syntax:

To add a new column in the table

1. ALTER TABLE table_name ADD column_name COLUMN-definition;


1. ALTER TABLE table_name MODIFY(column_definitions....);
d. TRUNCATE: It is used to delete all the rows from the table and free the
space containing the table.

Syntax:

1. TRUNCATE TABLE table_name;

Example:

1. TRUNCATE TABLE EMPLOYEE;


2. Data Manipulation Language
o DML commands are used to modify the database. It is responsible for all
form of changes in the database.
o The command of DML is not auto-committed that means it can't
permanently save all the changes in the database. They can be rollback.

Here are some commands that come under DML:

o INSERT
o UPDATE
o DELETE

a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the
row of a table.

Syntax:

1. INSERT INTO TABLE_NAME


2. (col1, col2, col3,.... col N)
3. VALUES (value1, value2, value3, .... valueN);

Or

1. INSERT INTO TABLE_NAME


2. VALUES (value1, value2, value3, .... valueN);

For example:

1. INSERT INTO javatpoint (Author, Subject) VALUES ("Sonoo", "DBMS");

b. UPDATE: This command is used to update or modify the value of a column


Syntax:

1. UPDATE table_name SET [column_name1= value1,...column_nameN =


valueN] [WHERE CONDITION]

For example:

1. UPDATE students
2. SET User_Name = 'Sonoo'
3. WHERE Student_Id = '3'

c. DELETE: It is used to remove one or more row from a table.

Syntax:

1. DELETE FROM table_name [WHERE condition];

For example:

1. DELETE FROM javatpoint


2. WHERE Author="Sonoo";
3. Data Control Language
DCL commands are used to grant and take back authority from any database
user.

Here are some commands that come under DCL:

o Grant
o Revoke

a. Grant: It is used to give user access privileges to a database.

Example

1. GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_US


ER;

b. Revoke: It is used to take back permissions from the user.

Example

1. REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;


Mapping cardinalities defines the relationship between numbers of entities
in one entity set with the number of entities to other entity sets.

One-to-one
As its name implies, it maps one entity of the first entity set with another one
in the second one entity set. In the below image this has depicted that one
entity from entity set A is associated with at most one entity of other one
entity set B.

For example - a customer has only one ID.

6.
List various
mapping If a single instance of an entity is connected with one instances of another 2
cardinalities entity, then it is called a relationship between one and many.
of

One-to-many
E-R Diagram

An entity from set A can be aligned with more than one entity from set B,
but an entity from set B can be associated with a limit of one entity.
For example - a customer may place many orders, but many customers do not place
an order.

If a single instance of an entity is connected to more than one instances of another


entity, then it is called a relationship between one and many.

Many-to-one
More than one entity from set A could be paired with a maximum of one entity from
set B, but more than one entity from set B can be paired with a maximum of one
entity from set A.

For example – many customers may place 1 order.


Many-to-many
It is possible to connect one entity from set A with more than one entity from
set B and vice versa.

For example – many customers may place many orders.

If more than one instance of the first entity is connected with more than one
instance of the second entity, it is called a many to many relationships.
An Entity Relationship (ER) Diagram is a type of flowchart that illustrates how
“entities” such as people, objects or concepts relate to each other within a system

Generalization

Generalization is a bottom-up approach in which two lower


level entities combine to form a higher level entity. In
generalization, the higher level entity can also combine with
other lower level entities to make further higher level entity.

It's more like Superclass and Subclass system, but the only
7. difference is the approach, which is bottom-up. Hence, entities
Define E-R are combined to form a more generalised entity, in other words,
diagram.
Discuss sub-classes are combined to form a super-class.
generalization,
specialization,
With E-R
diagram

For example, Saving and Current account types entities can be


generalised and an entity with name Account can be created,
which covers both.

Specialization

Specialization is opposite to Generalization. It is a top-down


approach in which one higher level entity can be broken down
into two lower level entity. In specialization, a higher level entity
may not have any lower-level entity sets, it's possible.
Railway Reservation System
8. Enlist The database is required to keep record of ticket booking, train departure, and arrival
status. Also if trains get late then people get to know it through database updates.
Applicati
ons of Library Management System
There are thousands of books in the library so it is very difficult to keep record of all
DBMS the books in a copy or register. So DBMS is used to maintain all the information related
to book issuing dates, name of the book, author, and availability of the book.
Also See: Role, Duties, and Responsibilities of DBA
1
Banking
We make thousands of transactions through banks daily and we can do this without
going to the bank. So how banking has become so easy that by sitting at home we can
send or get money through banks. That is all possible just because of DBMS that
manages all the bank transactions.

Universities and colleges


Examinations are done online today and universities and colleges maintain all these
records through DBMS. Student’s registrations details, results, courses, and grades all
the information are stored in the database.

Credit card transactions


For purchase of credit cards and all the other transactions are made possible only by
DBMS. A credit cardholder knows the importance of their information that all are
secured through DBMS.
Advantage of DBMS
1. Improved data sharing:
• The DBMS helps create an environment in which end users have better access to more and
better-managed data.
• Such access makes it possible for end users to respond quickly to changes in their
environment.

2. Improved data security:


• The more users access the data, the greater the risks of data security
breaches.Corporations invest considerable amounts of time, effort, and money to ensure
that corporate data are used properly.
• A DBMS provides a framework for better enforcement of data privacy and security policies.

3. Better data integration:


9.
Explain pros • Wider access to well-managed data promotes an integrated view of the organization’s
and cons of operations and a clearer view of the big picture.
DBMS • It becomes much easier to see how actions in one segment of the company affect other 11
segments.

4. Minimized data inconsistency:


• Data inconsistency exists when different versions of the same data appear in different
places.
• For example, data inconsistency exists when a company’s sales department stores a sales
representative’s name as “Bill Brown” and the company’s personnel department stores
that same person’s name as “William G. Brown,” or when the company’s regional sales
office shows the price of a product as $45.95 and its national sales office shows the same
product’s price as $43.95.
• The probability of data inconsistency is greatly reduced in a properly designed database.
Disadvantage of DBMS
1. Increased costs:
• Database systems require sophisticated hardware and software and highly skilled
personnel.
• The cost of maintaining the hardware, software, and personnel required to operate and
manage a database system can be substantial. Training, licensing, and regulation
compliance costs are often overlooked when database systems are implemented.

2. Management complexity:
• Database systems interface with many different technologies and have a significant impact
on a company’s resources and culture.
• The changes introduced by the adoption of a database system must be properly managed
to ensure that they help advance the company’s objectives. Given the fact that database
systems hold crucial company data that are accessed from multiple sources, security
issues must be assessed constantly.

3. Maintaining currency:
• To maximize the efficiency of the database system, you must keep your system current.
• Therefore, you must perform frequent updates and apply the latest patches and security
measures to all components.
• Because database technology advances rapidly, personnel training costs tend to be
significant. Vendor dependence.
• Given the heavy investment in technology and personnel training, companies might be
reluctant to change database vendors.
1

4. Frequent upgrade/replacement cycles:


• DBMS vendors frequently upgrade their products by adding new functionality. Such new
features often come bundled in new upgrade versions of the software.
• Some of these versions require hardware upgrades. Not only do the upgrades themselves
cost money, but it also costs money to train database users and administrators to properly
use and manage the new features.
Primary Key
A primary key constrain is a column or group of columns that uniquely
identifies every row in the table of the relational database management
system. It cannot be a duplicate, meaning the same value should not
appear more than once in the table.

A table can have more than one primary key. Primary key can be defined at
the column or the table level. If you create a composite primary key, it
should be defined at the table level.

Foreign Key
Foreign key is a column that creates a relationship between two tables.
The purpose of the Foreign key is to maintain data integrity and allow
10.
Define navigation between two different instances of an entity. It acts as a cross-
Primary Key, reference between two tables as it references the primary key of another
Foreign Key, table. Every relationship in the database should be supported by a foreign
NOT NULL
constraints key.
and referential 2
NOT NULL Constraint in SQL
constraints

By default, the columns are able to hold NULL values. A NOT NULL constraint in SQL is
used to prevent inserting NULL values into the specified column, considering it as a not
accepted value for that column. This means that you should provide a valid SQL NOT NULL
value to that column in the INSERT or UPDATE statements, as the column will always
contain data.

Referential Constraints

Referential constraints are optional and can be defined in CREATE TABLE


statements and ALTER TABLE statements. Referential constraints are
enforced by the database manager during the execution of INSERT, UPDATE,
and DELETE statements. The enforcement is effectively performed at the
completion of the statement except for delete and update rules of RESTRICT
which are enforced as rows are processed.
11.
Draw an E-R
diagram of
Library
Management
System
2
Primary Key
A primary key constrain is a column or group of columns that uniquely
identifies every row in the table of the relational database management
system. It cannot be a duplicate, meaning the same value should not
appear more than once in the table.

A table can have more than one primary key. Primary key can be defined
at the column or the table level. If you create a composite primary key, it
12.
Define the
should be defined at the table level.
terms
(i) Primary
key
Foreign Key
(ii) Second
ary key Foreign key is a column that creates a relationship between two tables.
(iii) Foreign The purpose of the Foreign key is to maintain data integrity and allow
key
navigation between two different instances of an entity. It acts as a
cross-reference between two tables as it references the primary key of
another table. Every relationship in the database should be supported by
a foreign key.
2

Secondary Key
Secondary Key is the key that has not been selected to be the primary key.
However, it is considered a candidate key for the primary key.
Therefore, a candidate key not selected as a primary key is called secondary
key. Candidate key is an attribute or set of attributes that you can consider as
a Primary key.
Network model
This is an extension of the hierarchical model, allowing many-to-many
13
Explain relationships in a tree-like structure that allows multiple parents
network
model and
Object
Oriented
model in brief

Object-Oriented Model
• This data model is another method of representing real
world objects.
• It considers in the world as objects and isolates it from
2
each other
• It groups its related functionalities together and allows
inheriting its functionalities to other related sub-groups.
14.
List the relational algebra operators. Discuss any one such algebra operator
with suitable example
• Relational algebra is a language for expressing relational database
queries.
• Relational algebra is a procedural query language.
• Relational algebraic operators are as follows:
1. Selection
2. Projection
3. Division
4. Cartesian product
5. Rename
6. Set difference
7. Join and its types
❖ Selection:-
• Operation: selects tuples from a relation that satisfy a
given condition. It is used to select particular tuples from a
relation. It selects particular tuples but all attributes from a
relation
• Symbol : sigma
• Notation: sigmacondition<relation>
• Operators : the following operators can be used in a
condition.
=,!=,<,>,<=,>=,^(AND), V(OR)
• Consider the following table
RNO NAME DEPT CPI
101 DHWIJA CC 10
102 HARSH CS 10
103 JAYRAJ CS 10
104 HETVI MLAI 10
105 SHIVAM CS 10
106 BHAVESH CC 10
107 MEENAKSHI B.SC 10

• EXAMPLE: Find out all the students of CE


department.
SigmaDEPT=”CS”(student)
• Output: the above query returns all tuples
which contain CS as department name. output
of above query is as follows:
RNO NAME DEPT CPI
102 HARSH CS 10
103 JAYRAJ CS 10
105 SHIVAM CS 10
15.
EXPLAIN
DDL DML
DIFFERENCE IT STANDS FOR DATA IT STANDS FOR DATA
BETWEEN DDL AND
DML DEFINITION LANGUAGE MANIPULATION LANGUAGE
IT IS USED TO CREATE IT IS USED TO ADD,
DATABASE SCHEMA AND RETRIEVE, OR UPDATE THE
CAN BE USED TO DEFINE DATA.
SOME CONSTRAINTS AS
WELL.
IT IS BASICALLY DEFINES THE
IT ADD OT UPDATE THE ROW
COLUMN (ATTRIBUTES) OF OF THE TABLE. THESE ROWS
THE TABLE ARE CALLED TUPLE.
IT DOESN’T HAVE ANY IT IS FURTHER CLASSIFIED
FURTHER CLASSIFICATION INTO PROCEDURAL AND
NON-PROCEDURAL DML
BASIC COMMANDS PRESENT BASIC COMMANDS PRESENT
IN DDL ARE CREATE, DROP, IN DML ARE UPDATE, INSERT,
RENAME, ALTER ETC. DDL MERGE, ETC. WHILE DML
DOESNOT USE WHERE CLAUS USES WHERE CLAUSE IN ITS
IN ITS STATEMENT. STATEMENT.
18.
EXPLAIN DIFFERNCE
BETWEEN DBMS AND
RDBMS DBMS RDBMS
DBMS stores data as file. RDBMS stores data in tabular
form.
Data elements need to Multiple data elements can
access individually. be accessed at the same
time.
No relationship between Data is stored in the form of
data tables which are related to
each other.
Normalization is not present. RDBMS supports distributed
DBMS does not support database.
distributed database
It stores data in either a It uses a tabular structure
navigational or hierarchical where the headers are the
form. column names, and the rows
contain corresponding
values.
It deals with small quantity of It deals with large amount of
data. data
Data redundancy is common Keys and indexes do not
in this model allow data redundancy.
It is used for small It is used to handle large
organization and deal with amount of data
small data
It supports single user. It supports multiple users.
Data fetching is slower for Data fetching is fast because
the large amount of data. of relational approach
The data in DBMS is subject There exists multiple levels of
to low security levels with data security in a RDBMS.
regards to data manipulation.
Low software and hardware Higher software and
necessities. hardware necessities
Examples: XML, WINDOW Examples: MySQL, SQL,
REGISTRY ETC. Oracle etc
16.
Draw an E-R
diagram of
hospital
management
system
Types of Join statements
The type of join statement you use depends on your use case. There
are four different types of join operations:

• (INNER) JOIN: Returns dataset that have matching values


in both tables
• LEFT (OUTER) JOIN: Returns all records from the left table
and matched records from the right s
19. • RIGHT (OUTER) JOIN: Returns all records from the right
Explain all types table and the matched records from the left
of join in detail • FULL (OUTER) JOIN: Returns all records when there is a
with examples match in either the left table or right table

Inner Joins

If you were to think of each table as a separate circle in a Venn


diagram, the inner join would be the shaded area where both
circles intersect.

The INNER JOIN keyword selects all rows from the tables as long as
a join condition satisfies. This keyword will create a result-set made
up of combined rows from both tables where a common field exists.

Here is the syntax for an inner join:

SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
Right outer Joins

This join statement takes all the records from Table B whether or not
they have NULL values and the matching columns from Table A.

Right join returns all the rows of the rightmost table of and the
matching rows for the leftmost table. RIGHT JOIN is also known as
RIGHT OUTER. Here is the syntax:

SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;

Left outer Joins

Left join is similar to right join. Left join returns all the rows of the
leftmost table and the matching rows for the rightmost table. Below is
the syntax:

SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;

Full Joins

Full joins are also known as full outer joins. This basically means that a
query would combine data and return records from both tables no
matter if they had NULL values.

FULL JOIN creates a result-set by combining the results of the left and
right joins, including all the rows. For the rows that do not match. the
result-set (joined table) will shows NULL values. The syntax is as
follows:

SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
20. LIST THE STEPS FOR CONVERT E-R DIAGRAM INTO
TABLE
o Entity type becomes a table.

In the given ER diagram, LECTURE, STUDENT, SUBJECT and COURSE forms


individual tables.

o All single-valued attribute becomes a column for the table.

In the STUDENT entity, STUDENT_NAME and STUDENT_ID form the column of


STUDENT table. Similarly, COURSE_NAME and COURSE_ID form the column of
COURSE table and so on.

o A key attribute of the entity type represented by the primary key.

In the given ER diagram, COURSE_ID, STUDENT_ID, SUBJECT_ID, and LECTURE_ID


are the key attribute of the entity.

o The multivalued attribute is represented by a separate table.

In the student table, a hobby is a multivalued attribute. So it is not possible to


represent multiple values in a single column of STUDENT table. Hence we create
a table STUD_HOBBY with column name STUDENT_ID and HOBBY. Using both the
column, we create a composite key.

o Composite attribute represented by components.

In the given ER diagram, student address is a composite attribute. It contains CITY,


PIN, DOOR#, STREET, and STATE. In the STUDENT table, these attributes can
merge as an individual column.

o Derived attributes are not considered in the table.

In the STUDENT table, Age is the derived attribute. It can be calculated at any point
of time by calculating the difference between current date and Date of Birth.
21. • Functional Dependency is when one attribute determines another
WHAT IS attribute in a DBMS system.
• Axiom, Decomposition, Dependent, Determinant, Union are key terms
FUNCTIONAL
for functional dependency
DEPENDENCY? • Four types of functional dependency are 1) Multivalued 2) Trivial 3)
EXPLAIN ITS Non-trivial 4) Transitive
TYPES IN DETAIL
Types of Functional Dependencies in DBMS
There are mainly four types of Functional Dependency in DBMS. Following
are the types of Functional Dependencies in DBMS:

• Multivalued Dependency
• Trivial Functional Dependency
• Non-Trivial Functional Dependency
• Transitive Dependency

Multivalued Dependency in DBMS


Multivalued dependency occurs in the situation where there are multiple
independent multivalued attributes in a single table. A multivalued
dependency is a complete constraint between two sets of attributes in a
relation. It requires that certain tuples be present in a relation. Consider the
following Multivalued Dependency Example to understand.

Trivial Functional Dependency in DBMS


The Trivial dependency is a set of attributes which are called a trivial if the
set of attributes are included in that attribute.

So, X -> Y is a trivial functional dependency if Y is a subset of X

Non Trivial Functional Dependency in DBMS


Functional dependency which also known as a nontrivial dependency
occurs when A->B holds true where B is not a subset of A. In a relationship, if
attribute B is not a subset of attribute A, then it is considered as a non-trivial
dependency.
Transitive Dependency in DBMS
A Transitive Dependency is a type of functional dependency which
happens when “t” is indirectly formed by two functional dependencies.

22.
Primary key:
GIVE A BRIEF
ABOUT • A primary key is a special relational database table column (or combination
of columns) designated to uniquely identify all table records.
PRIMARY KEY
• A primary key’s main features are:
AND FOREIGN o It must contain a unique value for each row of data.
KEY o It cannot contain null values.
• A primary key is either an existing table column or a column that is
specifically generated by the database according to a defined sequence.
• For example, students are routinely assigned unique identification (ID)
numbers, and all adults receive government-assigned and uniquely-
identifiable Social Security numbers.

Foreign Key:

• A foreign key is a field (or collection of fields) in one table that uniquely
identifies a row of another table. In simpler words, the foreign key is
defined in a second table, but it refers to the primary key in the first table.
• For example, a table called Employee has a primary key called
employee_id. Another table called Employee Details has a foreign key
which references employee_id in order to uniquely identify the relationship
between both the tables.
• A foreign key is a column or group of columns in a relational database table
that provides a link between data in two tables. It acts as a cross-reference
between tables because it references the primary key of another table,
thereby establishing a link between them.
23.
EXPLAIN THE
CLOUSRE OF
FOLLOWING SET
F OF
FUNCTIONAL
DEPENDENCY
FOR RELATION
SCHEMA
R(A,B,C,D,E).
A->BC,
CD->E,
B->D,
E->A
LIST THE
CANDIDATE S
KEYS FOR R
First Normal Form (1NF):
If a relation contains a composite or multi-valued attribute, it violates
the first normal form, or the relation is in first normal form if it does
not contain any composite or multi-valued attribute. A relation is
in first normal form if every attribute in that relation is singled valued
attribute.
A table is in 1 NF iff:
1. There are only Single Valued Attributes.
2. Attribute Domain does not change.
3. There is a unique name for every Attribute/Column.
4. The order in which data is stored does not matter.

Consider the examples given below.


Example-1:
Relation STUDENT in table 1 is not in 1NF because of multi-valued
attribute STUD_PHONE. Its decomposition into 1NF has been
shown in table 2.
24. In the below table, Course is a multi-valued attribute so it is not in
Explain 1NF, 1NF.
2NF and BCNF
with suitable
example
Example-2:

below Table is in 1NF as there is no multi-valued attribute:

ID Name Course

------------------

1 A c1

1 A c2

2 E c3

3 M c2

3 M c3

Second Normal Form (2NF):


Second Normal Form (2NF) is based on the concept of full functional
dependency. Second Normal Form applies to relations with
composite keys, that is, relations with a primary key composed of
two or more attributes. A relation with a single-attribute primary key
is automatically in at least 2NF. A relation that is not in 2NF may
suffer from the update anomalies.
Consider following functional dependencies in relation R (A, B, C, D )

AB -> C [A and B together determine C]

BC -> D [B and C together determine D]

In the above relation, AB is the only candidate key and there is no partial dependency, i.e.,
any proper subset of AB doesn’t determine any non-prime attribute.

Boyce-Codd Normal Form (BCNF)


NF is adequate normal form for relational database, still, this (3NF)
normal form may not remove 100% redundancy because of X?Y
functional dependency, if X is not a candidate key of given relation.
This can be solve by Boyce-Codd Normal Form (BCNF).
Normalization is the process of minimizing redundancy from a
relation or set of relations. Redundancy in relation may cause
insertion, deletion, and update anomalies. So, it helps to minimize
the redundancy in relations. Normal forms are used to eliminate or
reduce redundancy in database tables.
First Normal Form (1NF):
If a relation contains a composite or multi-valued attribute, it violates
the first normal form, or the relation is in first normal form if it does
not contain any composite or multi-valued attribute. A relation is in
first normal form if every attribute in that relation is singled valued
attribute.
25. A table is in 1 NF iff:
What is 1. There are only Single Valued Attributes.
2. Attribute Domain does not change.
normalization? 3. There is a unique name for every Attribute/Column.
Write its need. 4. The order in which data is stored does not matter.
List and Second Normal Form (2NF):
discuss various Second Normal Form (2NF) is based on the concept of full functional
normalization dependency. Second Normal Form applies to relations with
composite keys, that is, relations with a primary key composed of
forms two or more attributes. A relation with a single-attribute primary key
is automatically in at least 2NF. A relation that is not in 2NF may
suffer from the update anomalies.

3NF (Third Normal Form) Rules


• Rule 1- Be in 2NF
• Rule 2- Has no transitive functional dependencies

To move our 2NF table into 3NF, we again need to again divide our
table.

Boyce-Codd Normal Form (BCNF)


NF is adequate normal form for relational database, still, this (3NF)
normal form may not remove 100% redundancy because of X?Y
functional dependency, if X is not a candidate key of given relation.
This can be solve by Boyce-Codd Normal Form (BCNF).

s
26. Explain armstrong’s axioms
• Armstrong's Axioms is a set of rules.
• It provides a simple technique for reasoning about functional
dependencies.
• It was developed by William W. Armstrong in 1974.
• It is used to infer all the functional dependencies on a relational
database.

Various Axioms Rules


A. Primary Rules

Rule 1 Reflexivity
If A is a set of attributes and B is a subset of A, then A holds B. { A → B }

Rule 2 Augmentation
If A hold B and C is a set of attributes, then AC holds BC. {AC → BC}
It means that attribute in dependencies does not change the basic dependencies.

Rule 3 Transitivity
If A holds B and B holds C, then A holds C.
If {A → B} and {B → C}, then {A → C}
A holds B {A → B} means that A functionally determines B.

B. Secondary Rules

Rule 1 Union
If A holds B and A holds C, then A holds BC.
If{A → B} and {A → C}, then {A → BC}

Rule 2 Decomposition
If A holds BC and A holds B, then A holds C.
If{A → BC} and {A → B}, then {A → C}

Rule 3 Pseudo Transitivity


If A holds B and BC holds D, then AC holds D.
If{A → B} and {BC → D}, then {AC → D}

Sometimes Functional Dependency Sets are not able to reduce if the


set has following properties,
1. The Right-hand side set of functional dependency holds only one
attribute.
2. The Left-hand side set of functional dependency cannot be reduced, it
changes the entire content of the set.
3. Reducing any functional dependency may change the content of the set.

A set of functional dependencies with the above three properties are also
called as Canonical or Minimal.

Trivial Functional Dependency

Trivial If A holds B {A → B}, where A is a subset of B, then it is called a Trivial Funct


Trivial always holds Functional Dependency.

Non-Trivial If A holds B {A → B}, where B is not a subset A, then it is called as a Non-Triv


Dependency.

Completely Non- If A holds B {A → B}, where A intersect Y = Φ, it is called as a Completely No


Trivial Dependency.
When multiple transactions are running concurrently then there is a
possibility that the database may be left in an inconsistent state.
Serializability is a concept that helps us to check which schedules are
serializable. A serializable schedule is the one that always leaves the
database in consistent state.
27.
State true or false. Any relation schema that satisfies BCNF also sati
3NF
ANS: TRUE
28.
EXPLAIN STEPS OF QUERY PROCESSING WITH THE HELP OF NEAT DIAGRA
ANS:
• A given SQL query is translated by the query processor into a low level program called an execution plan
• An execution plan is a program in a functional language
• The physical relational algebra extends the relational algebra with primitives to search through the internal st
structure of DBMS.

Basic Steps in Query Processing

1. Parsing and translation


2. Optimization
3. Evaluation

1. Parsing and translation

• Translate the query into its internal form. This is then translated into relational algebra.
• Parser checks syntax, verifies relation.

2. Optimization

• SQL is a very high level language:


o The users specify what to search for- not how the search is actually done
o The algorithms are chosen automatically by the DBMS.
• For a given SQL query there may be many possible execution plans.
• Amongst all equivalent plans choose the one with lowest cost.
• Cost is estimated using statistical information from the database catalog.

3. Evaluation

• The query evaluation engine takes a query evaluation plan, executes that plan and returns the answer to that
29. WHAT IS A VIEW? EXPLAIN HOW TO CREATE, ITS TYPES AND SIGNIFICANC
DBMS
ANS: Views in SQL
o Views in SQL are considered as a virtual table. A view also contains rows and columns.
o To create the view, we can select the fields from one or more tables present in the database.
o A view can either have specific rows based on certain condition or all the rows of a table.

Sample table:
Student_Detail

STU_ID NAME ADDRESS

1 Stephan Delhi

2 Kathrin Noida

3 David Ghaziabad

4 Alina Gurugram

Student_Marks

STU_ID NAME MARKS AGE


1 Stephan 97 19

2 Kathrin 86 21

3 David 74 18

4 Alina 90 20

5 John 96 18

1. Creating view
A view can be created using the CREATE VIEW statement. We can create a view from a single table or multiple

Syntax:

1. CREATE VIEW view_name AS


2. SELECT column1, column2.....
3. FROM table_name
4. WHERE condition;

2. Creating View from a single table


In this example, we create a View named DetailsView from the table Student_Detail.

Query:

1. CREATE VIEW DetailsView AS


2. SELECT NAME, ADDRESS
3. FROM Student_Details
4. WHERE STU_ID < 4;

Just like table query, we can query the view to view the data.

1. SELECT * FROM DetailsView;

Output:
NAME ADDRESS

Stephan Delhi

Kathrin Noida

David Ghaziabad

3. Creating View from multiple tables


View from multiple tables can be created by simply include multiple tables in the SELECT statement.

In the given example, a view is created named MarksView from two tables Student_Detail and Student_Marks.

Query:

1. CREATE VIEW MarksView AS


2. SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Student_Marks.MARKS
3. FROM Student_Detail, Student_Mark
4. WHERE Student_Detail.NAME = Student_Marks.NAME;

To display data of View MarksView:

1. SELECT * FROM MarksView;

NAME ADDRESS MARKS

Stephan Delhi 97

Kathrin Noida 86

David Ghaziabad 74

Alina Gurugram 90

4. Deleting View
A view can be deleted using the Drop View statement.
Syntax

1. DROP VIEW view_name;

Example:

If we want to delete the View MarksView, we can do this as:

1. DROP VIEW MarksView;

30. EXPLAIN B-TREE AND HASHING


ANS:
Definition − A B-tree of order m is an m-way tree that means a node can have maxm m children.

Properties of B-tree
B-tree satisfies the following properties −

• The number of keys in a node (non leaf node) is one less than the number of its children (and these key
the keys of children like a binary search tree).

• The root has a minimum one key to maximum (m-1) keys. So, root has minimum two children to m
children.

• Any node (non-leaf node) except the root has minm([m/2]-1) to maxm(m-1) keys. So, they have minm [ m/2
to maxm m children.

• All leaf nodes are on the same level.

Example
A B-tree of order 3 (i.e a node can have maxm 3 children) satisfy following properties −

• The root has minimum one key to maximum 2 keys. So root has minimum two children to maximum 3 c

• Any node (non-leaf node) except the root has minm 1 to maxm 2 keys. So, they have minm 2 children
children.
Hashing
In a huge database structure, it is very inefficient to search all the index values and reach the desired data
technique is used to calculate the direct location of a data record on the disk without using index structure.

In this technique, data is stored at the data blocks whose address is generated by using the hashing function. Th
location where these records are stored is known as data bucket or data blocks.

In this, a hash function can choose any of the column value to generate the address. Most of the time, the has
uses the primary key to generate the address of the data block. A hash function is a simple mathematical funct
complex mathematical function. We can even consider the primary key itself as the address of the data block. T
each row whose address will be the same as a primary key stored in the data block.

The above diagram shows data block addresses same as primary key value. This hash function can also b
mathematical function like exponential, mod, cos, sin, etc. Suppose we have mod (5) hash function to dete
address of the data block. In this case, it applies mod (5) hash function on the primary keys and generates 3, 3,
respectively, and records are stored in those data block addresses.
31. EXPLAIN INDICES WITH EXAMPLE
ANS: Indexing is a data structure technique to efficiently retrieve records from the database files based
attributes on which the indexing has been done. Indexing in database systems is similar to what we see in bo
Indexing is defined based on its indexing attributes. Indexing can be of the following types −
• Primary Index − Primary index is defined on an ordered data file. The data file is ordered on a key field
field is generally the primary key of the relation.
• Secondary Index − Secondary index may be generated from a field which is a candidate key and has
value in every record, or a non-key with duplicate values.
• Clustering Index − Clustering index is defined on an ordered data file. The data file is ordered on a non
Ordered Indexing is of two types −

• Dense Index
• Sparse Index

Dense Index
In dense index, there is an index record for every search key value in the database. This makes searching
requires more space to store index records itself. Index records contain search key value and a pointer to
record on the disk.

Sparse Index
In sparse index, index records are not created for every search key. An index record here contains a search k
actual pointer to the data on the disk. To search a record, we first proceed by index record and reach at the actu
of the data. If the data we are looking for is not where we directly reach by following the index, then the sys
sequential search until the desired data is found.
Multilevel Index
Index records comprise search-key values and data pointers. Multilevel index is stored on the disk along with
database files. As the size of the database grows, so does the size of the indices. There is an immense nee
the index records in the main memory so as to speed up the search operations. If single-level index is used, th
size index cannot be kept in memory which leads to multiple disk accesses.

32. LIST AND DISCUSS ACID PROPERTIES OF TRANSACTIONS.

ANS: ACID Properties


The expansion of the term ACID defines for:
1) Atomicity: The term atomicity defines that the data remains atomic. It means if any operation is perform
data, either it should be performed or executed completely or should not be executed at all. It further mean
operation should not break in between or execute partially. In the case of executing operations on the trans
operation should be completely executed and not partially.

14.6M
293
History of Java
Next
Stay

Example: If Remo has account A having $30 in his account from which he wishes to send $10 to Sheero's acco
is B. In account B, a sum of $ 100 is already present. When $10 will be transferred to account B, the sum will bec
Now, there will be two operations that will take place. One is the amount of $10 that Remo wants to trans
debited from his account A, and the same amount will get credited to account B, i.e., into Sheero's account.
happens - the first operation of debit executes successfully, but the credit operation, however, fails. Thus,
account A, the value becomes $20, and to that of Sheero's account, it remains $100 as it was previously presen
In the above diagram, it can be seen that after crediting $10, the amount is still $100 in account B. So, it is not
transaction.

The below image shows that both debit and credit operations are done successfully. Thus the transaction is ato

Thus, when the amount loses atomicity, then in the bank systems, this becomes a huge issue, and so the atom
main focus in the bank systems.
2) Consistency: The word consistency means that the value should remain preserved always. In DBMS, the i
the data should be maintained, which means if a change in the database is made, it should remain preserved
the case of transactions, the integrity of the data is very essential so that the database remains consistent befor
the transaction. The data should always be correct.

Example:

In the above figure, there are three accounts, A, B, and C, where A is making a transaction T one by one to b
There are two operations that take place, i.e., Debit and Credit. Account A firstly debits $50 to account B, and th
in account A is read $300 by B before the transaction. After the successful transaction T, the available amount in B
$150. Now, A debits $20 to account C, and that time, the value read by C is $250 (that is correct as a debit of $5
successfully done to B). The debit and credit operation from account A to C has been done successfully. We ca
the transaction is done successfully, and the value is also read correctly. Thus, the data is consistent. In case the
by B and C is $300, which means that data is inconsistent because when the debit operation executes, it w
consistent.

4) Isolation: The term 'isolation' means separation. In DBMS, Isolation is the property of a database where no d
affect the other one and may occur concurrently. In short, the operation on one database should begin when the
on the first database gets complete. It means if two operations are being performed on two different databases
not affect the value of one another. In the case of transactions, when two or more transactions occur simultan
consistency should remain maintained. Any changes that occur in any particular transaction will not be seen
transactions until the change is not committed in the memory.
Example: If two operations are concurrently running on two different accounts, then the value of both accou
not get affected. The value should remain persistent. As you can see in the below diagram, account A is making
transactions to account B and C, but both are executing independently without affecting each other. It is
Isolation.

4) Durability: Durability ensures the permanency of something. In DBMS, the term durability ensures that the
the successful execution of the operation becomes permanent in the database. The durability of the data sho
perfect that even if the system fails or leads to a crash, the database still survives. However, if gets lost, it be
responsibility of the recovery manager for ensuring the durability of the database. For committing the values, th
command must be used every time we make changes.

Therefore, the ACID property of DBMS plays a vital role in maintaining the consistency and availability of d
database.

33. DEFINE TRANSACTION. EXPLAIN VARIOUS STATES OF TRANSACTION WITH


SUITABLE DIAGRAM.
ANS: Transaction
o The transaction is a set of logically related operation. It contains a group of tasks.
o A transaction is an action or series of actions. It is performed by a single user to perform operations for accessing t
of the database.
States of Transaction
In a database, the transaction can be in one of the following states -

Active state
o The active state is the first state of every transaction. In this state, the transaction is being executed.
o For example: Insertion or deletion or updating a record is done here. But all the records are still not saved to the

Partially committed
o In the partially committed state, a transaction executes its final operation, but the data is still not saved to the da
o In the total mark calculation example, a final display of the total marks step is executed in this state.

Committed
A transaction is said to be in a committed state if it executes all its operations successfully. In this state, all the
now permanently saved on the database system.

Failed state
o If any of the checks made by the database recovery system fails, then the transaction is said to be in the failed sta
o In the example of total mark calculation, if the database is not able to fire a query to fetch the marks, then the tran
fail to execute.

Aborted
o If any of the checks fail and the transaction has reached a failed state then the database recovery system will ma
the database is in its previous consistent state. If not then it will abort or roll back the transaction to bring the da
a consistent state.
o If the transaction fails in the middle of the transaction then before executing the transaction, all the executed tran
rolled back to its consistent state.
o After aborting the transaction, the database recovery module will select one of the two operations:
1. Re-start the transaction
2. Kill the transaction

34. WHAT IS B+ TREE WITH EXAMPLE

ANS: B+ Tree
o The B+ tree is a balanced binary search tree. It follows a multi-level index format.
o In the B+ tree, leaf nodes denote actual data pointers. B+ tree ensures that all leaf nodes remain at the same heig
o In the B+ tree, the leaf nodes are linked using a link list. Therefore, a B+ tree can support random access as well a
access.

Structure of B+ Tree
o In the B+ tree, every leaf node is at equal distance from the root node. The B+ tree is of the order n where n is fix
B+ tree.
o It contains an internal node and leaf node.

Internal node

o An internal node of the B+ tree can contain at least n/2 record pointers except the root node.
o At most, an internal node of the tree contains n pointers.

Leaf node

o The leaf node of the B+ tree can contain at least n/2 record pointers and n/2 key values.
o At most, a leaf node contains n record pointer and n key values.
o Every leaf node of the B+ tree contains one block pointer P to point to next leaf node.

Searching a record in B+ Tree


Suppose we have to search 55 in the below B+ tree structure. First, we will fetch for the intermediary node which
to the leaf node that can contain a record for 55.

So, in the intermediary node, we will find a branch between 50 and 75 nodes. Then at the end, we will be redirec
third leaf node. Here DBMS will perform a sequential search to find 55.

B+ Tree Insertion
Suppose we want to insert a record 60 in the below structure. It will go to the 3rd leaf node after 55. It is a bala
and a leaf node of this tree is already full, so we cannot insert 60 there.

In this case, we have to split the leaf node, so that it can be inserted into tree without affecting the fill factor, b
order.

Keep Watching
Competitive questions on Structures in Hindi
00:00/03:34
Keep Watching
Competitive questions on Structures in Hindi
00:00/03:34
Keep Watching
Competitive questions on Structures in Hindi
Keep Watching
Keep Watching

The 3rd leaf node has the values (50, 55, 60, 65, 70) and its current root node is 50. We will split the leaf node
in the middle so that its balance is not altered. So we can group (50, 55) and (60, 65, 70) into 2 leaf nodes.

If these two has to be leaf nodes, the intermediate node cannot branch from 50. It should have 60 added to it
we can have pointers to a new leaf node.

This is how we can insert an entry when there is overflow. In a normal scenario, it is very easy to find the node w
and then place it in that leaf node.

B+ Tree Deletion
Suppose we want to delete 60 from the above example. In this case, we have to remove 60 from the intermed
as well as from the 4th leaf node too. If we remove it from the intermediate node, then the tree will not satisfy
the B+ tree. So we need to modify it to have a balanced tree.

After deleting node 60 from above B+ tree and re-arranging the nodes, it will show as follows:
35. DEFINE HASHING AND ITS TYPES.

ANS: Hashing
In a huge database structure, it is very inefficient to search all the index values and reach the desired data
technique is used to calculate the direct location of a data record on the disk without using index structure.

In this technique, data is stored at the data blocks whose address is generated by using the hashing function. Th
location where these records are stored is known as data bucket or data blocks.

In this, a hash function can choose any of the column value to generate the address. Most of the time, the has
uses the primary key to generate the address of the data block. A hash function is a simple mathematical funct
complex mathematical function. We can even consider the primary key itself as the address of the data block. T
each row whose address will be the same as a primary key stored in the data block.
The above diagram shows data block addresses same as primary key value. This hash function can also b
mathematical function like exponential, mod, cos, sin, etc. Suppose we have mod (5) hash function to dete
address of the data block. In this case, it applies mod (5) hash function on the primary keys and generates 3, 3,
respectively, and records are stored in those data block addresses.

Skip Ad
Types of Hashing:

Static Hashing
In static hashing, the resultant data bucket address will always be the same. That means if we generate an a
EMP_ID =103 using the hash function mod (5) then it will always result in same bucket address 3. Here, there
change in the bucket address.

Hence in this static hashing, the number of data buckets in memory remains constant throughout. In this examp
have five data buckets in the memory used to store the data.
Dynamic Hashing
o The dynamic hashing method is used to overcome the problems of static hashing like bucket overflow.
o In this method, data buckets grow or shrink as the records increases or decreases. This method is also known as
hashing method.
o This method makes hashing dynamic, i.e., it allows insertion or deletion without resulting in poor performance.

How to search a key


o First, calculate the hash address of the key.
o Check how many bits are used in the directory, and these bits are called as i.
o Take the least significant i bits of the hash address. This gives an index of the directory.
o Now using the index, go to the directory and find bucket address where the record might Be.

36. STATE DIFFERENCES BETWEEN CONFLICT SERIALIZIBILITY AND VIEW SERIALIZABILITY.

ANS:

CONFLICT SERIALIZIBITY VIEW SERIALIZIBITY


Two schedules are said to be conflict equivalent if all the Two schedules are said to be in view equivalent
conflicting operators in both the schedule get executed in
the same order. If a schedule is a conflict equivalent to its If the order of initial read, final write and update
serial schedule then it is called conflict serializable
Operations is the same in both the schedules.
schedule.
If a schedule is view equivalent to its serial sched

Then it is called view serializable schedule.


If a schedule is a view serializable then it may or may not If a schedule is conflict serializable then it is also
be conflict serializable.
View serializable schedule.
Conflict equivalence can be easily achieved by reordering View equivalence is rather difficult to achieve as
the operators of two transactions therefore, conflict
SERIALIZIBITY is easy to achieve. Both transactions should perform similar actions

In a similar manner. Thus, view serializablity is

Difficult to achieve.
For a transaction T1 writing value A that no one else reads If a transaction T1 writes a value A that no other
but later some other transactions say T2 write it own value
of A, W(A) cannot be places under positions where it is Transaction reads W(A) can be placed in position
never read.
Of the schedule where it is never read.

37. Define failure. Write a note on log based recovery.

Ans: Failure Classification


To see where the problem has occurred, we generalize a failure into various categories, as follows −
Transaction failure
A transaction has to abort when it fails to execute or when it reaches a point from where it can’t go any furth
called transaction failure where only a few transactions or processes are hurt.
Reasons for a transaction failure could be −
• Logical errors − Where a transaction cannot complete because it has some code error or any inte
condition.
• System errors − Where the database system itself terminates an active transaction because the DB
able to execute it, or it has to stop because of some system condition. For example, in case of deadlock o
unavailability, the system aborts an active transaction.

Log-Based Recovery
o The log is a sequence of records. Log of each transaction is maintained in some stable storage so that if any fai
then it can be recovered from there.
o If any operation is performed on the database, then it will be recorded in the log.
o But the process of storing the logs should be done before the actual transaction is applied in the database.

Let's assume there is a transaction to modify the City of a student. The following logs are written for this transa

o When the transaction is initiated, then it writes 'start' log.

1. <Tn, Start>
o When the transaction modifies the City from 'Noida' to 'Bangalore', then another log is written to the file.

1. <Tn, City, 'Noida', 'Bangalore' >


o When the transaction is finished, then it writes another log to indicate the end of the transaction.

1. <Tn, Commit>
There are two approaches to modify the database:

1. Deferred database modification:


o The deferred modification technique occurs if the transaction does not modify the database until it has committe
o In this method, all the logs are created and stored in the stable storage, and the database is updated when a
commits.

2. Immediate database modification:


o The Immediate modification technique occurs if database modification occurs while the transaction is still active.
o In this technique, the database is modified immediately after every operation. It follows an actual database modif

Recovery using Log records


When the system is crashed, then the system consults the log to find which transactions need to be undone
need to be redone.

1. If the log contains the record <Ti, Start> and <Ti, Commit> or <Ti, Commit>, then the Transaction Ti needs to be
2. If log contains record<Tn, Start> but does not contain the record either <Ti, commit> or <Ti, abort>, then the Tra
needs to be undone.

38. Explain types of schedule with examples.

Ans: 1. Serial Schedule


The serial schedule is a type of schedule where one transaction is executed completely before starting another tr
In the serial schedule, when the first transaction completes its cycle, then the next transaction is executed.

For example: Suppose there are two transactions T1 and T2 which have some operations. If it has no inter
operations, then there are the following two possible outcomes:

1. Execute all the operations of T1 which was followed by all the operations of T2.
2. Execute all the operations of T1 which was followed by all the operations of T2.

o In the given (a) figure, Schedule A shows the serial schedule where T1 followed by T2.
o In the given (b) figure, Schedule B shows the serial schedule where T2 followed by T1.

2. Non-serial Schedule
o If interleaving of operations is allowed, then there will be non-serial schedule.
o It contains many possible orders in which the system can execute the individual operations of the transa
o In the given figure (c) and (d), Schedule C and Schedule D are the non-serial schedules. It has inter
operations.

3. Serializable schedule
o The serializability of schedules is used to find non-serial schedules that allow the transaction to execute co
without interfering with one another.
o It identifies which schedules are correct when executions of the transaction have interleaving of their op
o A non-serial schedule will be serializable if its result is equal to the result of its transactions executed ser
Here,

Hello Java Program for Beginners

Schedule A and Schedule B are serial schedule.

Schedule C and Schedule D are Non-serial schedule.

39. Explain serializability with methods

ANS: When multiple transactions are running concurrently then there is a possibility that the data
be left in an inconsistent state. Serializability is a concept that helps us to check which sche
serializable. A serializable schedule is the one that always leaves the database in consistent state.

Conflicting operations
Two operations are said to be in conflict, if they satisfy all the following three conditions:

1. Both the operations should belong to different transactions.


2. Both the operations are working on same data item.
3. At least one of the operation is a write operation.
Lets see some examples to understand this:
Example 1: Operation W(X) of transaction T1 and operation R(X) of transaction T2 are conflicting ope
because they satisfy all the three conditions mentioned above. They belong to different transactions,
working on same data item X, one of the operation in write operation.

View Serializability is a process to find out that a given schedule is view serializable or not.

To check whether a given schedule is view serializable, we need to check whether the given schedule
Equivalent to its serial schedule. Lets take an example to understand what I mean by that.

Given Schedule:

T1 T2
----- ------
R(X)
W(X)
R(X)
W(X)
R(Y)
W(Y)
R(Y)
W(Y)
Serial Schedule of the above given schedule:
As we know that in Serial schedule a transaction only starts when the current running transaction is f
So the serial schedule of the above given schedule would look like this:

T1 T2
----- ------
R(X)
W(X)
R(Y)
W(Y)
R(X)
W(X)
R(Y)
W(Y)
If we can prove that the given schedule is View Equivalent to its serial schedule then the given schedu
called view Serializable.

40. Explain Deadlock with examples


Ans: Deadlock in DBMS
A deadlock is a condition where two or more transactions are waiting indefinitely for one another to give
Deadlock is said to be one of the most feared complications in DBMS as no task ever gets finished and is in wa
forever.

For example: In the student table, transaction T1 holds a lock on some rows and needs to update some rows in
table. Simultaneously, transaction T2 holds locks on some rows in the grade table and needs to update the r
Student table held by Transaction T1.

Now, the main problem arises. Now Transaction T1 is waiting for T2 to release its lock and similarly, transa
waiting for T1 to release its lock. All activities come to a halt state and remain at a standstill. It will remain in
until the DBMS detects the deadlock and aborts one of the transactions.

Deadlock Avoidance
o When a database is stuck in a deadlock state, then it is better to avoid the database rather than aborting or re
database. This is a waste of time and resource.
o Deadlock avoidance mechanism is used to detect any deadlock situation in advance. A method like "wait for gra
for detecting the deadlock situation but this method is suitable only for the smaller database. For the large
deadlock prevention method can be used.
41. Explain the concurrency problem. How does the strict two phase

Locking protocol solve three problems concurrency? Explain with

Example

Ans: In a multiprogramming environment where multiple transactions can be executed simultaneously, i


important to control the concurrency of transactions. We have concurrency control protocols to ensure atomicity
and serializability of concurrent transactions. Concurrency control protocols can be broadly divided into two ca

• Lock based protocols


• Time stamp based protocols

Lock-based Protocols
Database systems equipped with lock-based protocols use a mechanism by which any transaction cannot rea
data until it acquires an appropriate lock on it. Locks are of two kinds −
• Binary Locks − A lock on a data item can be in two states; it is either locked or unlocked.
• Shared/exclusive − This type of locking mechanism differentiates the locks based on their uses. If
acquired on a data item to perform a write operation, it is an exclusive lock. Allowing more than one tr
to write on the same data item would lead the database into an inconsistent state. Read locks are shared
no data value is being changed.
There are four types of lock protocols available −
Simplistic Lock Protocol
Simplistic lock-based protocols allow transactions to obtain a lock on every object before a 'write' operation is p
Transactions may unlock the data item after completing the ‘write’ operation.
Pre-claiming Lock Protocol
Pre-claiming protocols evaluate their operations and create a list of data items on which they need locks. Befor
an execution, the transaction requests the system for all the locks it needs beforehand. If all the locks are gr
transaction executes and releases all the locks when all its operations are over. If all the locks are not gr
transaction rolls back and waits until all the locks are granted.
Two-Phase Locking 2PL
This locking protocol divides the execution phase of a transaction into three parts. In the first part, when the tr
starts executing, it seeks permission for the locks it requires. The second part is where the transaction acqui
locks. As soon as the transaction releases its first lock, the third phase starts. In this phase, the transacti
demand any new locks; it only releases the acquired locks.

Two-phase locking has two phases, one is growing, where all the locks are being acquired by the transactio
second phase is shrinking, where the locks held by the transaction are being released.
To claim an exclusive (write) lock, a transaction must first acquire a shared (read) lock and then upgrade it to an
lock.

42. Write difference between shared lock and exclusive lock.

Ans: Exclusive locks


Exclusive locks protect updates to file resources, both recoverable and non-recoverable. They can be owned by on
transaction at a time. Any transaction that requires an exclusive lock must wait if another task currently owns an e
lock or a shared lock against the requested resource.

Shared locks
Shared locks support read integrity. They ensure that a record is not in the process of being updated during a read
request. Shared locks can also be used to prevent updates of a record between the time that a record is read and th
syncpoint.

A shared lock on a resource can be owned by several tasks at the same time. However, although several tasks can o
shared locks, there are some circumstances in which tasks can be forced to wait for a lock:

• A request for a shared lock must wait if another task currently owns an exclusive lock on the resource.
• A request for an exclusive lock must wait if other tasks currently own shared locks on this resource.
• A new request for a shared lock must wait if another task is waiting for an exclusive lock on a resource that
has a shared lock.

43. What is locking? Explain Two phase locking and its types.

Ans:
A lock is a variable associated with a data item that describes the status of the item with respect to possible o
that can be applied to it. Generally, there is one lock for each data item in the database. Locks are used as a
synchronizing the access by concurrent transactions to the database item.

Exclusive locks
Exclusive locks protect updates to file resources, both recoverable and non-recoverable. They can be owned by on
transaction at a time. Any transaction that requires an exclusive lock must wait if another task currently owns an e
lock or a shared lock against the requested resource.

Shared locks
Shared locks support read integrity. They ensure that a record is not in the process of being updated during a read
request. Shared locks can also be used to prevent updates of a record between the time that a record is read and th
syncpoint.

A shared lock on a resource can be owned by several tasks at the same time. However, although several tasks can o
shared locks, there are some circumstances in which tasks can be forced to wait for a lock:

• A request for a shared lock must wait if another task currently owns an exclusive lock on the resource.
• A request for an exclusive lock must wait if other tasks currently own shared locks on this resource.
• A new request for a shared lock must wait if another task is waiting for an exclusive lock on a resource that
has a shared lock.

44. explain cryptography techniques to secure data.


Ans: Cryptography provides for secure communication in the presence of malicious third-parties—
as adversaries. Encryption uses an algorithm and a key to transform an input (i.e., plaintext) into a
encrypted output (i.e., ciphertext). A given algorithm will always transform the same plaintext into
same ciphertext if the same key is used.
Algorithms are considered secure if an attacker cannot determine any properties of the plaintext o
given the ciphertext. An attacker should not be able to determine anything about a key given a larg
number of plaintext/ciphertext combinations which used the key.
With symmetric cryptography, the same key is used for both encryption and decryption. A sender
recipient must already have a shared key that is known to both. Key distribution is a tricky problem
was the impetus for developing asymmetric cryptography.
With asymmetric crypto, two different keys are used for encryption and decryption. Every user in a
asymmetric cryptosystem has both a public key and a private key. The private key is kept secret a
times, but the public key may be freely distributed.
Data encrypted with a public key may only be decrypted with the corresponding private key. So, se
message to John requires encrypting that message with John’s public key. Only John can decrypt
message, as only John has his private key. Any data encrypted with a private key can only be decr
with the corresponding public key. Similarly, Jane could digitally sign a message with her private k
anyone with Jane’s public key could decrypt the signed message and verify that it was in fact Jan
sent it.
Symmetric is generally very fast and ideal for encrypting large amounts of data (e.g., an entire disk
partition or database). Asymmetric is much slower and can only encrypt pieces of data that are sm
than the key size (typically 2048 bits or smaller). Thus, asymmetric crypto is generally used to enc
symmetric encryption keys which are then used to encrypt much larger blocks of data. For digital
signatures, asymmetric crypto is generally used to encrypt the hashes of messages rather than en
messages.
A cryptosystem provides for managing cryptographic keys including generation, exchange, storag
revocation, and replacement of the keys.

45. Explain DAC and MAC models in detail.

Ans: DAC is a type of access control in which the owner of a resource restricts access to the resource based o
identity of the users. MAC is a type of access control that restricts the access to the resources based on the cle
the subjects.

The DAC stands for Discretionary Access Control (DAC) and the MAC stands for Mandatory Access Control.
Basis
In DAC, the resource owner determines who can access and what privileges they have. MAC provides acc
users depending on the clearance level of the users. Access is determined by the system.

Flexibility
Furthermore, DAC is more flexible than MAC.

Security
Also, MAC is more secure than DAC.

Implementation
Moreover, DAC is easier to implement than MAC.

Conclusion
The main difference between DAC and MAC is that the DAC is an access control method in which the ow
resource determines the access while the MAC is an access control method that provides access to the
depending on the clearance level of the user. In brief, DAC is suitable

46. Write SQL statements (Query) for following tables: T1(roll_no, stuname,

Age, city, branchcode) T2(branchcode, branchname)

1. Retrieve students details whose branchcode is 5.


Ans:
2. Find an average age of all students.
Ans:
3. Add new branch in T2 table
Ans:
4. Display rollno, stuname and age of students whose city is Chennai.
Ans:
5. Change age of student to 20 whose rollno is 18
Ans:
6. Delete student details whose age is 18
Ans:
7. Retrieve branch information in descending order.
Ans:

47. Describe following commands:

Grant: specially used to provide privileges to database objects for a user. This command also allows
Users to grant permissions to other users too.

Syntax: grant privilege_name on object_name to {user_name|public|role_name}

Revoke: revoke command withdraw user priviliges on database objects if any granted. It does
Operations opposite to the grant command. When a privilege is revoked from a particular user U,

Then the privileges granted to all other users U will be revoked

Syntax: revoke privilenge_name on object_name from {user_name|public|role_name}

A COMMIT is the SQL command used in the transaction tables or database to make the current tran
database statement as permanent. It shows the successful completion of a transaction. If we have successfully
the transaction statement or a simple database query, we want to make the changes permanent. We need t
the commit command to save the changes, and these changes become permanent for all users. Furthermore
commit command is executed in the database, we cannot regain its previous states in which it was earlier
execution of the first statement.

Syntax

1. COMMIT;

The SQL ROLLBACK command is used to roll back the current transaction state if any error occurred during the
of a transaction. In a transaction, the error can be a system failure, power outage, incorrect execution of the tr
system crash, etc. Generally, a rollback command performs the current transaction's rollback action to
transaction on its previous state or the first statement. A rollback command can only be executed if the us
performed the COMMIT command on the current transaction or statement.

Syntax

1. ROLLBACK;

48. list and explain aggregation functions with suitable examples.


Ans: Aggregate functions in DBMS take multiple rows from the table and return a value according to the que
All the aggregate functions are used in Select statement.
Syntax −
SELECT <FUNCTION NAME> (<PARAMETER>) FROM <TABLE NAME>

AVG Function
This function returns the average value of the numeric column that is supplied as a parameter.
Example: Write a query to select average salary from employee table.
Select AVG(salary) from Employee

COUNT Function
The count function returns the number of rows in the result. It does not count the null values.
Example: Write a query to return number of rows where salary > 20000.
Select COUNT(*) from Employee where Salary > 20000;
Types −

• COUNT(*): Counts all the number of rows of the table including null.

• COUNT( COLUMN_NAME): count number of non-null values in column.

• COUNT( DISTINCT COLUMN_NAME): count number of distinct values in a column.

MAX Function
The MAX function is used to find maximum value in the column that is supplied as a parameter. It can be us
type of data.
Example − Write a query to find the maximum salary in employee table.
Select MAX(salary) from Employee

SUM Function
This function sums up the values in the column supplied as a parameter.
Example: Write a query to get the total salary of employees.
Select SUM(salary) from Employee

STDDEV Function
The STDDEV function is used to find standard deviation of the column specified as argument.
Example − Write a query to find standard deviation of salary in Employee table.
Select STDDEV(salary) from Employee

VARIANCE Function
The VARIANCE Function is used to find variance of the column specified as argument.
Example −
Select VARIANCE(salary) from Employee

49. Explain single row function with commands


Ans: Single row functions
Single row functions can be character functions, numeric functions, date functions, and conversion functions.
these functions are used to manipulate data items. These functions require one or more input arguments an
on each row, thereby returning one output value for each row. Argument can be a column, literal or an expressi
row functions can be used in SELECT statement, WHERE and ORDER BY clause. Single row functions can b
• Case Conversion functions - Accepts character input and returns a character value. Functions
category are UPPER, LOWER and INITCAP.
o UPPER function converts a string to upper case.
o LOWER function converts a string to lower case.
o INITCAP function converts only the initial alphabets of a string to upper case.

50. Write short note on with examples


1. Cursor with types
A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A cursor holds
(one or more) returned by a SQL statement. The set of rows the cursor holds is referred to as the active set.
You can name a cursor so that it could be referred to in a program to fetch and process the rows returned b
statement, one at a time. There are two types of cursors −

• Implicit cursors
• Explicit cursors

Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when there is
cursor for the statement. Programmers cannot control the implicit cursors and the information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is associated
statement. For INSERT operations, the cursor holds the data that needs to be inserted. For UPDATE and
operations, the cursor identifies the rows that would be affected.
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always has attrib
as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT. The SQL cursor has
attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS, designed for use with the FORALL statemen

Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over the context area. An explicit cur
be defined in the declaration section of the PL/SQL Block. It is created on a SELECT Statement which returns
one row.
The syntax for creating an explicit cursor is −
CURSOR cursor_name IS select_statement;
Working with an explicit cursor includes the following steps −

• Declaring the cursor for initializing the memory


• Opening the cursor for allocating the memory
• Fetching the cursor for retrieving the data
• Closing the cursor to release the allocated memory

2. Trigger with advantage

Triggers are programs that are available in the memory, with unique names made up of SQL queri
we need to fire on our database on and off.
Triggers can be made to insert, update and delete statements in SQL

Advantages of Triggers in SQL


Some of the prominent advantages of triggers are as follows:

1. Helps us to automate the data alterations.

2. Allows us to reuse the queries once written.

3. Provides a method to check the data integrity of the database.

4. Helps us to detect errors on the database level.

5. Allows easy auditing of data.

51. Explain different types of triggers.


Ans: Following are different types of triggers in Sql Server

▪ Data Manipulation Language (DML) Triggers

DML triggers are executed when a DML operation like INSERT, UPDATE OR DELETE is fired on a Table or View.

DML Triggers are of the following two types


AFTER Triggers

AFTER Triggers are executed after the DML statement completes but before it is committed to the datab
Triggers if required can rollback it’s actions and source DML statement which invoked it.

INSTEAD OF Triggers

INSTEAD OF Triggers are the triggers which gets executed automatically in place of triggering DML (i.e. INSER
and DELETE) action. It means if we are inserting a record and we have a INSTEAD OF trigger for INSERT then
INSERT whatever action is defined in the trigger that gets executed.
▪ Data Definition Language (DDL) Triggers

DDL Triggers are executed when a DDL Statements like CREATE, ALTER, DROP, GRANT, DENY, REVOKE, an
STATISTICS statements are executed. Certain system stored procedures that perform DDL like operations c
DDL triggers.

DDL triggers can be DATABASE scoped or SERVER scoped. The DDL triggers with Server level scope gets fired i
to a DDL statement with server scope like CREATE DATABASE, CREATE LOGIN, GRANT_SERVER, ALTER DATAB
LOGIN etc. Where as DATABASE scoped DDL triggers fire in response to DDL statement with DATABASE SCOPE l
TABLE, CREATE PROCEDURE, CREATE FUNCTION, ALTER TABLE, ALTER PROCEDURE, ALTER FUNCTION etc.

▪ LOGON Triggers

Logon Triggers gets executed automatically in response to a LOGON event. They get executed only after the
authentication but before the user session is established. If authentication fails the logon triggers will not be f

▪ CLR Triggers

CLR Triggers are based on the Sql CLR. We can write DML and DDL triggers by using the Supported .NET CLR
like C#, VB.NET etc. CLR triggers will useful if require heavy computation in the trigger or require referenc
outside SQL.

51. Explain stored procedure with proper example.


Ans: stored procedure is a group of one or more pre-compiled SQL statements into a logical unit. It is st
object inside the database server. It is a subroutine or a subprogram in the common computing language tha
created and stored in the database. Each procedure in SQL Server always contains a name, parameter
Transact-SQL statements. The SQL Database Server stores the stored procedures as named objects. We can
procedures by using triggers, other procedures, and applications such as Java

, Python
, PHP
, etc. It can support almost all relational database systems.

SQL Server

builds an execution plan when the stored procedure is called the first time and stores them in the cache memory. The plan is reuse
Server in subsequent executions of the stored procedure, allowing it to run quickly and efficiently.
Features of Stored Procedures in SQL Server
The following are the features of stored procedure in SQL Server:

o Reduced Traffic: A stored procedure reduces network traffic between the application and the database server,
increased performance. It is because instead of sending several SQL

statements, the application only needs to send the name of the stored procedure and its parameters.

o Stronger Security: The procedure is always secure because it manages which processes and activities we can
removes the need for permissions to be granted at the database object level and simplifies the security layers.
o Reusable: Stored procedures are reusable. It reduces code inconsistency, prevents unnecessary rewrites of the
and makes the code transparent to all applications or users.
o Easy Maintenance: The procedures are easier to maintain without restarting or deploying the application.
o Improved Performance: Stored Procedure increases the application performance. Once we create the stored
and compile them the first time, it creates an execution plan reused for subsequent executions. The procedur
processed quicker because the query processor does not have to create a new plan.

Types of Stored Procedures


SQL Server categorizes the stored procedures mainly in two types:

17.8M
368
HTML Tutorial

1. User-defined Stored Procedures


2. System Stored Procedures

53. write a PL/SQL code to print sum of the odd numbers between 1 to 100

Ans:
NUM
Sum
begin
loop
NUM1 :=
Sum:=Sum+Num1;
exit when
end
dbms_output.put_line
end;

Output:

The sum of odd numbers is 2500

54. write a PL/SQL code to print sum of the even numbers between 1 to 100

Ans: declare
NUM number:=0;
Sum number:=0;
begin
loop
NUM1 := NUM+2;
Sum:=Sum+Num1;
exit when NUM1=100;
end loop;
dbms_output.put_line (sum);
end;

55. Write PL/SQL code to print first 10 0dd numbers.


Ans: The following PL/SQL code will print odd numbers between 1 to 10.
declare
n number := 1;
begin
while n<=10
loop
dbms_output.put_line(n);
n := n+2;
end loop;
end;
/
Output:

Prepared by: Dhwija Kachhia


43 What is locking? Explain Two phase locking and its types

44 Explain cryptography techniques to secure data.

45 Explain DAC and MAC models in detail.

46
Write short note on with examples
50
1. Cursor with types
2. Trigger with advantage
Explain Different Types of Triggers.

51

52 Explain stored procedure with proper example.

53 Write A PL/SQL Code to Print Sum Of The Odd Numbers Between 1 to 100.

54 Write a PL/SQL code to print sum of the even numbers between 1 to 100

55

You might also like