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

Ucs 51 - Database Management Systems Unit-1 - Introduction: Type: 100% Theory Question Bank

The document discusses a database management systems (DBMS) course syllabus. It includes: 1) Sample questions from the syllabus covering topics like applications of DBMS, data models, entity relationship modeling, keys, and more. 2) Definitions of DBMS, database, schema, instance, and other core database concepts. 3) Descriptions of entity attributes, relationships, and cardinality. 4) An overview of advantages of using a DBMS like reduced data redundancy, concurrent access control, and integration with other applications.

Uploaded by

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

Ucs 51 - Database Management Systems Unit-1 - Introduction: Type: 100% Theory Question Bank

The document discusses a database management systems (DBMS) course syllabus. It includes: 1) Sample questions from the syllabus covering topics like applications of DBMS, data models, entity relationship modeling, keys, and more. 2) Definitions of DBMS, database, schema, instance, and other core database concepts. 3) Descriptions of entity attributes, relationships, and cardinality. 4) An overview of advantages of using a DBMS like reduced data redundancy, concurrent access control, and integration with other applications.

Uploaded by

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

ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

UCS 51 – DATABASE MANAGEMENT SYSTEMS


Unit-1 – Introduction
Type: 100% Theory
Question Bank

Syllabus: [Regulation: 2012]


UNIT-I:Purpose of Database - Overall System Structure - Entity Relationship Model -Mapping
Constraints - Keys - E-R Diagrams.

PART – A QUESTIONS

1. Any five applications on database.(April/May 2016)

 ListBanking and Financial services


 Airlines
 Universities Credit card transactions
 Human Resource
 Transport and Tourism

2. Define DBMS.[April/May 2014]


A database-management system (DBMS) is a collection of interrelated data and a set
of programs to access those data. The collection of data usually referred to as the
database.

3. Define database.[Nov 2014]


The collection of data, usually referred to as the database, contains information relevant
to an enterprise.

4. What are the applications of DBMS?


 Enterprise information
 Sales
 Accounting
 Human resource
 Manufacturing
 Online retailers

 Banking and finance


 Banking
 Credit card transactions
RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0
Unit – 1 Answer Page 1 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

 Finance
 Universities
 Airlines
 Telecommunications

5. What is the primary goal of DBMS?


The primary goal of a DBMS is to provide a way to store and retrieve database
information that is both convenient and efficient.

6. What happens when multiple users are allowed to access a database?


Concurrent-access anomalies occur many systems allow multiple users to update
thedata simultaneously. In such an environment, interaction of concurrent updates may
result in inconsistent data.

7. How do you define consistency in terms of database? How you maintain consistency
in database?
Consistency is maintaining data in a correct state. This could be accomplished by
Atomicity property.

8. Define abstraction.
A major purpose of a database system is to provide users with an abstract view of the
data. That is, the system hides certain details of how the data are stored and maintained.

9. Define schema.
The overall design of the database is called the database schema.Schemas are changed
infrequently.

10. What is an instance?


The collection of information stored in the database at a particular moment is called an
instance of the database.

11. What is a relationship? Give example. (Apr/May 2016)


A relationship is an association among several entities. For example, a depositor
relationship associates a customer with each account that they having.

12. Mention the types of Data models.[Nov 2014]


There are a number of different data models; they can be classified into four different
categories
 Relation model

RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0


Unit – 1 Answer Page 2 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

 Entity relationship model


 Object-based Data model
 Semi-structured Data model

13. Define E-R model. [April/May 2014]


The entity-relationship (E-R) data model uses a collection of basic objects, called
entities,andrelationships among these objects.

14. What is an entity?


An entity is a “thing” or “object” in the real world that is distinguishable from other
objects. For example, each person is an entity, and bank accounts can be considered as
entities.

15. What is an attribute?(DEC 2011)


Entities are represented by means of their propertiescalled attributes. All attributes have
values.

16. What are different types of keys(NOV 2013)


Key is an attribute or collection of attributes that uniquely identifies an entity among
entity set. For example, roll_number of a student makes her/him identifiable among
students.
 Super Key
 Candidate Key
 Primary Key

17. Define Super Key.(NOV )


Super Key: Set of attributes (one or more) that collectively identifies an entity in an
entity set.

18. What is candidate key?


Candidate Key:Minimal super key is called candidate key that is, supers keys for which
no proper subset are a super key. An entity set may have more than one candidate key.
19. What is primary key?
Primary Key:This is one of the candidate key chosen by the database designer to uniquely
identify the entity set.
20. What are the uses of query language?
Query Language: DBMS is equipped with query language, which makes it more
efficient to retrieve and manipulate data. A user can apply as many and different filtering
options, as he or she wants. Traditionally it was not possible where file-processing
system was used.

21. Short notes on less redundancy.


RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0
Unit – 1 Answer Page 3 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

Less redundancy: DBMS follows rules of normalization, which splits a relation when
any of its attributes is having redundancy in values. Following normalization, which itself
is a mathematically rich and scientific process, make the entire database to contain as less
redundancy as possible.

22. Define isolation of data and application.


Isolation of data and application: A database system is entirely different than its data.
Where database is said to active entity, data is said to be passive one on which the
database works and organizes. DBMS also stores metadata which is data about data, to
ease its own process.

23. What is simple attributes?


Simple Attributes:Simple attributes are atomic values, which cannot be divided further.
For example, student's phone-number is an atomic value of 10 digits.

24. Write about Composite attribute.


Composite attribute:Composite attributes are made of more than one simple attribute.
For example, a student's complete name may have first_name and last_name.

25. Define derived attributes.


Derived attribute:Derived attributes are attributes, which do not exist physical in the
database, but there values are derived from other attributes presented in the database. For
example, average_salary in a department should be saved in database instead it can be
derived. For another example, age can be derived from data_of_birth.

26. Short notes on single-valued and multi-valued attributes.


Single-valued attribute:Single valued attributes contain on single value. For example:
Social_Security_Number.
Multi-value attribute:Multi-value attribute may contain more than one values. For
example, a person can have more than one phone numbers, email_addresses etc.

27. Define binary relationship and cardinality.


Binary Relationship and Cardinality: A relationship where two entities are
participating is called a binary relationship. Cardinality is the number of instance of an
entity from a relation that can be associated with the relation.
 One – to - one
 One – to – many
 Many – to – one
 Many – to – many

RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0


Unit – 1 Answer Page 4 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

PART – B QUESTIONS

1. List the advantages of DBMS.(NOV/DEC 2011, NOV/DEC 2012)


Features of DBMS:
 Users can create tables, queries, forms and reports and connect them together with
macros.

 The import and export of data to many formats including Excel, Outlook, ASCII, dBase,
Paradox, FoxPro, SQL Server, Oracle, ODBC, etc.

 There is also the Jet Database format (MDB or ACCDB in Access 2007), which can
contain the application and data in one file. This makes it very convenient to distribute
the entire application to another user, who can run it in disconnected environments.

 Microsoft Access offers parameterized queries. These queries and Access tables can be
referenced from other programs like VB6 and .NET through DAO or ADO.

 The desktop editions of Microsoft SQL Server can be used with Access as an alternative
to the Jet Database Engine.

 Microsoft Access is a file server-based database. Unlike client-server relational database


management systems (RDBMS), Microsoft Access does not implement database triggers,
stored procedures, or transaction logging.

 High Performance and High Availability.

 Database mirroring with Database snapshots.

 CLR integration.

 Service Broker.

 Supports DDL, DML, DCL, TCL, procedure, triggers and curser.

 Ranking functions.Row version-based isolation levels.

2. Explain entity and entity sets with examples.(NOV 2012)


Entity
A real-world thing either animate or inanimate that can be easily identifiable and
distinguishable. For example, in a school database, student, teachers, class and course offered
can be considered as entities. All entities have some attributes or properties that give them
their identity.

An entity set is a collection of similar types of entities. Entity set may contain entities
with attribute sharing similar values. For example, Students set may contain all the student of

RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0


Unit – 1 Answer Page 5 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

a school; likewise Teachers set may contain all the teachers of school from all faculties.
Entities sets need not to be disjoint.

Entities are represented by means of rectangles. Rectangles are named with the entity set
they represent.

[Image: Entities in a school database]

ENTITY-SET AND KEYS

Key is an attribute or collection of attributes that uniquely identifies an entity among


entity set.

For example, roll_number of a student makes her/him identifiable among students.

 Super Key: Set of attributes (one or more) that collectively identifies an entity in an
entity set.
 Candidate Key: Minimal super key is called candidate key that is, supers keys for which
no proper subset are a superkey. An entity set may have more than one candidate key.
 Primary Key: This is one of the candidate key chosen by the database designer to
uniquely identify the entity set.

3. Explain the different types of attributes used in the E-R diagram (APRIL/MAY 2013)
Attributes:
Entities are represented by means of their properties, called attributes. All attributes have
values. For example, a student entity may have name, class, age as attributes.

There exist a domain or range of values that can be assigned to attributes. For example, a
student's name cannot be a numeric value. It has to be alphabetic. A student's age cannot be
negative, etc.

TYPES OF ATTRIBUTES:

 Simple attribute:
Simple attributes are atomic values, which cannot be divided further. For example, student's
phone-number is an atomic value of 10 digits.

 Composite attribute:
Composite attributes are made of more than one simple attribute. For example, a student's
complete name may have first_name and last_name.

RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0


Unit – 1 Answer Page 6 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

 Derived attribute:
Derived attributes are attributes, which do not exist physical in the database, but there values
are derived from other attributes presented in the database. For example, average_salary in a
department should be saved in database instead it can be derived. For another example, age
can be derived from data_of_birth.

 Single-valued attribute:
Single valued attributes contain on single value. For example: Social_Security_Number.

 Multi-value attribute:
Multi-value attribute may contain more than one values. For example, a person can have
more than one phone numbers, email_addresses etc.

These attribute types can come together in a way like:

 simple single-valued attributes

 simple multi-valued attributes

 composite single-valued attributes

 composite multi-valued attributes

4. Briefly exampling the design issues of E-R model (APRIL/MAY 2013)


E-R Data Models:
Data model tells how the logical structure of a database is modeled. Data Models are
fundamental entities to introduce abstraction in DBMS. Data models define how data is
connected to each other and how it will be processed and stored inside the system.

The very first data model could be flat data-models where all the data used to be kept in same
plane. Because earlier data models were not so scientific they were prone to introduce lots of
duplication and update anomalies.

Entity-Relationship Model

Entity-Relationship model is based on the notion of real world entities and relationship
among them. While formulating real-world scenario into database model, ER Model creates
entity set, relationship set, general attributes and constraints.

ER Model is best used for the conceptual design of database.

ER Model is based on:

 Entities and their attributes


 Relationships among entities
RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0
Unit – 1 Answer Page 7 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

These concepts are explained below.

[Image: ER Model]
 Entity
An entity in ER Model is real world entity, which has some properties called attributes.
Every attribute is defined by its set of values, called domain.
For example, in a school database, a student is considered as an entity. Student has various
attributes like name, age and class etc.

 Relationship
The logical association among entities is called relationship. Relationships are mapped with
entities in various ways. Mapping cardinalities define the number of association between two
entities.
Mapping cardinalities:

 one to one
 one to many
 many to one
 many to many
Relational Model
The most popular data model in DBMS is Relational Model. It is more scientific model then
others. This model is based on first-order predicate logic and defines table as an n-ary
relation.

RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0


Unit – 1 Answer Page 8 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

[Image: Table in relational Model]


The main highlights of this model are:

 Data is stored in tables called relations.

 Relations can be normalized.

 In normalized relations, values saved are atomic values.

 Each row in relation contains unique value

 Each column in relation contains values from a same domain.

5. Explain the three different levels of system architecture(APRIL/MAY 2014)


System Architecture:
The design of a Database Management System highly depends on its architecture. It can
be centralized or decentralized or hierarchical. DBMS architecture can be seen as single tier
or multi tier. n-tier architecture divides the whole system into related but independent n
modules, which can be independently modified, altered, changed or replaced.

In 1-tier architecture, DBMS is the only entity where user directly sits on DBMS and uses
it. Any changes done here will directly be done on DBMS itself. It does not provide handy
tools for end users and preferably database designer and programmers use single tier
architecture.

If the architecture of DBMS is 2-tier then must have some application, which uses the
DBMS. Programmers use 2-tier architecture where they access DBMS by means of
application. Here application tier is entirely independent of database in term of operation,
design and programming.

3-tier architecture
Most widely used architecture is 3-tier architecture. 3-tier architecture separates it tier
from each other on basis of users. It is described as follows:

RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0


Unit – 1 Answer Page 9 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

[Image: 3-tier DBMS architecture]


 Database (Data) Tier: At this tier, only database resides. Database along with its query
processing languages sits in layer-3 of 3-tier architecture. It also contains all relations and
their constraints.
 Application (Middle) Tier: At this tier the application server and program, which access
database, resides. For a user this application tier works as abstracted view of database. Users
are unaware of any existence of database beyond application. For database-tier, application
tier is the user of it. Database tier is not aware of any other user beyond application tier. This
tier works as mediator between the two.
 User (Presentation) Tier: An end user sits on this tier. From a users aspect this tier is
everything. He/she doesn't know about any existence or form of database beyond this layer.
At this layer multiple views of database can be provided by the application. All views are
generated by applications, which reside in application tier.
Multiple tier database architecture is highly modifiable as almost all its components are
independent and can be changed independently.

6. What are the relationships? Explain with E-R diagram. (APRIL/MAY 2014)
Relationship:
The association among entities is called relationship. For example, employee entity has
relation works_at with department. Another example is for student who enrolls in some
course. Here, Works_at and Enrolls are called relationship.

Relationship set:

Relationship of similar type is called relationship set. Like entities, a relationship too can
have attributes. These attributes are called descriptive attributes.

Degree of Relationship”

The number of participating entities in an relationship defines the degree of the relationship.

RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0


Unit – 1 Answer Page 10 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

 Binary = degree 2

 Ternary = degree 3

 n-ary = degree

MAPPING CARDINALITIES:

Cardinality defines the number of entities in one entity set which can be associated to the
number of entities of other set via relationship set.
 One-to-one: one entity from entity set A can be associated with at most one entity of entity
set B and vice versa.

[Image: One-to-one relation]


 One-to-many: One entity from entity set A can be associated with more than one entities of
entity set B but from entity set B one entity can be associated with at most one entity.

[Image: One-to-many relation]


 Many-to-one: More than one entities from entity set A can be associated with at most one
entity of entity set B but one entity from entity set B can be associated with more than one
entity from entity set A.

RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0


Unit – 1 Answer Page 11 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

[Image: Many-to-one relation]


 Many-to-many: one entity from A can be associated with more than one entity from B and
vice versa.

[Image: Many-to-many relation]

BINARY RELATIONSHIP AND CARDINALITY

A relationship where two entities are participating, is called a binary relationship.


Cardinality is the number of instance of an entity from a relation that can be associated with
the relation.
 One-to-one
When only one instance of entity is associated with the relationship, it is marked as '1'.
This image below reflects that only 1 instance of each entity should be associated with the
relationship. It depicts one-to-one relationship

[Image: One-to-one]
 One-to-many
When more than one instance of entity is associated with the relationship, it is marked as 'N'.
This image below reflects that only 1 instance of entity on the left and more than one
instance of entity on the right can be associated with the relationship. It depicts one-to-many
relationship

[Image: One-to-many]
 Many-to-one

RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0


Unit – 1 Answer Page 12 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

When more than one instance of entity is associated with the relationship, it is marked as 'N'.
This image below reflects that more than one instance of entity on the left and only one
instance of entity on the right can be associated with the relationship. It depicts many-to-one
relationship

[Image: Many-to-one]
 Many-to-many
This image below reflects that more than one instance of entity on the left and more than one
instance of entity on the right can be associated with the relationship. It depicts many-to-
many relationship

[Image: Many-to-many]

7. What is primary key, candidate key and foreign key? Explain. (NOV 2012)
PRIMARY KEY:
o The PRIMARY KEY constraint uniquely identifies each record in a database table.
o Primary keys must contain unique values.
o A primary key column cannot contain NULL values.
o Most tables should have a primary key, and each table can have only ONE primary
key.

SQL PRIMARY KEY Constraint on CREATE TABLE

The following SQL creates a PRIMARY KEY on the "P_Id" column when the "Persons"
table is created:

MySQL:

CREATE TABLE Persons


(
P_Idint NOT NULL,
LastNamevarchar(255) NOT NULL,
RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0
Unit – 1 Answer Page 13 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

FirstNamevarchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
)
FOREIGN KEY:

A FOREIGN KEY in one table points to a PRIMARY KEY in another table.

Let's illustrate the foreign key with an example. Look at the following two tables:

The "Persons" table:

P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes


3 Pettersen Kari Storgt 20 Stavanger

The "Orders" table:

O_Id OrderNo P_Id


1 77895 3

2 44678 3
3 22456 2

4 24562 1

o Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the
"Persons" table.
o The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons"
table.
o The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
o The FOREIGN KEY constraint is used to prevent actions that would destroy links
between tables.
o The FOREIGN KEY constraint also prevents invalid data from being inserted into the
foreign key column, because it has to be one of the values contained in the table.

8. Explain the mapping coordinates with necessary diagrams.(APRIL/MAY 2013)

RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0


Unit – 1 Answer Page 14 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

MAPPING CARDINALITIES:

Cardinality defines the number of entities in one entity set which can be associated to the
number of entities of other set via relationship set.
 One-to-one: one entity from entity set A can be associated with at most one entity of
entity set B and vice versa.

[Image: One-to-one relation]


 One-to-many: One entity from entity set A can be associated with more than one entities
of entity set B but from entity set B one entity can be associated with at most one entity.

[Image: One-to-many relation]


 Many-to-one: More than one entities from entity set A can be associated with at most
one entity of entity set B but one entity from entity set B can be associated with more
than one entity from entity set A.

[Image: Many-to-one relation]


 Many-to-many: one entity from A can be associated with more than one entity from B
and vice versa.

RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0


Unit – 1 Answer Page 15 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

[Image: Many-to-many relation]

9. Briefly explain the database schema with diagram.


Database schema
Database schema skeleton structure of and it represents the logical view of entire
database. It tells about how the data is organized and how relation among them is associated.
It formulates all database constraints that would be put on data in relations, which resides in
database.

A database schema defines its entities and the relationship among them. Database schema
is a descriptive detail of the database, which can be depicted by means of schema diagrams.
All these activities are done by database designer to help programmers in order to give some
ease of understanding all aspect of database.

[Image: Database Schemas]


Database schema can be divided broadly in two categories:

 Physical Database Schema: This schema pertains to the actual storage of data and its form
of storage like files, indices etc. It defines the how data will be stored in secondary storage
etc.

RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0


Unit – 1 Answer Page 16 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

 Logical Database Schema: This defines all logical constraints that need to be applied on
data stored. It defines tables, views and integrity constraints etc.
Database Instance
It is important that we distinguish these two terms individually. Database schema is the
skeleton of database. It is designed when database doesn't exist at all and very hard to do any
changes once the database is operational. Database schema does not contain any data or
information.

Database instances, is a state of operational database with data at any given time. This is
a snapshot of database. Database instances tend to change with time. DBMS ensures that its
every instance (state) must be a valid state by keeping up to all validation, constraints and
condition that database designers has imposed or it is expected from DBMS itself.

PART – C QUESTIONS

1. Explain the overall system structure with neat structure. (DEC 2013)
Overall Structure:
The design of a Database Management System highly depends on its architecture. It can
be centralized or decentralized or hierarchical. DBMS architecture can be seen as single tier
or multi-tier. N-tier architecture divides the whole system into related but independent n
modules, which can be independently modified, altered, changed or replaced.

In 1-tier architecture, DBMS is the only entity where user directly sits on DBMS and uses
it. Any changes done here will directly be done on DBMS itself. It does not provide handy
tools for end users and preferably database designer and programmers use single tier
architecture.

If the architecture of DBMS is 2-tier then must have some application, which uses the
DBMS. Programmers use 2-tier architecture where they access DBMS by means of
application. Here application tier is entirely independent of database in term of operation,
design and programming.

3-tier architecture
Most widely used architecture is 3-tier architecture. 3-tier architecture separates it tier
from each other on basis of users. It is described as follows:

RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0


Unit – 1 Answer Page 17 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

[Image: 3-tier DBMS architecture]


 Database (Data) Tier: At this tier, only database resides. Database along with its query
processing languages sits in layer-3 of 3-tier architecture. It also contains all relations and
their constraints.
 Application (Middle) Tier: At this tier the application server and program, which access
database, resides. For a user this application tier works as abstracted view of database. Users
are unaware of any existence of database beyond application. For database-tier, application
tier is the user of it. Database tier is not aware of any other user beyond application tier. This
tier works as mediator between the two.
 User (Presentation) Tier: An end user sits on this tier. From a users aspect this tier is
everything. He/she doesn't know about any existence or form of database beyond this layer.
At this layer multiple views of database can be provided by the application. All views are
generated by applications, which reside in application tier.
Multiple tier database architecture is highly modifiable as almost all its components are
independent and can be changed independently.

2. Explains the details about the Entity – Relationship model.(APRIL/MAY 2014)


Entity – Relationship model:
Entity relationship model defines the conceptual view of database. It works around real world
entity and association among them. At view level, ER model is considered well for designing
databases.

Entity
A real-world thing either animate or inanimate that can be easily identifiable and
distinguishable. For example, in a school database, student, teachers, class and course offered
can be considered as entities. All entities have some attributes or properties that give them
their identity.

An entity set is a collection of similar types of entities. Entity set may contain entities with
attribute sharing similar values. For example, Students set may contain all the student of a

RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0


Unit – 1 Answer Page 18 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

school; likewise Teachers set may contain all the teachers of school from all faculties.
Entities sets need not to be disjoint.

Attributes
Entities are represented by means of their properties, called attributes. All attributes have
values. For example, a student entity may have name, class, age as attributes.

There exist a domain or range of values that can be assigned to attributes. For example, a
student's name cannot be a numeric value. It has to be alphabetic. A student's age cannot be
negative, etc.

TYPES OF ATTRIBUTES:

 Simple attribute:
Simple attributes are atomic values, which cannot be divided further. For example, student's
phone-number is an atomic value of 10 digits.

 Composite attribute:
Composite attributes are made of more than one simple attribute. For example, a student's
complete name may have first_name and last_name.

 Derived attribute:
Derived attributes are attributes, which do not exist physical in the database, but there values
are derived from other attributes presented in the database. For example, average_salary in a
department should be saved in database instead it can be derived. For another example, age
can be derived from data_of_birth.

 Single-valued attribute:
Single valued attributes contain on single value. For example: Social_Security_Number.

 Multi-value attribute:
Multi-value attribute may contain more than one values. For example, a person can have
more than one phone numbers, email_addresses etc.

These attribute types can come together in a way like:

1. simple single-valued attributes

2. simple multi-valued attributes

3. composite single-valued attributes

4. composite multi-valued attributes

RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0


Unit – 1 Answer Page 19 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

ENTITY-SET AND KEYS

Key is an attribute or collection of attributes that uniquely identifies an entity among entity
set.

For example, roll_number of a student makes her/him identifiable among students.

 Super Key: Set of attributes (one or more) that collectively identifies an entity in an entity
set.
 Candidate Key: Minimal super key is called candidate key that is, supers keys for which no
proper subset are a superkey. An entity set may have more than one candidate key.
 Primary Key: This is one of the candidate key chosen by the database designer to uniquely
identify the entity set.
Relationship
The association among entities is called relationship. For example, employee entity has
relation works_at with department. Another example is for student who enrolls in some
course. Here, Works_at and Enrolls are called relationship.

RELATIONSHIP SET:

Relationship of similar type is called relationship set. Like entities, a relationship too can
have attributes. These attributes are called descriptive attributes.

DEGREE OF RELATIONSHIP

The number of participating entities in an relationship defines the degree of the relationship.

 Binary = degree 2

 Ternary = degree 3

 n-ary = degree

MAPPING CARDINALITIES:

Cardinality defines the number of entities in one entity set which can be associated to the
number of entities of other set via relationship set.
 One-to-one: one entity from entity set A can be associated with at most one entity of entity
set B and vice versa.

RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0


Unit – 1 Answer Page 20 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

[Image: One-to-one relation]


 One-to-many: One entity from entity set A can be associated with more than one entities of
entity set B but from entity set B one entity can be associated with at most one entity.

[Image: One-to-many relation]


 Many-to-one: More than one entities from entity set A can be associated with at most one
entity of entity set B but one entity from entity set B can be associated with more than one
entity from entity set A.

[Image: Many-to-one relation]


 Many-to-many: one entity from A can be associated with more than one entity from B and
vice versa.

[Image: Many-to-many relation]

RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0


Unit – 1 Answer Page 21 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

3. Explain the DBMS and its characteristics.


DBMS:

Database is collection of data which is related by some aspect. Data is collection of facts
and figures which can be processed to produce information. Name of a student, age, class and
her subjects can be counted as data for recording purposes.

Mostly data represents recordable facts. Data aids in producing information which is
based on facts. For example, if we have data about marks obtained by all students, we can
then conclude about toppers and average marks etc.A database management system stores
data, in such a way which is easier to retrieve, manipulate and helps to produce information.

Characteristics:

Traditionally data was organized in file formats. DBMS was all new concepts then and all the
research was done to make it to overcome all the deficiencies in traditional style of data
management. Modern DBMS has the following characteristics:

 Real-world entity: Modern DBMS are more realistic and uses real world entities to design
its architecture. It uses the behavior and attributes too. For example, a school database may
use student as entity and their age as their attribute.
 Relation-based tables: DBMS allows entities and relations among them to form as tables.
This eases the concept of data saving. A user can understand the architecture of database just
by looking at table names etc.
 Isolation of data and application: A database system is entirely different than its data.
Where database is said to active entity, data is said to be passive one on which the database
works and organizes. DBMS also stores metadata which is data about data, to ease its own
process.
 Less redundancy: DBMS follows rules of normalization, which splits a relation when any of
its attributes is having redundancy in values. Following normalization, which itself is a
mathematically rich and scientific process, make the entire database to contain as less
redundancy as possible.
 Consistency: DBMS always enjoy the state on consistency where the previous form of data
storing applications like file processing does not guarantee this. Consistency is a state where
every relation in database remains consistent. There exist methods and techniques, which can
detect attempt of leaving database in inconsistent state.
 Query Language: DBMS is equipped with query language, which makes it more efficient to
retrieve and manipulate data. A user can apply as many and different filtering options, as he
or she wants. Traditionally it was not possible where file-processing system was used.
 ACID Properties: DBMS follows the concepts for ACID properties, which stands for
Atomicity, Consistency, Isolation and Durability. These concepts are applied on transactions,
which manipulate data in database. ACID properties maintains database in healthy state in
multi-transactional environment and in case of failure.
 Multiuser and Concurrent Access: DBMS support multi-user environment and allows them
to access and manipulate data in parallel. Though there are restrictions on transactions when
they attempt to handle same data item, but users are always unaware of them.

RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0


Unit – 1 Answer Page 22 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

 Multiple views: DBMS offers multiples views for different users. A user who is in sales
department will have a different view of database than a person working in production
department. This enables user to have a concentrate view of database according to their
requirements.
 Security: Features like multiple views offers security at some extent where users are unable
to access data of other users and departments. DBMS offers methods to impose constraints
while entering data into database and retrieving data at later stage. DBMS offers many
different levels of security features, which enables multiple users to have different view with
different features. For example, a user in sales department cannot see data of purchase
department is one thing, additionally how much data of sales department he can see, can also
be managed. Because DBMS is not saved on disk as traditional file system it is very hard for
a thief to break the code.
Users
DBMS is used by various users for various purposes. Some may involve in retrieving data
and some may involve in backing it up. Some of them are described as follows:

[Image: DBMS Users]


 Administrators: A bunch of users maintain the DBMS and are responsible for
administrating the database. They are responsible to look after its usage and by whom it
should be used. They create users access and apply limitation to maintain isolation and force
security. Administrators also look after DBMS resources like system license, software
application and tools required and other hardware related maintenance.
 Designer: This is the group of people who actually works on designing part of database. The
actual database is started with requirement analysis followed by a good designing process.
They people keep a close watch on what data should be kept and in what format. They
identify and design the whole set of entities, relations, constraints and views.
 End Users: This group contains the persons who actually take advantage of database system.
End users can be just viewers who pay attention to the logs or market rates or end users can
be as sophisticated as business analysts who take the most of it.

4. Describe short notes on data model in database.


Data Models:

RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0


Unit – 1 Answer Page 23 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

Data model tells how the logical structure of a database is modeled. Data Models are
fundamental entities to introduce abstraction in DBMS. Data models define how data is
connected to each other and how it will be processed and stored inside the system.

The very first data model could be flat data-models where all the data used to be kept in same
plane. Because earlier data models were not so scientific they were prone to introduce lots of
duplication and update anomalies.

Entity-Relationship Model
Entity-Relationship model is based on the notion of real world entities and relationship
among them. While formulating real-world scenario into database model, ER Model creates
entity set, relationship set, general attributes and constraints.

ER Model is best used for the conceptual design of database.

ER Model is based on:

 Entities and their attributes


 Relationships among entities
These concepts are explained below.

[Image: ER Model]
 Entity
An entity in ER Model is real world entity, which has some properties called attributes.
Every attribute is defined by its set of values, called domain.
For example, in a school database, a student is considered as an entity. Student has various
attributes like name, age and class etc.

 Relationship
The logical association among entities is called relationship. Relationships are mapped with
entities in various ways. Mapping cardinalities define the number of association between two
entities.
Mapping cardinalities:

RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0


Unit – 1 Answer Page 24 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

 one to one

 one to many

 many to one

 many to many

Relational Model
The most popular data model in DBMS is Relational Model. It is more scientific model then
others. This model is based on first-order predicate logic and defines table as an n-ary
relation.

[Image: Table in relational Model]


The main highlights of this model are:

 Data is stored in tables called relations.

 Relations can be normalized.

 In normalized relations, values saved are atomic values.

 Each row in relation contains unique value

 Each column in relation contains values from a same domain.

RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0


Unit – 1 Answer Page 25 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

5. Draw the diagrammatic representation about E-R Diagram.


E-R Diagram Representation:
Now we shall learn how ER Model is represented by means of ER diagram. Every object
like entity, attributes of an entity, relationship set, and attributes of relationship set can be
represented by tools of ER diagram.

Entity
Entities are represented by means of rectangles. Rectangles are named with the entity set they
represent.

[Image: Entities in a school database]


Attributes

Attributes are properties of entities. Attributes are represented by means of eclipses. Every
eclipse represents one attribute and is directly connected to its entity (rectangle).

[Image: Simple Attributes]

If the attributes are composite, they are further divided in a tree like structure. Every node is
then connected to its attribute. That is composite attributes are represented by eclipses that
are connected with an eclipse.

RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0


Unit – 1 Answer Page 26 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

[Image: Composite Attributes]


Multivalued attributes are depicted by double eclipse.

[Image: Multivalued Attributes]

Derived attributes are depicted by dashed eclipse.

[Image: Derived Attributes]


Relationship

Relationships are represented by diamond shaped box. Name of the relationship is written
in the diamond-box. All entities (rectangles), participating in relationship, are connected to it
by a line.

BINARY RELATIONSHIP AND CARDINALITY

RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0


Unit – 1 Answer Page 27 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

A relationship where two entities are participating, is called a binary relationship.


Cardinality is the number of instance of an entity from a relation that can be associated with
the relation.
 One-to-one
When only one instance of entity is associated with the relationship, it is marked as '1'.
This image below reflects that only 1 instance of each entity should be associated with the
relationship. It depicts one-to-one relationship

[Image: One-to-one]
 One-to-many
When more than one instance of entity is associated with the relationship, it is marked as 'N'.
This image below reflects that only 1 instance of entity on the left and more than one
instance of entity on the right can be associated with the relationship. It depicts one-to-many
relationship

[Image: One-to-many]
 Many-to-one
When more than one instance of entity is associated with the relationship, it is marked as 'N'.
This image below reflects that more than one instance of entity on the left and only one
instance of entity on the right can be associated with the relationship. It depicts many-to-one
relationship

[Image: Many-to-one]
 Many-to-many

RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0


Unit – 1 Answer Page 28 of 29
ACADEMIC YEAR: 2016– 2017 REGULATION CBCS - 2012

This image below reflects that more than one instance of entity on the left and more than one
instance of entity on the right can be associated with the relationship. It depicts many-to-
many relationship

[Image: Many-to-many]

PARTICIPATION CONSTRAINTS

 Total Participation: Each entity in the entity is involved in the relationship. Total
participation is represented by double lines.
 Partial participation: Not all entities are involved in the relationship. Partial participation is
represented by single line.

[Image: Participation Constraints]

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

RAAK/B.Sc(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-1 ANS/VER 2.0


Unit – 1 Answer Page 29 of 29
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

UCS 51 – DATABASE MANAGEMENT SYSTEM


Unit-2 – Relational Model
Type: 100% Theory
Questions And Answers
PART – A QUESTIONS

1. Define Tuple. (April /May 2016,Nov/Dec 2011)

A tuple is a nothing but one record in a table. A tuple usually represents an object
and information about that object. Objects are typically physical objects or concepts

2. What is query?(April /May 2016)

A query is a request for data or information from a database table or combination


of tables. This data may be generated as results returned by Structured Query
Language (SQL) or as pictorials, graphs or complex results, e.g., trend analyses
from data-mining tools.

3. What is the need for primary key?(Nov/Dec 2015)

 Need your table to be joinable on something.

 If you want your table to be clustered, you need some kind of a primary key.

 If your table design does not need a primary key, rethink your design: most
probably, you are missing something

4. What is Relationship? (Nov 2014)

A relationship is an association amongseveralentities.

Example:Adepositorrelationshipassociatesacustomerwitheachaccountthat he/shehas.

5. What is Data Dictionary? (Nov 2014)

Adatadictionary isadatastructurewhichstoresmetadataaboutthestructureof
thedatabaseie. theschemaofthedatabase.

6. What is Relational Algebra? (Nov/Dec 2011)

Therelationalalgebraisaproceduralquery language.Itconsistsofasetof
operationsthattake oneor tworelationasinputandproduce a newrelationas output.
RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0
Unit – 2 Answers Page 1 of 28
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

7. Give the use of Select operation. (Nov 2012)

 It is used to choose a subset of the tuples from a relation that satisfies a


selection condition.
 It restricts the tuples in a relation to only those tuples that satisfy the
condition.
 It can also used to be visualized as a horizontal partition of the relation into
two sets of tuples

8. What is order by clause? (Nov 2012)

ORDER BY is an optional clause which will allow you to display the results
of your query in a sorted order (either ascending order or descending order) based
on the columns that you specify to order by.

9. Give the general procedure for set difference operation. (April/May 2013)

The set difference operation: - finds tuples in one relation but not in other. It
is denoted as –

Example: Find the names of all customers who have an account but not a loan.

Code: πcustomer-name (Depositor) - πcustomer-name (Borrower)

10. What is Data Independence? (April/May 2014)

Data dependence is the way in which the data is organized in secondary


storage, and the technique for accessing it, are both dictated by the requirements of
the application under consideration, and moreover that knowledge of that data
organization and that access technique is built into the application logic and code.

11. What is a view? How it is related to data independence? (April/May 2014)

Any relationthatisnotpartofthelogicalmodel,butismadevisibletoauserasa
virtual relation is called aview.

WedefineviewinSQLbyusingthecreateviewcommand.Theformofthe
createviewcommand is

Createviewvas <queryexpression>

RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0


Unit – 2 Answers Page 2 of 28
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

12. Whatis theuseofgroup by clause?

Groupbyclauseisusedtoapply aggregate functionstoasetoftuples.The


attributesgiveninthe groupbyclauseare usedtoformgroups.Tupleswiththe
samevalueon all attributes in thegroup by clause areplaced in onegroup.

13. Whatis theuseofsubqueries?

Asubqueryisaselect-from-whereexpressionthatisnestedwithinanother
query.Acommonuseofsubqueriesisto performtestsforsetmembership,make
setcomparisons, and determineset cardinality.

14. Whatis viewin SQL?Howis itdefined?

Any relationthatisnotpartofthelogicalmodel,butismadevisibletoauserasa
virtual relation is called aview.

WedefineviewinSQLbyusingthecreateviewcommand.Theformofthecreatevie
wcommand is

Createviewvas <queryexpression>

15. Whatis theuseofwith clausein SQL?

TheWITHclauseprovidesawayofdefiningatemporaryviewwhosedefinitionis
availableonlyto thequeryin which theWITHclauseoccurs.

16. List the tablemodificationcommands in SQL?

 Deletion
 Insertion
 Updates
 Updateofaview

17. Listout thestatements associatedwitha database transaction?

 Commit work
 Rollback work

18. Whatis transaction?

Transaction is aunit ofprogram execution that accesses and possiblyupdated


various dataitems.

RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0


Unit – 2 Answers Page 3 of 28
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

19. Whatis theuseofintegrity constraints?

Integrity constraintsensurethatchangesmadeto thedatabaseby


authorizedusers donotresultinalossofdataconsistency.Thusintegrity
constraintsguardagainst accidental damageto thedatabase.

20. Whatis trigger?

Triggersarestatementsthatareexecutedautomaticallybythesystemastheside
effect ofamodification to thedatabase.

21. Whataredomainconstraints?

Adomainisasetofvaluesthatmaybeassignedtoanattributeallvaluesthat
appearina column ofarelation must betaken from thesamedomain.

22. Whatare referential integrity constraints?

Avaluethatappearsinonerelationforagivensetofattributesalsoappearsfora
certain set ofattributes in anotherrelation.

23. Whatis assertion? Mentiontheforms available.

Anassertionisapredicateexpressingaconditionthatwewishthedatabase always
to satisfy.

 Domain integrityconstraints.

 Referential integrityconstraints

24. Give thesyntax ofassertion?

Createassertion<assertion name>check<predicate>

25. What is theneed fortriggers?

Triggersareusefulmechanismsforalertinghumansorforstartingcertaintasks
automaticallywhen certain conditions aremet.

 Specifying when atriggeris to be executed.

 Specifythe actions to betaken when thetrigger executes.

RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0


Unit – 2 Answers Page 4 of 28
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

26. Whatis a PROJECToperation?

Theprojectoperationisaunary operationthatreturnsitsargumentrelationwith
certain attributes left out. Projection is denoted bypie (π).

27. What is tuple relational calculus?

Thetuplerelationalcalculationisa proceduralquerylanguage.Itdescribes the


desiredinformationwithoutgivingaspecific procedureforobtainingthat information.

28. What is Domain Relational Calculus?

The domainrelationalcalculususesdomainvariablesthattake onvaluesfroman


attributedomain ratherthan values forentiretuple.

PART – B QUESTIONS

1. Give the schema diagram of banking system(April /May 2016)

RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0


Unit – 2 Answers Page 5 of 28
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

2. Explain set difference and Cartesian product operations. (April /May 2016)
Set Difference
 The difference operation is denoted by Depositor-Borrower.
 The Result of the difference operator is the relation that contains all tuples in
depositor but not in Borrower
Depositor-Borrower
Customer _name City
Johnson Mumbai
Lindsay Nashik
Turner Mumbai

 Both union and intersection operation are commulative and associative


operations.
 This means that the following are true:
 AUB=BUA And A∩B=B∩A
 AU(BUC)=(AUB)UC And A∩(B∩C)=(A∩B)∩C
 The difference operation is not commulative.This means that A-B is not the
same as B-A or in other words A-B#B-A.

Cartesian Product

 The Cartesian product is also known as CROSS PRODUCT or CROSS


JOINS.
 It is denoted by’x’.The Cartesian product of two relations A and B is
denoted by AxB.
 The result of Cartesian product of two relations which X and Y columns is a
relation that has X+Y columns .
 The resulting relation will have one tuple or each combination of tuples
from each participating relation.
 Hence if the relations have n and m tuples respectively,then the
CARTESIAN PRODUCT will have n*m tuples.

RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0


Unit – 2 Answers Page 6 of 28
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

3. Give an explanation about formal query language. (April /May 2016)

A query language is a language in which a user requests information from a


database. These are typically higher-level than programming languages.

They may be one of:

 Procedural, where the user instructs the system to perform a


sequence of operations on the database.
 Nonprocedural, where the user species the information desired
without giving a procedure for obtaining the information.

A complete query language also contains facilities to insert and delete tuples
as well as to modify parts of existing tuples.

4. Explain Entity, Attribute and Domain. (Nov 2014)

Entity

 Entities are represented by means of rectangles. Rectangles are


named with the entity set they represent.

Attributes

 Attributes are properties of entities. Attributes are represented by


means of eclipses. Every eclipse represents one attribute and is
directly connected to its entity (rectangle).

Types:

 Compositeattributes are represented by eclipses that are connected


with an eclipse.

RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0


Unit – 2 Answers Page 7 of 28
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

 Multivalued attributes are depicted by double eclipse.

 Derived attributes are depicted by dashed eclipse.

Domain:

 Definition: The domain of a database attribute is the set of all


allowable values that attribute may assume.

 Examples: A field for gender may have the domain {male, female,
unknown} where those three values are the only permitted entries in
that column.

5. State the various process of Relational Database. (Nov 2014)

Databases areusuallycustomizedtosuita particularapplication. Guidelines


areprovidedinmakingthesedesigndecision

Step 1: Define the purpose of the database (Requirement Analysis)


RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0
Unit – 2 Answers Page 8 of 28
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

Gather the requirements and define the objectives of the database.

Eg:Drafting out the input form, queries and reports

Step 2: Gather the data, Organize in tables and specify primary keys.

Once the requirements are collected, organize that data in a table format.
Set primary key for table to uniquely identify the data in that table.

Eg:Emp_Id, Stud_Id, etc,.,

Step 3: Create relationships among tables.

Themostcrucialaspectindesigninga relationaldatabaseistoidentifythe
relationshipsamongtables.Thetypesofrelationshipinclude:

 one‐to‐many
 many‐to‐many
 one‐to‐one

Step 4: Refine & Normalize the design

Normalization:

Applythenormalizationrules
tocheckwhetheryourdatabaseisstructurallycorrectand optimal.

 First
NormalFo r m ﴾1NF﴿:Atableis1NFifeverycellcontainsasinglevalue,
notalistofvalues. Thispropertyis knownasatomic.

 Second Normal Form ﴾2NF﴿: A table is 2NF, if it is 1NF and


every non‐key column is fully dependentontheprimarykey.

 Third Normal
Form﴾3NF﴿:Atableis3NF,ifitis2NFandthenon‐keycolumnsare
independentof eachothers.

6. Explain the modification of the Database. (Nov/Dec 2011&April/May 2014)

The modification of the database can be expressed using the assignment


operator. It includes the following operations.
 Deletion

RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0


Unit – 2 Answers Page 9 of 28
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

 Insertion
 Updating

Deletion:

 Deletion is expressed in much the same way as a query. Instead of


displaying, the selected tuples are removed from the database. We can
only delete whole tuples.
 In relational algebra, a deletion is of the form

where is a relation and is a relational algebra query.Tuples in for


which is true are deleted.

Examples:

 Delete all of Smith's account records.

 Delete all loans with loan numbers between 1300 and 1500.

Insertion:

 To insert data into a relation, we either specify a tuple, or write a query


whose result is the set of tuples to be inserted. Attribute values for
inserted tuples must be members of the attribute's domain.
 An insertion is expressed by

where is a relation and is a relational algebra expression.

Examples:

 To insert a tuple for Smith who has $1200 in account 9372 at the SFU
branch.

RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0


Unit – 2 Answers Page 10 of 28
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

Updating:

 Updating allows us to change some values in a tuple without necessarily


changing all.
 We use the update operator, , with the form

Where sigma is a relation with attribute , the expression is any


arithmetic expression involving constants and attributes in relation .

Examples:
 To increase all balances by 5 percent.

This statement is applied to every tuple in deposit.

7. Explain the following operation (Nov/Dec 2011)


a) Select:

Select selects tuples that satisfy a given predicate. Select is denoted by


alower case Greek sigma (σ), with the predicate appearing as a subscript. The
argument relation is given in parentheses following the σ.

For example, to select tuples (rows) of the borrow relation where the
branch is “SFU", we would write

σborrow= “SFU” (borrow)

Let Figure be distinguished, borrow and branch relations in the banking


example.

RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0


Unit – 2 Answers Page 11 of 28
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

The new relation created as the result of this operation consists of one tuple:
(SFU; 15; Hayes; 1500).

 We allow comparisons using =, > and ≥ in the selection predicate.


 We also allow the logical connectives v (or) and ^ (and).

For example:

σbname = “Downtown” ^ amount >1200 (borrow)

b) Project:

 Project copies its argument relation for the specified attributes only.
Since a relation is a set, duplicate rows are eliminated.

 Projection is denoted by the Greek capital letter pi (π). The attributes


to be copied appear as subscripts.

For example, to obtain a relation showing customers and branches, but


ignoring amount and loan#, we write

πbname, cname(borrow)

We can perform these operations on the relations resulting from other


operations. To get the names of customers having the same name as their
bankers,

πcname(σcname=banker(client))

Think of select as taking rows of a relation, and project as taking


columns of a relation.

8. Explain in brief on Assertion Function. (Nov 2012)

 An assertion is a predicate expressing a condition we wish the database


to always satisfy.

 Domain constraints, functional dependency and referential integrity are


special forms of assertion.
RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0
Unit – 2 Answers Page 12 of 28
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

 Where a constraint cannot be expressed in these forms, we use an


assertion, e.g.

o Ensuring the sum of loan amounts for each branch is less than
the sum of all account balances at the branch.

o Ensuring every loan customer keeps a minimum of $1000 in an


account.

 An assertion in DQL-92 takes the form, create assertion assertion-


name check predicate

 Two assertions mentioned above can be written as follows.

o Ensuring the sum of loan amounts for each branch is less than
the sum of all account balances at the branch.

o Ensuring every loan customer keeps a minimum of $1000 in an


account.

 When an assertion is created, the system tests it for validity.

 Some system developer omits support for general assertions or provides


specialized form of assertions that are easier to test.

Eg:

create assertion sum-constraintcheck


(not exists (select * frombranch
where (selectsum)amount) fromloan
where (loan.bname = branch.bname>=
(selectsum)amount) fromaccount
where(account.bname=
branch.bname)))

9. What is meant by Relational Algebra? (Nov 2012& April/May 2013)

RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0


Unit – 2 Answers Page 13 of 28
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

 Relational algebra is a procedural query language .It consists of set of


operation that takes one or more operations as input and produce a new
relation as their result.

Formal definition of the relational algebra:

A basic expression in the relational algebra consist of either one of the


following:

 A relation in the database

 A constant relation

A constant relation is written by listing its tuples within {},for


example {(A-101 Downtown,500)(A-215,mianus,700)}.

 A general expression in relational algebra is constructed out of


smaller sub expressions.Let E1 and E2be relational algebra
expressions.Then the relational algebra expression:

 E1 U E2

 E1 - E2

 E1 x E 2

 p(E1),where p is a predicate on attributes in E1.

 (E1),where s is a list consisting of some of the attributes in


E1.

 x(E1),where x is the new name for the result of E1.

 The relational algebraic operation are divided into two


groups:Thefitst group includes the set operations.

 Union

 Intersection

 Set difference

 Cartesian product

RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0


Unit – 2 Answers Page 14 of 28
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

 Second group of relational algebraic operation

 Select

 Project

 Rename

 Join

 Division

 Comment on view statement. (April/May 2013)

 A view is object that gives the user a logical view of data from an
underlying table or tables.

 Restrict what userscan view by allowing them to see only a few


attributes/columns from table.

10. View created for the following Reasons:

 Simplifies queries

 Can be queried as a database table

 Provides data security

Creation of Views:

 Database views are created using the CREATE VIEW statement.


Views can be created from a single table, multiple tables, or another
view.

 To create a view, a user must have the appropriate system privilege


according to the specific implementation.

Syntax
CREATE VIEW view_name as
SELECT column1, column2.....
FROM table_name
WHERE [condition];

RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0


Unit – 2 Answers Page 15 of 28
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

Example

Create view on book table which contains two fields title,and author name.

SQL>create view V_book as

Select Title,Author_name

From book;

Title Author_Name
Oracle Arora
DBMS Basu
DOS Sinha
ADBMS Basu
Unix Kapoor
Selecting Data from a View

Example:Display all the titles of books written by author ‘Basu’.

SQL>select Titles from V_Book

Where author_name=’Basu’;

Title
DBMS
ADBMS
Updatable Views

 View can also be used for data manipulation. the user can perform
Insert,update,and the delete operation on the view.

 The views on which data manipulation are calledreadonly views.

Destroying a View

A view can be dropped by using the DROP VIEW command

Syntax:
DROP VIEW viewname;

RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0


Unit – 2 Answers Page 16 of 28
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

Example

DROP VIEW V_Book;

11. What is Tuple? Explain the Tuple Relational Calculus. (April/May 2014)

Definition:
In the context of the database, a tuple is one record (one row)
Tuple Relational Calculus:

 A tuple relational calculus expression is of the form

where is a formula.

Several tuple variables may appear in a formula.

 A tuple variable is said to be a free variable unless it is quantified by a or


a . Then it is said to be a bound variable.
 A formula is built of atoms. An atom is one of the following forms:
o , where is a tuple variable, and r is a relation ( is not
allowed).
o , where and are tuple variables, and and are
attributes, and is a comparison operator ( ).
o , where is a constant in the domain of attribute .
 Formulae are built up from atoms using the following rules:
o An atom is a formula.
o If is a formula, then so are and .
o If and are formulae, then so are ,
and .
o If is a formula containing a free tuple variable , then

 Note some equivalences:


o
o
o

12. Explain Domain Relational Calculus.


RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0
Unit – 2 Answers Page 17 of 28
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

Domain variables take on values from an attribute's domain, rather than


values for an entire tuple.

 An expression is of the form

wherethe represent domain variables, and is a formula.

 An atom in the domain relational calculus is of the following forms


o where is a relation on attributes,
and , are domain variables or constants.
o , where and are domain variables, and is a comparison
operator.
o , where c is a constant.
 Formulae are built up from atoms using the following rules:
o An atom is a formula.
o If is a formula, then so are and .
o If and are formulae, then so are ,
and .
o If is a formula where x is a domain variable, then so
are and .

PART – C QUESTIONS

1. Show any two importance of null values with library information system.
(April /May 2016)

 A value of NULL indicates that the value is unknown. A value of NULL is different
from an empty or zero value.
 No two null values are equal. Comparisons between two null values, or between a
NULL and any other value, return unknown because the value of each NULL is
unknown.
 Null values generally indicate data that is unknown, not applicable, or that the data
will be added later. For example, a customer's middle initial may not be known at
the time the customer places an order.
Following is information about nulls:

RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0


Unit – 2 Answers Page 18 of 28
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

 To test for null values in a query, use IS NULL or IS NOT NULL in the WHERE
clause.
 When query results are viewed in SQL Server Management Studio Code editor, null
values are shown as NULL in the result set.
 Null values can be inserted into a column by explicitly stating NULL in an INSERT
or UPDATE statement, by leaving a column out of an INSERT statement, or when
adding a new column to an existing table by using the ALTER TABLE statement.
 Null values cannot be used for information that is required to distinguish one row in
a table from another row in a table, such as primary keys.

In program code, you can check for null values so that certain calculations are performed
 If it is likely that null values are stored in your data and you do not want null values
appearing in your data, you should create queries and data-modification statements
that either remove NULLs or transform them into some other value.
 When null values are present in data, logical and comparison operators can
potentially return a third result of UNKNOWN instead of just TRUE or FALSE.
This need for three-valued logic is a source of many application errors.
 These tables outline the effect of introducing null comparisons.
The following
Boolean expression to which the NOT operator is table shows the
Evaluates to
applied
results of applying

Important

To minimize maintenance and possible effects on existing queries or reports, you should
minimize the use of null values. Plan your queries and data-modification statements so that
null values have minimal effect.
an AND operator to two Boolean operands.

The following table shows the results of applying an OR operator to two Boolean operands.

RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0


Unit – 2 Answers Page 19 of 28
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

TRUE FALSE

UNKNOWN UNKNOWN

FALSE TRUE

 Reverses, the result of a Boolean operator.The ISO standard uses the keywords IS
NULL and IS NOT NULL to test for the presence of null values.
 Transact-SQL also offers an extension for null processing. If the option
ANSI_NULLS is set to OFF, comparisons between nulls, such as NULL = NULL,
evaluate to TRUE.
Comparisons between NULL and any data value evaluate to FALSE.

2. Explain Relational Model in detail. (Nov 2014)

Relational data model is the primary data model, which is used widely
around the world for data storage and processing. This model is simple and have all
the properties and capabilities required to process data with storage efficiency.

Concepts

 Tables: In relation data model, relations are saved in the format of


Tables. This format stores the relation among entities. A table has rows
and columns, where rows represent records and columns represents the
attributes.

 Tuple: A single row of a table, which contains a single record for that
relation, is called a tuple.

 Relation instance: A finite set of tuples in the relational database


system represents relation instance. Relation instances do not have
duplicate tuples.

 Relation schema: This describes the relation name (table name),


attributes and their names.

 Relation key: Each row has one or more attributes which can identify
the row in the relation (table) uniquely, is called the relation key.

RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0


Unit – 2 Answers Page 20 of 28
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

 Attribute domain: Every attribute has some pre-defined value scope,


known as attribute domain.

Constraints

Every relation has some conditions that must hold for it to be a valid
relation. These conditions are called Relational Integrity Constraints. There are
three main integrity constraints.

 Key Constraints
 Domain constraints
 Referential integrity constraints

Key Constraints:

There must be at least one minimal subset of attributes in the relation, which
can identify a tuple uniquely. This minimal subset of attributes is called key for that
relation. If there is more than one such minimal subset, these are called candidate
keys.

Domain Constraints

Attributes have specific values in real-world scenario. For example, age can
only be positive integer.

Referential Integrity Constraints (Foreign key)

A key attribute of a relation can be referred in other relation, where it is


called foreign key.Referential integrity constraint states that if a relation refers to a
key attribute of a different or same relation, that key element must exist.

3. Explain the structure of Relational Database. (Nov/Dec 2011)

A relational database consists of a collection of tables, each having a unique


name.

 A row in a table represents a relationship among a set of values.Thus


a table represents a collection of relationships.
 There is a direct correspondence between the concept of a table and
the mathematical concept of a relation.
 A substantial theory has been developed for relational databases.

Basic Structure:

RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0


Unit – 2 Answers Page 21 of 28
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

Database Schema:

 We distinguish between a database scheme (logical design) and a


database instance (data in the databaseat a point in time).
 A relation scheme is a list of attributes and their corresponding domains.
 The text uses the following conventions:
o italics for all names
o lowercase names for relations and attributes
o names beginning with an uppercase for relation schemes

Keys:

The notions of superkey, candidate key and primary key all apply to the
relational model.

For example, in Branch-scheme,

 fbnameg is a superkey.
 fbname, bcityg is a superkey.
 fbname, bcityg is not a candidate key, as the superkeyfbnameg is
contained in it.
 fbnameg is a candidate key.
 fbcityg is not a superkey, as branches may be in the same city.
 The primary key for Customer-scheme is fcnameg.

Query Language:

A query language is a language in which a user requests information from a


database. These are typicallyhigher-level than programming languages.

RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0


Unit – 2 Answers Page 22 of 28
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

They may be one of:

 Procedural, where the user instructs the system to perform a


sequence of operations on the database.
 Nonprocedural, where the user species the information desired
without giving a procedure for obtaining the information.

A complete query language also contains facilities to insert and delete tuples
as well as to modify parts ofexisting tuples.

4. Explain the operations used for modifications of database. (Nov 2011)

The content of the database may be modified using the following operations:

 Deletion
 Insertion
 Updating

All these operations are expressed using the assignment operator.

Deletion:

 A delete request is expressed similarly to a query, except instead of


displaying tuples to the user; the selected tuples are removed from the
database.
 Can delete only whole tuples; cannot delete values on onlyparticular
attributes
 A deletion is expressed in relational algebra by:

where r is a relation and E is a relational algebra query

Examples:

Delete all account records in the Perryridge branch

Delete all loan records with amount in the range of 0 to 50

RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0


Unit – 2 Answers Page 23 of 28
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

Insertion:

 To insert data into a relation, we either:specify a tuple to be


insertedwrite a query whose result is a set of tuples to be inserted.
 In relational algebra, an insertion is expressed by:

where r is a relation and E is a relational algebraexpression.

 The insertion of a single tuple is expressed by letting E bea constant


relation containing one tuple

Example:

Insert information in the database specifying that Smith has $1200in


account A-973 at the Perryridge branch

Provide as a gift for all loan customers in the Perryridge branch,


a$200 savings account. Let the loan number serve as the accountnumber for the
new savings account.

Updating:

 A mechanism to change a value in a tuple withoutcharging all values in


the tuple.
 Use the generalized projection operator to do this task.

 Each Fi is either attribute of r, if the Ith attribute is to be updated Fi is an


expression, involving onlyconstants and the attributes of r, which gives
the new value for theattribute

RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0


Unit – 2 Answers Page 24 of 28
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

Examples

Make interest payments by increasing all balances by 5 %Pay all


accounts with balances over $10,000 6 % interest and payall others 5 %

5. Describe the operations of Relational Algebra. (April/May 2013)

Fundamental operations of Relational algebra:

 Select
 Project
 Union
 Set different
 Cartesian product

Select Operation (σ)

Selects tuples that satisfy the given predicate from a relation.

Notation: σp(r)

Where p stands for selection predicate and r stands for relation. These terms
may use relational operators like: =, ≠, ≥, < , >, ≤.

For example:

σsubject="database"(Books)

Project Operation (π)

Projects column(s) that satisfy given predicate.

Notation: πA1, A2, An (r)

Where a1, a2 , an are attribute names of relation r. Duplicate rows are


automatically eliminated, as relation is a set.

For example:

πsubject, author (Books)

RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0


Unit – 2 Answers Page 25 of 28
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

Selects and projects columns named as subject and author from relation
Books.

Union Operation (∪)

Union operation performs binary union between two given relations and is
defined as:

r∪ s = {t | t ∈ r or t ∈ s}

Notation: rUs

Where r and s are either database relations or relation result set.

For examples:

πauthor (Books) ∪ πauthor (Articles)

Set Difference ( − )

The result of set difference operation is tuples which present in one relation
but are not in the second relation.

Where r and s are relations and there output will be defined as:

r Χ s = { q t | q ∈ r and t ∈ s}

Notation: r−s

For example:

πauthor (Books) − π author (Articles)

Cartesian Product (Χ):

Combines information of two different relations into one.

Notation: rΧs

For example:

πauthor = 'tutorialspoint'(Books Χ Articles)

Rename Operation (ρ)

RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0


Unit – 2 Answers Page 26 of 28
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

The rename operation allows us to rename the output relation. 'rename'


operation is denoted with small Greek letter rho ρ.

Notation: ρ x (E)

Where the result of expression E is saved with name of x.

Additional operations are −

 Set intersection
 Assignment
 Natural join

6. What are Mapping Constraints? Explain with example. (April/May 2014)

An E-R scheme may be certain constraints to which the contents of a


database must conform.

Mapping Cardinalitiesexpress the number of entities to which another


entity can be associated via a relationship.

For binary relationship sets between entity sets A and B, the mapping
cardinalitymust be one of:

 One-to-one: An entity in A is associated with at most one entity in B, and


an entity in B is associated with at most one entity in A.

 One-to-many: An entity in A is associated with any number in B. An entity


in B is associated with at most one entity in A.

RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0


Unit – 2 Answers Page 27 of 28
ACADEMIC YEAR: 2016 – 2017 REGULATION CBCS - 2012

 Many-to-one: An entity in A is associated with at most one


entityinB.Anentity in B is associated with any number in A.

 Many-to-many: Entities in A and B are associated with anynumber from


each other.

The appropriate mapping cardinality for a particular relationship set depends


on the real world being modeled.

Existence Dependencies:

If the existence of entity X depends on the existence of entity Y, then X is


saidto be existence dependent on Y.

For example,

 Consider account and transaction entity sets, and a relationship log between
them.
 This is one-to-many from account to transaction.
 If an account entity is deleted, its associated transaction entities must also be
deleted.
 Thus account is dominant and transaction is subordinate.
-----

RAAK/B.SC(cs)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-2ANS/VER 2.0


Unit – 2 Answers Page 28 of 28
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

UCS 51 – DATABASE MANAGEMENT SYSTEM


Unit-3 – Structured Query Language
Type: 100% Theory
Question Bank with Answers
PART – A QUESTIONS

1. Give the use of Date function.( April May 2016)

 The DATE datatype stores date and time information. Although date and time
information can be represented in both character and number datatypes,
the DATE datatype has special associated properties.

 For each DATE value, Oracle stores the following information: century, year,
month, date, hour, minute, and second.

 Specifying the date value as a literal

 Converting a character or numeric value to a date value with the TO_DATE


function

2. What is meant by a transaction? (April/May-2013 & Nov-2014)

Transaction is a unit of program execution that accesses and possibly updated


various data items.

3. What is unique-key constraint? (April/May-2013)

The UNIQUE constraint uniquely identifies each record in a database table. The
UNIQUE KEY constraint provides a guarantee for uniqueness for a column or set of
columns.

4. Define View command. (Nov-2012 & April/May-2014)

A view is nothing more than a SQL statement that is stored in the database with
an associated name. A view is actually a composition of a table in the form of a
predefined SQL query.

5. What are DDL commands?(Nov/Dec-2011,April May 2016)

 Create
 Alter
 Drop
RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0
Unit – 3 Answer Page 1 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

 Truncate

6. Define varchar functions. (Nov/Dec-2011)

A varchar or Variable Character Field is a set of character data of indeterminate


length. The term varchar refers to a data type of a field (or column) in a database
management system which can hold letters and numbers.

7. Write the structure of select command.(April/May-2014)

Select A1, A2…………., An From R1, R2……………, Rm Where P

8. What are the parts of SQL language?

The SQL language has several parts:

 Data Definition language


 Data manipulation language
 View definition
 Transaction control
 Embedded SQL
 Integrity
 Authorization

9. What are the three classes of SQL expression?

SQL expression consists of three clauses:

 Select
 From
 where

10. What is the use of rename operation?

Rename operation is used to rename both relations and a attributes. It uses the as
clause, taking the form:

Old-name as new-name

11. Define tuple variable?

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0


Unit – 3 Answer Page 2 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

Tuple variables are used for comparing two tuples in the same relation. The tuple
variables are defined in the from clause by way of the as clause.

12. List the string operations supported by SQL?

 Pattern matching Operation


 Concatenation
 Extracting character strings
 Converting between uppercase and lower case letters.

13. List the set operations of SQL?

 Union
 Intersect operation
 Set Difference

 Cartesian Product

14. What is the use of Union and intersection operation?

Union: The result of this operation includes all tuples that are either in r1 or in r2
or in both r1 and r2.Duplicate tuples are automatically eliminated.

Intersection: The result of this relation includes all tuples that are in both r1 and
r2.

15. What are aggregate functions? And list the aggregate functions supported by
SQL?

Aggregate functions are functions that take a collection of values as input and
return a single value.

Aggregate functions supported by SQL are

 Average: avg()
 Minimum: min()
 Maximum: max()
 Total: sum()
 Count: count()

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0


Unit – 3 Answer Page 3 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

16. What is the use of group by clause?

Group by clause is used to apply aggregate functions to a set of tuples. The


attributes given in the group by clause are used to form groups. Tuples with the same
value on all attributes in the group by clause are placed in one group.

17. What is the use of sub queries?

A sub query is a select-from-where expression that is nested with in another


query. A common use of sub queries is to perform tests for set membership, make set
comparisons, and determine set cardinality.

18. What is view in SQL? How is it defined?

Any relation that is not part of the logical model, but is made visible to a user as a
virtual relation is called a view.

We define view in SQL by using the create view command. The form of the
create view command is

Create view v as <query expression>

19. What is the use of with clause in SQL?

The WITH clause provides a way of defining a temporary view whose definition
is available only to the query in which the WITH clause occurs.

20. List the table modification commands in SQL?

 Deletion
 Insertion
 Updates
 Update of a view

21. List out the statements associated with a database transaction?

 Commit work
 Rollback work

22. What is transaction?

Transaction is a unit of program execution that accesses and possibly updated


various data items.

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0


Unit – 3 Answer Page 4 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

23. List the SQL domain Types?

SQL supports the following domain types.

1) Char(n) 2) varchar(n) 3) int 4) numeric(p,d) 5) float(n)

6) date.

PART – B QUESTIONS

1. Explain nested sub queries.(April/May 2016)


 SQL provides a mechanism for nesting subqueries .A sub query is a select from
where expression that is nested within another query.
 Mostly subqueries are used to perform tests for set membership to make set
comparisons and determine set cardinality.
1) IN
The in connective tests for set membership ,where the set is a collection of values
produced by select clause.
Examples:
Select title,Author_name,Publisher_name,pub_year from book where
Pub_year in(‘2000’,’2002’,’2004’);

Title Author_name Publisher_name Pub_year


Oracle Arora PHI 2004
DBMS Basu Technical 2004
ADBMS Basu Technical 2004
Unix Kapoor SciTech 2000

2)NOT IN
The not in connective tests for the absence of set membership
Examples:
Select Title,Author_name,Publisher_name,Pub_year from book where pub_year not
in(‘2002’,’2004’,’2005’)
Output:
Title Author_name Publisher_name Pub_year
DOS Sinhaa Nirali 2003

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0


Unit – 3 Answer Page 5 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

Unix Kapoor SciTech 2000

2. Explain rename operations with an example. (April/May-2013)

 The RENAME operator returns an existing relation under a new name.

 This is a Mechanism used for renaming both relations and attributes.

 This renaming is highly useful when one has to compare a set of tuples of the
same relation with other tuples of that relation.

 It has the following general format:

Old name as new-name

The ‘as’ clauses can appear in both the select and from clauses.

For example:

Select Title,Unit_price*1.15 as New_price from Book

TITLE NEW_PRICE
Oracle 458.85
DBMS 460
DOS 287.5
ADBMS 517.5
Unix 345

Note:

 Sometimes we want to change the name of a column.

 To do this in SQL, we specify that we want to change the structure of the table
using the ALTER TABLE command.

 The exact syntax for each database is as follows:

ALTER TABLE "table_name" RENAME COLUMN "column 1" TO "column 2";

For example:

Alter table student rename column phone to contact_no;

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0


Unit – 3 Answer Page 6 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

3. What is meant by dynamic SQL?(April/May-2013)

 Example:SQL defines standards for embedding dynamic SQL calls in a host


language,such as C,as in the following example:

Char*sqlprog=”Update account

set balance=balance*1.05

where acc_no=?”

EXEC SQL prepare dynprog from :sqlprog;

Char acc[10]=”101”;

EXEC SQL execute dynprog using:acc;

The dynamic SQL program contains acc_no=?,which is a place holder for a value that is
provided when the SQL program is executed.

 Dynamic SQL refers to SQL code that is generated within an application or


from the system tables and then executed against the database to manipulate
the data.

 The SQL code is not stored in the source program, but rather it is generated
based on user input.

 This can include determining not only what objects are involved, but also the
filter criteria and other qualifiers that define the set of data being acted on.

 Dynamic SQL also lets you execute data definition language (DDL)
statements and other SQL statements that are not supported in purely static
SQL programs.

Methods of Dynamic SQL:

The Four Methods of Dynamic SQL

Method Limitations Kind of SQL Statement


1 SQL statement cannot be a query, and it cannot Non-query with no host
contain any input host variables. variables. Good for data
definition statements

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0


Unit – 3 Answer Page 7 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

2 SQL statement cannot be a query. Number of Non-query with a known number


input host variables and the datatypes of the host of input host variables
variables must be known at precompile time.
3 Number of select-list items, number of input host Query with known number of
variables, and the datatypes of the host variables select-list items and input host
must be known at precompile time. variables
4 None. The number of select-list items, number of Query with unknown number of
input host variables, and the datatypes of the select-list items and input host
input host variables can be unknown until run variables. The input host variable
time. datatypes can also be unknown.

4. Give the basic structure of a SQL Expression.(Nov-2012)

 Basic structure of an SQL expression consists of select, from and where clauses.

 Select clause lists attribute to be copied - corresponds to relational algebra project.

 From clause corresponds to Cartesian product - lists relations to be used.

 Where clause corresponds to selection predicate in relational algebra.

 Typical query has the form

Select A1,A2, ……., An From R1, R2,…….., Rn Where P

where each Ai represents an attribute, each Ri a relation, and P is a predicate.The list


of attributes can be replaced with a * to select all.

i)Select Clause

This command is used to display all fields/or set of selected fields for all/selected
records from a relation.

Ex: Select Publisher_name from book;

Publisher_Name
PHI
Technical
Nirali
Technical
SciTech

ii)Where Clause
The where clause is used to select specific rows satisfying given predicate.
RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0
Unit – 3 Answer Page 8 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

Ex:Select title from book where pub_year=’2004’


TITLE

Oracle

DBMS

ADBMS

5. What are Duplicates?(Nov-2012)

 Formal query languages are based on mathematical relations. Thus no


duplicates appear in relations.

 As duplicate removal is expensive, SQL allows duplicates.

 To remove duplicates, we use the distinct keyword.

 To ensure that duplicates are not removed, we use the all keyword.

 Multiset (bag) versions of relational algebra operators.

 if there are copies of tuples in , and satisfies selection , then there


are copies of in .

 for each copy of tuple in , there is a copy of tuple in .

 if there are copies of tuple in , and copies of tuple in , there


is copies of tuple in .

 An SQL query of the form

Select A1,A2, ……., An From R1, R2,…….., Rn Where P

is equivalent to the algebra expression


Using the multiset
versions of the relational operators , and .

6. Discuss about a) Primary key b) Candidate key.(Nov/Dec-2011)

a) Primary key:

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0


Unit – 3 Answer Page 9 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

 A primary key is a field in a table which uniquely identifies each row/record


in a database table.

 Primary keys must contain unique values. A primary key column cannot have
NULL values.

 A table can have only one primary key, which may consist of single or
multiple fields.

 When multiple fields are used as a primary key, they are called a composite
key.

Create Primary Key:

Here is the syntax to define ID attribute as a primary key in a CUSTOMERS


table.

CREATE TABLE CUSTOMERS(


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);

 To create a PRIMARY KEY constraint on the "ID" column when


CUSTOMERS table already exists, use the following SQL syntax:

ALTER TABLE CUSTOMER ADD PRIMARY KEY (ID);

 For defining a PRIMARY KEY constraint on multiple columns, use the


following SQL syntax:

CREATE TABLE CUSTOMERS (


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID, NAME) );

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0


Unit – 3 Answer Page 10 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

 To create a PRIMARY KEY constraint on the "ID" and "NAMES" columns


when CUSTOMERS table already exists, use the following SQL syntax:

ALTER TABLE CUSTOMERS ADD CONSTRAINT


PK_CUSTID PRIMARY KEY (ID, NAME);

Delete Primary Key:

To clear the primary key constraints from the table, Use Syntax:

ALTER TABLE CUSTOMERS DROP PRIMARY KEY;

b) Candidate key:

 Candidate keys are defined as the set of fields from which primary key can be
selected.

 It is an attribute or set of attribute that can act as a primary key for a table to
uniquely identify each record in that table.

 A candidate key is a column, or set of columns, in a table that can uniquely


identify any database record without referring to any other data.

 Each table may have one or more candidate keys, but one candidate key is
special, and it is called the primary key. This is usually the best among the
candidate keys.

 Attribute needs to satisfy the following conditions

o The relation does not have two distinct tuples with the same values for
these attributes

o There is no proper subset of these attributes for which holds

7. Explain the character functions with examples.(April/May-2014)

A character or string function is a function which takes one or more characters or


numbers as parameters and returns a character value.

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0


Unit – 3 Answer Page 11 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

Basic string functions offer a number of capabilities and return a string value as a
result set.

CONCAT

The CONCAT function is used to concatenate strings. The || operator can also be
used to append one string to another.

SELECT MAX(LENGTH(first_name|| last_name))


FROM employees

LENGTH

The LENGTH function returns the number of characters (including spaces and
hidden characters) in the string passed to it.

Select length(‘Tecnology’) from dual;

Output:10

Code Sample:

SELECT
first_name,
last_name,
LENGTH(first_name),
LENGTH(last_name)
FROM employees
WHERE LENGTH(first_name||last_name) IN
(
SELECT MAX(LENGTH(first_name|| last_name))
FROM employees
);

INSTR

 The INSTR function is used to determine if a given string contains a specified


substring.
 The function returns an integer representing the position of the substring (if
found).
 If the string is not found, zero is returned.

REPLACE

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0


Unit – 3 Answer Page 12 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

The REPLACE function is used to substitute one substring for another within a
given text string.

Oracle also includes a similar function called TRANSLATE that can be used to perform
several single-character, one-to-one substitutions.

Select Replace(‘RocK’,’oc’,’AA’) from dual;

Output:RAAK

UPPER

The UPPER function is used to convert all of the character in a string to upper
case.

Select Upper(‘Database Management Systems’) from dual;

Output: DATABASE MANAGEMENT SYSTEMS

LOWER

The LOWER function is used to convert all of the character in a string to lower
case.

Select Lower(‘RDBMS’) from dual;

Output:rdbms

INITICAP

The INITCAP function is used to capitalize the first character in each substring
that appears as an independent word in the string. It sets all remaining characters to lower
case.

Code Sample:

SELECT last_name,
UPPER(last_name),
LOWER(last_name),
INITCAP(last_name)
FROM employeess;
8. Explain with example DDL.(April/May-2014)

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0


Unit – 3 Answer Page 13 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

 DDL (Data Definition Language) statements are used to build and modify the
structure of your tables and other objects in the database.
 Some of the DDL commands are CREATE, ALTER, DROP and USE.

CREATE statements

A CREATE statement is used to create table, index, stored query or database.

CREATE TABLE statement

Perhaps the most common CREATE command is the CREATE


TABLE command. The typical usage is:

CREATE TABLE [table_name] ( [column_definitions] ) [table parameters]

For example:

CREATE TABLE employees (


id INTEGER PRIMARY KEY,
first_name VARCHAR(50) NULL,
last_name VARCHAR(75) NOT NULL,
dateofbirth DATE NULL
);

DROP statement

The DROP command of the Data Definition Language, allows us to remove entire
database, table, view or an index objects from our DBMS.

SYNTAX:

DROP object_type object_name

For example:

DROP TABLE employee

ALTER statement

 The ALTER statement helps to modify an existing DB object.

 Once we've created a table within a database, you may wish to modify the
definition of it.
 The ALTER command allows you to make changes to the structure of a table
without deleting and recreating it.

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0


Unit – 3 Answer Page 14 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

SYNTAX:

ALTER object_type object_name paramerters

Eg:

ALTER TABLE employee ADD salary money null

USE statement

The USE command allows us to specify the database we wish to work with within
your DBMS.

For example:

If we're currently working in the department database and want to issue some commands
that will affect the employee’s database,

USE employees

It's important to always be conscious of the database you are working in before issuing
SQL commands that manipulate data.

9. What is Embedded SQL? Explain. (April/May-2014,2016)

 SQL provides a powerful declarative query language. However, access to a


database from a general-purpose programming language is required.

 SQL is not as powerful as a general-purpose programming language. There


are queries that cannot be expressed in SQL, but can be programmed in C,
Fortran, Pascal, Cobol, etc.

 Non declarative actions -- such as printing a report, interacting with a user, or


sending the result to a GUI -- cannot be done from within SQL.

 The SQL standard defines embedding of SQL as embedded SQL and the
language in which SQL queries are embedded is referred as host language.

 The result of the query is made available to the program one tuple (record) at
a time.

 To identify embedded SQL requests to the preprocessor, we use EXEC SQL


statement:

EXEC SQL embedded SQL statement END-EXEC

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0


Unit – 3 Answer Page 15 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

Note: A semi-colon is used instead of END-EXEC when SQL is embedded in C or


Pascal.

Embedded SQL statements: declare cursor, open, and fetch statements.

EXEC SQL

declare c cursor for

select cname, ccity

from deposit, customer

where deposit.cname = customer.cname

and deposit.balance > :amount

END-EXEC

where amount is a host-language variable.

Statements:

 To Open - EXEC SQL open c END-EXEC


 To Fetch - EXEC SQL fetch c into :cn, :cc END-EXEC
 To Close - EXEC SQL close c END-EXEC

Note: Embedded SQL can execute any valid update, insert, or delete statements.

10. Write short notes on SQL.(Nov-2014)

 SQL is Structured Query Language, which is a computer language for storing,


manipulating and retrieving data stored in relational database.
 SQL is the standard language for Relation Database System.
 All relational database management systems like MySQL, MS Access, Oracle,
Sybase, Informix, postgres and SQL Server use SQL as standard database
language.
 Also, they are using different dialects, such as:
o MS SQL Server using T-SQL,
o Oracle using PL/SQL,
o MS Access version of SQL is called JET SQL (native format) etc.

Why SQL?

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0


Unit – 3 Answer Page 16 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

 Allows users to access data in relational database management systems.


 Allows users to describe the data.
 Allows users to define the data in database and manipulate that data.
 Allows embedding within other languages using SQL modules, libraries &
pre-compilers.
 Allows users to create and drop databases and tables.
 Allows users to create view, stored procedure, functions in a database.
 Allows users to set permissions on tables, procedures, and views

History:

 1970 -- Dr. Edgar F. "Ted" Codd of IBM is known as the father of relational
databases. He described a relational model for databases.
 1974 -- Structured Query Language appeared.
 1978 -- IBM worked to develop Codd's ideas and released a product named
System/R.
 1986 -- IBM developed the first prototype of relational database and
standardized by ANSI.

SQL Architecture:

SQL Commands:

The standard SQL commands to interact with relational databases are CREATE,
SELECT, INSERT, UPDATE, DELETE and DROP. These commands can be classified
into groups based on their nature:

Command Description

CREATE Creates a new table, a view of a table, or other object in database

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0


Unit – 3 Answer Page 17 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

ALTER Modifies an existing database object, such as a table.

DROP Deletes an entire table, a view of a table or other object in the


database.

SELECT Retrieves certain records from one or more tables

INSERT Creates a record

UPDATE Modifies records

DELETE Deletes records

GRANT Gives a privilege to user

REVOKE Takes back privileges granted from user

11. What is Function? List out few Built-in SQL functions.(Nov-2014)

Numeric Functions

Function Input Argument Value Returned


ABS ( m ) m = value Absolute value of m
MOD ( m, n ) m = value, n = divisor Remainder of m divided by n
POWER ( m, n ) m = value, n = exponent m raised to the nth power
m = value, n = number of m rounded to the nth decimal
ROUND ( m [, n ] )
decimal places, default 0 place
SQRT ( n ) n = value positive square root of n
EXP ( n ) n = value e raised to the power n

Ex:

select round (83.28749, 2) from dual;


select sqrt (3.67) from dual;
select power (2.512, 5) from dual;

String Functions

Function Input Argument Value Returned


LOWER ( s ) s = character string All letters are changed to lowercase.
UPPER ( s ) s = character string All letters are changed to uppercase.

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0


Unit – 3 Answer Page 18 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

s1 and s2 are character Concatenation of s1 and s2.


CONCAT ( s1, s2 )
strings Equivalent to s1 || s2
Returns s with characters removed up
s is a character string
LTRIM ( s [, set ] ) to the first character not in set;
and set is a set of characters
defaults to space
Returns s with final characters
s is a character string
RTRIM ( s [, set ] ) removed after the last character not in
and set is a set of characters
set; defaults to space
s = character string,
REPLACE ( s, Returns s with every occurrence of
search_s = target string,
search_s [, replace_s ] search_s in s replaced by replace_s;
replace_s = replacement
) default removes search_s
string
s = character string, m = Returns a substring from s, beginning
SUBSTR ( s, m [, n ] ) beginning position, n = in position m and n characters long;
number of characters default returns to end of s.
LENGTH ( s ) s = character string Returns the number of characters in s.

Eg:

select concat ('Alan', 'Turing') as "NAME" from dual;


select 'Alan' || 'Turing' as "NAME" from dual;
select initcap ("now is the time for all good men to come to the aid of the
party") as "SLOGAN" from dual;
select substr ('Alan Turing', 1, 4) as "FIRST" from dual;

Date and Time Functions

Function Input Argument Value Returned


d = date, n = number of
ADD_MONTHS ( d, n ) Date d plus n months
months
Date of the last day of the month
LAST_DAY ( d ) d = date
containing d
d = date, day = day of the Date of the first day of the week
NEXT_DAY ( d, day )
week after d
SYSDATE none Current date and time
GREATEST ( d1, d2, ...,
d1 ... dn = list of dates Latest of the given dates
dn )
LEAST ( d1, d2, ..., dn ) d1 ... dn = list of dates Earliest of the given dates

Date Formats

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0


Unit – 3 Answer Page 19 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

Format Code Description Range of Values


DD Day of the month 1 - 31
DY Name of the day in 3 uppercase letters SUN, ..., SAT
Complete name of the day in uppercase,
DAY SUNDAY, ..., SATURDAY
padded to 9 characters
MM Number of the month 1 - 12
MON Name of the month in 3 uppercase letters JAN, ..., DEC
Name of the month in uppercase padded to a JANUARY, ...,
MONTH
length of 9 characters DECEMBER
YY or YYYY Two or four digit year 71 or 1971
HH:MI:SS Hours : Minutes : Seconds 10:28:53
HH 12 or HH
Hour displayed in 12 or 24 hour format 1 - 12 or 1 - 24
24

PART – C QUESTIONS

1. Explain in detail the various Aggregate Functions. (April /May 2016,Nov 2012)

Aggregate functions are functions that take a collection of values as input and
return a single value.SQL offers five built-in aggregate functions:

 Average:avg

 Minimum:min

 Maximum:max

 Total:sum

 Count:count

Useful aggregate functions:

1. AVG ():

Returns the average of the values in a group. Null values are ignored.
Syntax:
AVG ( [ DISTINCT | ALL] n)
Example:
Select avg (Unit_price) “Average Price” from book;

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0


Unit – 3 Answer Page 20 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

Average Price
359.8

MAX ():

Returns the largest value


Syntax:
MAX ([ALL|DISTINCT] expression)
Eg:
SELECT MAX(salary)FROM Employee;

MIN ():

Returns the minimum value in the expression.


Syntax:
MIN ([ALL|DISTINCT] expression)
Eg:
SELECT MIN(salary)FROM Employee;

SUM ():

Returns the sum of all the values, or only the DISTINCT values, in the
expression. SUM can be used with numeric columns only. Null values are ignored.
Syntax:
SUM ([ALL|DISTINCT] expression)
Eg:
SELECT SUM(price) FROM Employee;

COUNT ():

Returns the number of rows


Syntax:
COUNT ({[[ALL |DISTINCT] expression] | *})
Eg:
SELECT COUNT(*) FROM Employee;

FIRST () - Returns the first value

LAST () - Returns the last value

2. Explain the various clauses of select statement with example. (April /May 2013)

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0


Unit – 3 Answer Page 21 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

The SQL SELECT statement queries data from tables in the database. The
statement begins with the SELECT keyword. The basic SELECT statement has 3 clauses:

 SELECT- clause specifies the table columns that are retrieved.

 FROM - clause specifies the tables accessed.

 WHERE - clause specifies which table rows are used. The WHERE clause
is optional; if missing, all table rows are used.

SELECT Clause

The SELECT clause is mandatory. It specifies a list of columns to be retrieved


from the tables in the FROM clause. It has the following general format:

SELECT [ALL|DISTINCT] select-list

 Select-list is a list of column names separated by commas. The ALL and


DISTINCT specifies are optional.

 DISTINCT specifies that duplicate rows are discarded.

 A duplicate row is when each corresponding select-list column has the


same value. The default is ALL, which retains duplicate rows.

For example,

sno name city


S1 Pierre Paris
S2 John London
S3 Mario Rome

SELECT name FROM Customer WHERE city='Rome'

This query accesses rows from the table Customer. It then filters those rows
where the city column contains Rome. Finally, the query retrieves the name column from
each filtered row. Using the example s table, this query produces:

name
Mario

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0


Unit – 3 Answer Page 22 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

FROM Clause:

The FROM clause always follows the SELECT clause. It lists the tables accessed
by the query.

For example,

SELECT * FROM Customer

 When the From List contains multiple tables, commas separate the table
names.

 Like columns in the select list, tables in the from list can be renamed

WHERE Clause:

 The WHERE clause is optional, it always follows the FROM clause.


 The WHERE clause filters rows from the FROM clause tables.
 Omitting the WHERE clause specifies that all rows are used.
 Following the WHERE keyword is a logical expression, also known as a
predicate.
 The predicate evaluates to a SQL logical value -- true, false or unknown.

The most basic predicate is comparisons are as follows

> -- greater than


< -- less than
>= -- greater than or equal to
<= -- less than or equal to
= -- equal to

For example,

SELECT * FROM sp WHERE qty >= 200

sno pno qty


S2 P1 200
S3 P1 1000
S3 P2 200

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0


Unit – 3 Answer Page 23 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

3. Explain the Modification of the Database.(Nov/Dec-2011)

The SQL Modification Statements make changes to database data in tables and
columns. There are 3 modification statements:

 INSERT Statement -- add rows to tables

 UPDATE Statement -- modify columns in table rows

 DELETE Statement -- remove rows from tables

INSERT Statement:

 The INSERT Statement adds one or more rows to a table.

 It has two formats:

INSERT INTO table-1 [(column-list)] VALUES (value-list)

and,

INSERT INTO table-1 [(column-list)] (query-specification)

VALUES Clause

 The VALUES Clause in the INSERT Statement provides a set of values to


place in the columns of a new row.

 It has the following general format:

VALUES ( value-1 [, value-2] ... )

Value-1 and value-2 are Literal Values or Scalar Expressions involving literals.

Examples

INSERT INTO p (pno, color) VALUES ('P4', 'Brown')

Before After

pno descr color pno descr Color


=>
P1 Widget Blue P1 Widget Blue
P2 Widget Red P2 Widget Red

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0


Unit – 3 Answer Page 24 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

P3 Dongle Green P3 Dongle Green


P4 NULL Brown

INSERT INTO sp SELECT s.sno, p.pno, 500 FROM s, p WHERE


p.color='Green' AND s.city='London'

Before After
sno pno qty sno pno qty
S1 P1 NULL S1 P1 NULL
S2 P1 200 S2 P1 200
=>
S3 P1 1000 S3 P1 1000
S3 P2 200 S3 P2 200
S2 P3 500
UPDATE Statement

 The UPDATE statement modifies columns in selected table rows.

 It has the following general format:

UPDATE table-1 SET set-list [WHERE predicate]

SET Clause

 The SET Clause in the UPDATE Statement updates (assigns new value to)
columns in the selected table rows.

 It has the following general format:

SET column-1 = value-1 [, column-2 = value-2] ...

 Column-1 and column-2 are columns in the Update table.

 Value-1 and value-2 are expressions that can reference columns from the update
table.

Examples

UPDATE sp SET qty = qty + 20

Before After
sno pno qty => sno pno qty
RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0
Unit – 3 Answer Page 25 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

S1 P1 NULL S1 P1 NULL
S2 P1 200 S2 P1 220
S3 P1 1000 S3 P1 1020
S3 P2 200 S3 P2 220

UPDATE s SET name = 'Tony', city = 'Milan' WHERE sno = 'S3'

Before After
sno name city sno name city
S1 Pierre Paris S1 Pierre Paris
=>
S2 John London S2 John London
S3 Mario Rome S3 Tony Milan

DELETE Statement

 The DELETE Statement removes selected rows from a table.

 It has the following general format:

DELETE FROM table-1 [WHERE predicate]

Examples

DELETE FROM sp WHERE pno = 'P1'

Before After
sno pno qty sno pno qty
S1 P1 NULL S3 P2 200
S2 P1 200 =>
S3 P1 1000
S3 P2 200

DELETE FROM p WHERE pno NOT IN (SELECT pno FROM sp)

Before After
pno descr color pno descr color
P1 Widget Blue => P1 Widget Blue
P2 Widget Red P2 Widget Red
RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0
Unit – 3 Answer Page 26 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

P3 Dongle Green

4. Based on the following data write SQL Query For emp_table.(April/May-2014)

Perks(based
Emp_id Name Sal HRA DA Loans
of sales)
E1001 John $10000 $900 $500 $3000 $1500
E1002 Dominic $20000 $1500 $1000 $4000 $2300
E1003 Lawrance $10000 $900 $500 $4000 $2000

a) Show the list of employees.

Select * from emp_table.

b) Show the salary of Dominic.

Select Sal from emp_table.

c) Show the employee name who have loans above $1200.

Select Name from emp_table where Loans>$1200

d) Show the employee name who gets perks below $2000.

Select Name from emp_table where Perks<$2000

e) Delete the details of Mr. John.

Delete from emp_table where emp_id=E1001

5. Explain the various numerical functions used in SQL.(Nov-2014)

SQL numeric functions are used primarily for numeric manipulation and/or
mathematical calculations. The following table details the numeric functions:

Function Description

ABS( numeric_exp ) Returns the absolute value of numeric_exp.

CEILING( numeric_exp ) Returns the smallest integer greater than or equal


to numeric_exp. The return value is of the same data type
as the input parameter.

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0


Unit – 3 Answer Page 27 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

COS( float_exp ) Returns the cosine of float_exp, where float_exp is an


angle expressed in radians.

COT( float_exp ) Returns the cotangent of float_exp, where float_exp is an


angle expressed in radians.

DEGREES( numeric_exp ) Returns the number of degrees converted


from numeric_exp radians.

EXP( float_exp ) Returns the exponential value of float_exp.

FLOOR( numeric_exp ) Returns the largest integer less than or equal


to numeric_exp. The return value is of the same data type
as the input parameter.

LOG( float_exp ) Returns the natural logarithm of float_exp.

LOG10( float_exp ) Returns the base 10 logarithm of float_exp.

MOD( integer_exp1, integer_exp2)( Returns the remainder (modulus) of integer_exp1 divided


by integer_exp2.

PI( ) Returns the constant value of pi as a floating-point value.

POWER( numeric_exp, integer_exp) Returns the value of numeric_exp to the power


of integer_exp.

RADIANS( numeric_exp ) Returns the number of radians converted


from numeric_exp degrees.

RAND([integer_exp]) Returns a random floating-point value


using integer_exp as the optional seed value.

ROUND( numeric_exp, integer_exp) Returns numeric_exp rounded to integer_exp places right


of the decimal point. If integer_exp is
negative, numeric_exp is rounded to |integer_exp| places
to the left of the decimal point.

SIGN( numeric_exp ) Returns an indicator of the sign of numeric_exp.


If numeric_exp is less than zero, –1 is returned.
If numeric_exp equals zero, 0 is returned.
If numeric_exp is greater than zero, 1 is returned.

SIN( float_exp ) Returns the sine of float_exp, where float_exp is an angle


expressed in radians.

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0


Unit – 3 Answer Page 28 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

SQRT( float_exp ) Returns the square root of float_exp.

TAN( float_exp ) Returns the tangent of float_exp, where float_exp is an


angle expressed in radians.

-----

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-3 ANS/VER 1.0


Unit – 3 Answer Page 29 of 29
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

UCS 51 – DATABASE MANAGEMENT SYSTEM


Unit-4 – Normalization
Type: 100% Theory
Question Bank with Answers

Syllabus:
UNIT IV: Relational Database Design – Pitfalls – Normalization Using Functional Dependencies
– First Normal Form – Second Normal Form – Third Normal Form – Fourth Normal Form and
BCNF.

PART A – QUESTIONS

1. What is Pitfalls?(April/May 2016)


Creating an effective design for a relational database is a key element in building a reliable
system. There is no one "correct" relational database design for any particular project, and
developers must make choices to create a design that will work efficiently. There are a few
common design pitfalls that can harm a database system. Watching out for these errors at
the design stage can help to avoid problems later on.
2. What is called as Normalization? (Nov 2013)
Normalization is an essential part of database design.A good understanding of the
semantics of data helps the designer to build efficient design using the concept of
normalization.
3. What is BCNF? (Nov 2013) (Nov 2012)
A Relationship is said to be in BCNF if it is already in 3NF and the left hand side of every
dependency is a candidate key.

4. Define the term Functional Dependency. (April/May 2014) (Nov/Dec 2011)


 A Functional Dependency describes a relationship between attributes within a
single relation.
 An attribute is functionally dependent on another if we can use the value of one
attribute to determine the value of another.

RAAK/B.SC(CS)/M.USHA/III YEAR/V SEMESTER/UCS 51 /DATABASE


MANAGEMENT SYSTEM/UNIT-IV QUESTION AND ANSWER
Unit – 4 Question and Answer Page 1 of 17
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

Example: Branch name -> Asset.

5. What do you understand about Trivial Functional Dependency? (April/May 2013)


A trivial functional dependency occurs when you describe a of an attribute on a
collection of attributes that includes the original attribute.
Examples: For example, “{A, B} -> B” is a trivial functional dependency as is “{name,
SSN} -> SSN”.

6. Define Partial Dependency? (Nov 2012)


If any proper subsets of the key determine any of the non-key attributes then there exists a
partial dependency.
Example: Given a Relation R(A,B,C,D) Functional Dependency : AB->CD
Then, A->C : is a partial Dependency
A->D : is a partial Dependency
B->C : is a partial Dependency
B->D : is a partial Dependency

7. What are the categories of Normalization? (April/May 2014)


 First Normal Form(1NF)
 Second normal form(2NF)
 Third normal form(3NF)
 Boyce-Codd normal form(BCNF)
 Fourth normal form(4NF)
 Fifth normal form(5NF)

8. What is Third Normal Form? (Nov 2014)


 A Relation is in third normal form (3NF) if it is in second normal form and it
contains no transitive dependencies.
 i.e If a table contains transitive dependency, then it is not in 3NF, and the table must
be split to bring it into 3NF
9. What is Atomic in 1NF?
 In First normal form, each cell in the table can contain only one value (atomic
i.e.indivisible units) and it cannot be decomposed into smaller pieces.

RAAK/B.SC(CS)/M.USHA/III YEAR/V SEMESTER/UCS 51 /DATABASE


MANAGEMENT SYSTEM/UNIT-IV QUESTION AND ANSWER
Unit – 4 Question and Answer Page 2 of 17
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

 It should not contain repeating group.


10. What is Extraneous?
An attribute of a functional dependency is said to be extraneous if we can remove it
without changing the closure of the set of functional dependencies.

11. What is Lossy and Lossless - Join Decomposition ?


Eg: For relation R(x,y,z) there can be 2 subsets:R1(x,z) and R2(y,z)
If we union R1 and R2, we get R = R1 U R2
Due to the loss of information, we call decomposition of R into R1 and R2 a lossy join
decomposition.
A decomposition that is not a lossy-join decomposition is a lossless-join decomposition.

12. What is 2NF?


A relation is in the second Normal form if it is the first normal form at all non-key
attributes are fully functionally depend primary key.

13. What is 4NF?


A relation in a Fourth Normal Form if and only if for every one of its non-trivial
multivalued dependency.
X->->Y, X is the super key, X is either a candidate key or a super key.

14. What is Multivalued Dependency?


Multivalued dependencies (MVD s)’ express a condition among tuples of a relation that
exists when the relation is trying to represent more than one many‐many relationship.
Example: Address (Door No, Street,City,State)

15. What is Super Key?


A super key is a set of one or more attributes or columns which are used to identify a
row(tuple) uniquely.
Example : Emp_no and name is a super key.

RAAK/B.SC(CS)/M.USHA/III YEAR/V SEMESTER/UCS 51 /DATABASE


MANAGEMENT SYSTEM/UNIT-IV QUESTION AND ANSWER
Unit – 4 Question and Answer Page 3 of 17
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

16. List out the Armstrong’s Axioms rule.


Reflexivity: If Y is a subset of X, then X → Y
Augmentation: If X → Y, then XZ → YZ
Transitivity: If X → Y and Y → Z, then X → Z

17. What is Dependency – Preserving Decomposition?


Since losing a dependency means, that the corresponding constraint can be check only
through natural join of the appropriate resultant relation in the decomposition.
Example: Decomposition of R: R1=(A, B) R2=(B, C)
F1= {A->B, A->A, B->B, AB->AB} F2= {B->B, C->C, B->C, BC->BC}
F’= F1’ U F2’ = {A->B, B->C, trivial dependencies} In F’ all the original dependencies
occur, so this decomposition preserves dependencies.

18. Mention the two Generating Dependencies?


 Functional Dependencies(Equality- Generating Dependencies).
 Multivalued Dependencies(Tuple- Generating Dependencies)

19. List out the Disadvantages of if a table is not in 1NF.


 Data becomes less flexible.
 Wastage of memory.
 Difficult to search.

20. List out the Disadvantages of if a table is not converted to 2nd normal form.
 Data Redundancy (Repetition of information).
 Difficult to change data because of redundancy.

21. Define Fully Functional Dependency.


Given a relation R and Functional Dependency X->Y, Y is fully functionally dependent on
x and there should not be any Z->Y, where Z is a proper subset of X.

22. Write an example for to convert from 1 NF to 2 NF.


Student(rollno,name,dob,address)
Here, address field may contain a DoorNo,street,city,pincode.

RAAK/B.SC(CS)/M.USHA/III YEAR/V SEMESTER/UCS 51 /DATABASE


MANAGEMENT SYSTEM/UNIT-IV QUESTION AND ANSWER
Unit – 4 Question and Answer Page 4 of 17
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

Address is a non – atomic attribute.


So, Address(add_id,DoorNo,street,city,pincode)
(rollno,name,dob,add_id)

23. Write an example for to convert from Un-Normalized to 1 NF.

EmpID Empname Month Sales BankId Bankname


E01 Arun Jan 1000 B01 SBI
Feb 1200
E02 Bala Jan 1500 B02 ICICI
E03 Chitra Feb 1400 B01 SBI
EmpID Empname Month Sales BankId Bankname
E01 Arun Jan 1000 B01 SBI

E01 Arun Feb 1200 B01 SBI

E02 Bala Jan 1500 B02 ICICI

E03 Chitra Feb 1400 B01 SBI

24. What are Transitive Dependency and its Problem?


Transitive Dependency is defined as a functional dependency (relationship) between two or
more non-key columns and it is denoted as
A->B and B->C, but A will not depend on C
Problem: During insertion, deletion and modification of data.
25. Write an example for 3 NF.
Roll->City
And
City->STDCode
If we try to derive Roll->STDcode it becomes a transitive dependency, because obviously
the STDCode of a city cannot depend on the roll number issued by a school or college.

RAAK/B.SC(CS)/M.USHA/III YEAR/V SEMESTER/UCS 51 /DATABASE


MANAGEMENT SYSTEM/UNIT-IV QUESTION AND ANSWER
Unit – 4 Question and Answer Page 5 of 17
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

26. Write three characteristics of relational model.


Structure – View of data.
Integrity – To Satisfy integrity constraints
Data manipulation- Supports insert, delete, update.

PART – B QUESTIONS
1. Illustrate the concept of Lossless Decomposition. (April/May 2014)
Decomposition:
Let R be a relation schema
A set of relation schemas { R1, R2,…, Rn } is a decomposition of R if
R = R1 U R2 U …..U Rn
each Ri is a subset of R ( for i = 1,2…,n)
Lossless Decomposition
A decomposition {R1, R2,…, Rn} of a relation R is called a lossless decomposition for
R if the natural join of R1, R2,…, Rn produces exactly the relation R.
A decomposition is lossless if we can recover:
R(A, B, C)
Decompose
R1(A, B) R2(A, C)
Recover
R’(A, B, C)
Thus, R’ = R
X ∩ Y  X, X ∩ Y  Y
Example : Lossless Decomposition
Given:
Lending-schema = (branch-name, branch-city, assets, customer-name, loan-number,
amount)
Required FD’s:
branch-name branch-city assets
loan-number amount branch-name

RAAK/B.SC(CS)/M.USHA/III YEAR/V SEMESTER/UCS 51 /DATABASE


MANAGEMENT SYSTEM/UNIT-IV QUESTION AND ANSWER
Unit – 4 Question and Answer Page 6 of 17
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

Decompose Lending-schema into two schemas:


Branch-schema = (branch-name, branch-city, assets)
Loan-info-schema = (branch-name, customer-name, loan-number, amount)
Show that decomposition is Lossless Decomposition
 Since branch-name->branch-city assets, the augmentation rule for FD implies that:
branch-name->branch-name branch-city assets
 Since Branch-schema ∩ Loan-info-schema = {branch-name}
Thus, this decomposition is Lossless decomposition
Decompositions should always be lossless
Lossless decomposition ensure that the information in the original relation can be
accurately reconstructed based on the information represented in the decomposed relations.

2. State the three anomalies to be considered while Manipulation a Database. (April/May


2014)
Without Normalization, it becomes difficult to handle and update the database,
without facing data loss. Insertion, Updation and Deletion Anamolies are very frequent if
Database is not Normalized. To understand these anomalies let us take an example
of Student table.

S_id S_Name S_Address Subject_opted

401 Adam Noida Bio

402 Alex Panipat Maths

403 Stuart Jammu Maths

404 Adam Noida Physics

Three anamolies (inconsistency) are:

 Updation
 Insertion
 Deletion

RAAK/B.SC(CS)/M.USHA/III YEAR/V SEMESTER/UCS 51 /DATABASE


MANAGEMENT SYSTEM/UNIT-IV QUESTION AND ANSWER
Unit – 4 Question and Answer Page 7 of 17
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

Updation Anamoly :

To update address of a student who occurs twice or more than twice in a table, we will have
to update S_Address column in all the rows, else data will become inconsistent.
Insertion Anamoly :
Suppose for a new admission, we have a Student id(S_id), name and address of a student
but if student has not opted for any subjects yet then we have to insert NULL there, leading to
Insertion Anamoly.
Deletion Anamoly :
If (S_id) 401 has only one subject and temporarily he drops it, when we delete that row,
entire student record will be deleted along with it.

3. Discuss the Design Pitfalls of Relational Database (Nov 2012) (April/May 2013) (Nov/Dec
2011) ( Nov 2014)

Relational database design requires that we find a “good” collection of relation schemas.
A bad design may lead to
 Repetition of information
 Inability to represent certain information.
Design Goals:
 Avoid redundant data.

 Ensure that relationships among attributes are represented.

 Facilitate the checking of updates for violation of  database integrity constraints.


Relation schema:
Lending-schema = (branch-name,branch-city,customer-name,loan-number,amount)

Sample Lending Relation:

Branch- Branch-city Assets Customer- Loan-number amount


name name
SBI Chennai 2000000 AAAA L-10 50000

RAAK/B.SC(CS)/M.USHA/III YEAR/V SEMESTER/UCS 51 /DATABASE


MANAGEMENT SYSTEM/UNIT-IV QUESTION AND ANSWER
Unit – 4 Question and Answer Page 8 of 17
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

SBI Pondy 2000000 BBBB L-15 10000


HDFC Pondy 1000000 CCCC L-12 90000
SBI Trichy 2000000 DDDD L-16 80000

Here, the repetition of information in our alternative design is undesirable.


Repeating information wastes space.
It complicates updating the database.
Thus, we must repeat the asset and city data for the HDFC branch, add must add the
tuple
(HDFC, Cuddalore, 1000000, EEEE, L18, 8000)
That Observation is bank branch has a unique value of assets, so given a branch name we
can uniquely identify the assets value.
Branch may make many loans, so given a branch name we cannot uniquely determine a
loan number.
Functional dependency : Branch-name -> Assets

4. Write a short note on Functional Dependency.( Nov 2013) (Nov 2012)


RK is a superkey for relation schema R if and only if K is a candidate key for R if and on
ly if R, andK RK, for no Functional dependencies allow us to express constraints that
cannot be expressed using superkeys.
Consider the schema:
inst_dept (ID, name, salary, dept_name, building, budget ).
We expect these functional dependencies to hold:
buildingdept_name building an ID but would not expect the following to hold:
dept_name
Use of Functional Dependencies:
 We use functional dependencies to:test relations to see if they are legal under a given set of
 functional dependencies.
 If a relation r is legal under a set F of functional  dependencies, we say that r satisfies F.
specify constraints on the set of legal relations.
RAAK/B.SC(CS)/M.USHA/III YEAR/V SEMESTER/UCS 51 /DATABASE
MANAGEMENT SYSTEM/UNIT-IV QUESTION AND ANSWER
Unit – 4 Question and Answer Page 9 of 17
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

 We say that F holds on R if all legal relations on R4 satisfy the set of functional
dependencies F.
 Note: A specific instance of a relation schema may satisfy a functional dependency even if
the functional dependency does not hold on all legal instances.For example, a specific inst
ance of instructor may, by chance, satisfy ID. name
 A functional dependency is trivial if it is satisfied by all instances of a relation Example:
ID ID, name name name ,    is trivial if   

5. Compare and Contrast BCNF with 3NF. (April/May 2013)


Relations in BCNF and 3NF

 Relations in BCNF: no repetition of information


 Relations in 3NF: problem of repetition of information

Decomposition in BCNF and in 3NF

 It is always possible to decompose a relation into relations in 3NF and


o the decomposition is lossless
o dependencies are preserved

 It is always possible to decompose a relation into relations in BCNF and


o the decomposition is lossless
o the information is not repeated

 NF is always achievable. BCNF is not. BCNF may result in Loss-less Join Decomposition
and lead to loss of Dependency Preserving Decompositions.

Properties 3NF BCNF


Achievability Always achievable Not always achievable
Quality of the tables Less More
Non-key Determinants Can have non-key attributes as Cannot have.
determinants
Proposed by Edgar F. Codd Raymond F.Boyce and Edgar F.Codd
jointly proposed
Decomposition Loss-less join decomposition can Sometimes Loss-less join
be achieved decomposition cannot be achieved

RAAK/B.SC(CS)/M.USHA/III YEAR/V SEMESTER/UCS 51 /DATABASE


MANAGEMENT SYSTEM/UNIT-IV QUESTION AND ANSWER
Unit – 4 Question and Answer Page 10 of 17
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

Table 1 – 3NF – BCNF Comparisons

6. What is 4 NF? List the unique features of 4 NF (Nov 2013)


 A relation is in fourth normal form if it is in BCNF and it contains no multivalued
dependencies.
 Multivalued Dependency:
 A type of functional dependency where the determinant can determine more than one
value.
More formally, there are 3 criteria:
There must be at least 3 attributes in the relation. call them A, B, and C, for example.

Given A, one can determine multiple values of B.

A, one can determine multiple values of C.

B and C are independent of one another.

Vendor Code
Item Code
Project No.
V1 I1 P1
V1 I2 P1
V1 I1 P3
V1 I2 P3
V2 I2 P1
V2 I3 P1
V3 I1 P2
V3 I1 P3

RAAK/B.SC(CS)/M.USHA/III YEAR/V SEMESTER/UCS 51 /DATABASE


MANAGEMENT SYSTEM/UNIT-IV QUESTION AND ANSWER
Unit – 4 Question and Answer Page 11 of 17
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

The given relation has a number of problems.

For example:

If vendor V1 has to supply to project P2, but the item is not yet decided, then a row with a blank
for item code has to be introduced.

The information about item I1 is stored twice for vendor V3.

The table can be expressed as the two 4NF relations given as following. The fact that vendors are
capable of supplying certain items and that they are assigned to supply for some projects in
independently specified in the 4NF relation.

Vendor-Supply

Vendor Code
Item Code
V1 I1

V1 I2
V2 I2
V2 I3
V3 I1
Vendor-Project

Vendor Code
Project No.
V1 P1
V1 P3
V2 P1
V3 P2

RAAK/B.SC(CS)/M.USHA/III YEAR/V SEMESTER/UCS 51 /DATABASE


MANAGEMENT SYSTEM/UNIT-IV QUESTION AND ANSWER
Unit – 4 Question and Answer Page 12 of 17
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

7. Explain the concept of BCNF using example. (Nov 2014)

 A relationship is said to be in BCNF if it is already in 3NF and the left hand side of every
dependency is a candidate key.

 A relation which is in 3NF is almost always in BCNF.

 These could be same situation when a 3NF relation may not be in BCNF the following
conditions are found true.

 The candidate keys are composite.

 There are more than one candidate keys in the relation.

There are some common attributes in the relation.


Professor Code
Department Head of Dept.
Percent Time
P1 Physics Ghosh 50
P1 Mathematics Krishnan 50
P2 Chemistry Rao 25
P2 Physics Ghosh 75
P3 Mathematics Krishnan 100

Consider, as an example, the above relation. It is assumed that:

 A professor can work in more than one department

 The percentage of the time he spends in each department is given.

 Each department has only one Head of Department.

The relation diagram for the above relation is given as the following:

RAAK/B.SC(CS)/M.USHA/III YEAR/V SEMESTER/UCS 51 /DATABASE


MANAGEMENT SYSTEM/UNIT-IV QUESTION AND ANSWER
Unit – 4 Question and Answer Page 13 of 17
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012


The given relation is in 3NF. Observe, however, that the names of Dept. and Head of Dept.
are duplicated.

 Further, if Professor P2 resigns, rows 3 and 4 are deleted. We lose the information that Rao
is the Head of Department of Chemistry.

 The normalization of the relation is done by creating a new relation for Dept. and Head of
Dept. and deleting Head of Dept. form the given relation.

The normalized relations are shown in the following.

Professor Department
Percent
DepartmentHead of Dept. Code Time
Physics Ghosh P1 Physics 50
Mathematics
Krishnan
Chemistry Rao P1 Mathematics
50

P2 Chemistry 25

P2 Physics 75

P3 Mathematics
100

PART – C QUESTIONS

1. Explain the First Three Normal forms with suitable example. April/May 2013 Nov 2012

Un-Normalized Form (UNF)

 If a table contains non-atomic values at each row, it is said to be in UNF.

 An atomic value is something that cannot be further decomposed.

 A non-atomic value, as the name suggests, can be further decomposed and simplified.

Emp-Id Emp-Name Month Sales Bank-Id Bank-Name


E01 AA Jan 1000 B01 SBI
Feb 1200
Mar 850

RAAK/B.SC(CS)/M.USHA/III YEAR/V SEMESTER/UCS 51 /DATABASE


MANAGEMENT SYSTEM/UNIT-IV QUESTION AND ANSWER
Unit – 4 Question and Answer Page 14 of 17
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

E02 BB Jan 2200 B02 UTI


Feb 2500
E03 CC Jan 1700 B01 SBI
Feb 1800
Mar 1850
Apr 1725

First Normal Form (1NF)

 A relation is said to be in 1NF if it contains no non-atomic values and each row can
provide a unique combination of values.

The above table in UNF can be processed to create the following table in 1NF.
Emp-Id Emp-Name Month Sales Bank-Id Bank-Name
E01 AA Jan 1000 B01 SBI
E01 AA Feb 1200 B01 SBI
E01 AA Mar 850 B01 SBI
E02 BB Jan 2200 B02 UTI
E02 BB Feb 2500 B02 UTI
E03 CC Jan 1700 B01 SBI
E03 CC Feb 1800 B01 SBI
E03 CC Mar 1850 B01 SBI
E03 CC Apr 1725 B01 SBI

As you can see now, each row contains unique combination of values. Unlike in UNF, this relation
contains only atomic values, i.e. the rows cannot be further decomposed, so the relation is now in
1NF.

Second Normal Form (2NF)


A relation is said to be in 2NF f if it is already in 1NF and each and every
attribute fully depends on the primary key of the relation.
Let us explain. Emp-Id is the primary key of the above relation. Emp-Name,
Month, Sales and Bank-Name all depend upon Emp-Id. But the attribute Bank-Name depends on
Bank-Id, which is not the primary key of the table. So the table is in 1NF, but not in 2NF. If this
position can be removed into another related relation, it would come to 2NF.

RAAK/B.SC(CS)/M.USHA/III YEAR/V SEMESTER/UCS 51 /DATABASE


MANAGEMENT SYSTEM/UNIT-IV QUESTION AND ANSWER
Unit – 4 Question and Answer Page 15 of 17
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

Emp-Id
Emp-Name
Month
Sales
Bank-Id
E01 AA JAN 1000B01
E01 AA FEB 1200B01
E01 AA MAR850B01
E02 BB JAN 2200B02
E02 BB FEB 2500B02
E03 CC JAN 1700B01
E03 CC FEB 1800B01
E03 CC MAR1850B01
E03 CC APR 1726B01

Bank-Id
Bank-Name
B01 SBI
B02 UTI

After removing the portion into another relation we store lesser amount of data in two relations
without any loss information. There is also a significant reduction in redundancy.

Third Normal Form (3NF)

 A relation is said to be in 3NF, if it is already in 2NF and there exists no transitive


dependency in that relation.

What is a transitive dependency? Within a relation if we see


A → B [B depends on A]
And
B → C [C depends on B]
Then we may derive
A → C[C depends on A]

Such derived dependencies hold well in most of the situations. For example if we have
Roll → Marks
And
Marks → Grade
Then we may safely derive
Roll → Grade.

This third dependency was not originally specified but we have derived it.

The derived dependency is called a transitive dependency when such dependency becomes
improbable. For example we have been given

RAAK/B.SC(CS)/M.USHA/III YEAR/V SEMESTER/UCS 51 /DATABASE


MANAGEMENT SYSTEM/UNIT-IV QUESTION AND ANSWER
Unit – 4 Question and Answer Page 16 of 17
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

Roll → City
And
City → STDCode

If we try to derive Roll → STDCode it becomes a transitive dependency, because obviously the
STDCode of a city cannot depend on the roll number issued by a school or college.

In such a case the relation should be broken into two, each containing one of these two
dependencies:
Roll → City
And
City → STD code

2. Describe the BCNF and Fourth Normal Form. (Refer Part-B 5th and 6th questions)

3. Discuss and Summarize the Normalization steps. (Refer Part-c 1st and 2nd questions)

Input Transformation Output


Relation Relation

All Eliminate variable length record. Remove multi-attribute lines in table. 1NF
Relations

1NF Remove dependency of non-key attributes on part of a multi-attribute key. 2NF


Relation

2NF Remove dependency of non-key attributes on other non-key attributes. 3NF

3NF Remove dependency of an attribute of a multi attribute key on an attribute of


BCNF
another (overlapping) multi-attribute key.

BCNF Remove more than one independent multi-valued dependency from relation
4NF
by splitting relation.

4NF Add one relation relating attributes with multi-valued dependency. 5NF

RAAK/B.SC(CS)/M.USHA/III YEAR/V SEMESTER/UCS 51 /DATABASE


MANAGEMENT SYSTEM/UNIT-IV QUESTION AND ANSWER
Unit – 4 Question and Answer Page 17 of 17
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

UCS 51 – DATABASE MANAGEMENT SYSTEM


Unit-5 – PL/SQL
Type: 100% Theory
Question Bank with Answers
PART – A QUESTIONS

1. What is a trigger? (April/May 2013,Nov/dec 2015)

A trigger is a SQL procedure that initiates an action (i.e., fires an action) when an
event (INSERT, DELETE or UPDATE) occurs. A trigger cannot be called or executed.

2. What are the DCL commands in oracle? (April/May 2013)

 GRANT – used to access permission on owned database objects to other user

 REVOKE – used to revoke an existing privilege from a user

Eg:

REVOKE SELECT ON T1 FROM U1

GRANT CREATE SESSION TO U1

3. What are the uses of PL/SQL? (Nov 2012)

 PL/SQL is tightly integrated with SQL.

 It offers extensive error checking.

 It offers numerous data types.

 It offers a variety of programming structures.

4. What is Exception Handling? (Nov 2012,Apr/May 2016)

PL/SQL provides a feature to handle the Exceptions which occur in a PL/SQL


Block known as exception Handling.

Using Exception Handling we can test the code and avoid it from exiting abruptly.

PL/SQL Exception message consists of three parts.

1) Type of Exception
RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-5 QB/VER 1.0
Unit – 5 Answer Page 1 of 24
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

2) An Error Code
3) A message

5. Write DDL commands in oracle. (Nov/Dec 2011)

 CREATE: Use to create objects like CREATE TABLE, CREATE


FUNCTION, CREATE SYNONYM, and CREATE VIEW. Etc.

 ALTER: Use to Alter Objects like ALTER TABLE, ALTER USER, ALTER
TABLESPACE, ALTER DATABASE. Etc.

 DROP: Use to Drop Objects like DROP TABLE, DROP USER,


DROPTABLESPACE, DROP FUNCTION. Etc.

 REPLACE: Use to rename table names.

 TRUNCATE: Use to truncate (delete all rows) a table.

6. What is varchar function? (Nov/Dec 2011)

The VARCHAR function returns a varying-length character string representation


of a character string.

Eg:

Stud_name varchar(25;)

7. Define an Entity set. (April/May 2014)

An entity set is a set of entities of the same type (e.g., all persons having an
account at a bank).

Entity sets need not be disjoint. For example, the entity set employee (all
employees of a bank) and the entity set customer (all customers of the bank) may have
members in common.

8. Define an Entity set. (April/May 2014)

Functional dependency is a relationship that exists when one attribute uniquely


determines another attribute.

If R is a relation with attributes X and Y, a functional dependency between the


attributes is represented as X->Y, which specifies Y is functionally dependent on X.

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-5 QB/VER 1.0


Unit – 5 Answer Page 2 of 24
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

9. How to get back the privileges given by GRANT command? (Nov 2014)

Revoke Command is used to get back the privileges given by Grant command.

Syntax:

Revoke create table from username;

10. What are the uses of SET SERVER OUTPUT ON command? (Nov 2014)

Whenever you start Oracle SQL (PL/SQL) at that time we must have to write the
"SET Serveroutput ON" command.

PL/SQL program execution into Oracle engine so we always required to get


server output result and display into the screen otherwise result can't be display.

11. What is a Cursor?

A cursor is a pointer to context area which contains all information needed for
processing the statement.

PL/SQL controls the context area through a cursor. The set of rows the cursor
holds is referred to as the active set.

12. Define Integrity Constraint.

A constraint (rule) that must remain true for a database to preserve data integrity.
Integrity constraints are specified at database creation time and enforced by the database
management system.

13. What are the advantages of PL/SQL?

 Applications written in PL/SQL are fully portable.


 PL/SQL provides high security level.
 PL/SQL provides access to predefined SQL packages.
 PL/SQL provides support for Object-Oriented Programming.
 PL/SQL provides support for Developing Web Applications and Server Pages.

14. What is a Package?

PL/SQL Packages is schema object and collection of related data type (variables,
constants), cursors, procedures, functions are defining within a single context.

Packages are device into two parts,

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-5 QB/VER 1.0


Unit – 5 Answer Page 3 of 24
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

 Package Specification
 Package Body

15. What is subprogram?

A subprogram is a program unit/module that performs a particular task. These


subprograms are combined to form larger programs. This is basically called the 'Modular
design'. A subprogram can be invoked by another subprogram or program which is called
the calling program.

16. What is meant by Dbms_output?

The DBMS_OUTPUT is a built-in package that enables you to display output,


display debugging information, and send messages from PL/SQL blocks, subprograms,
packages, and triggers.

PART – B QUESTIONS

1. Explain the features of Relational DBMS. (April/May 2013)

 Provides data to be stored in tables

 Persists data in the form of rows and columns

 Provides facility primary key, to uniquely identify the rows

 Creates indexes for quicker data retrieval

 Provides a virtual table creation in which sensitive data can be stored and
simplified query can be applied(views)

 Sharing a common column in two or more tables(primary key and foreign key)

 Provides multi user accessibility that can be controlled by individual users

2. Describe about Exception Handling.(April/May 2013)

In the PL/SQL language, errors of any kind are treated as exceptions -- situations
that should not occur -- in your program. An exception can be one of the following:

 An error generated by the system (such as "out of memory" or "duplicate


value in index")
 An error caused by a user action
 A warning issued by the application to the user
RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-5 QB/VER 1.0
Unit – 5 Answer Page 4 of 24
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

Exception handlers. :

 The exception-handler mechanism allows you to cleanly separate your error


processing code from your executable statements.

 It also provides an event-driven model, as opposed to a linear code model, for


processing errors.

 When an error occurs in PL/SQL, whether a system error or an application


error, an exception is raised.

 We cannot return to that block after you finish handling the exception.
Instead, control is passed to the enclosing block, if any.

Figure: Exception handling architecture

3. Mention some of the DDL commands in oracle. (Nov 2012 & April/May 2014,2016)

Data definition language (DDL) statements enable you to perform these tasks:

 CREATE:Use to create objects like CREATE TABLE, CREATE


FUNCTION,CREATE SYNONYM, and CREATE VIEW. Etc.
 ALTER: Use to Alter Objects like ALTER TABLE, ALTER USER, ALTER
TABLESPACE, ALTER DATABASE. Etc.
 DROP:Use to Drop Objects like DROP TABLE, DROP USER,
DROPTABLESPACE, DROP FUNCTION. Etc.
 REPLACE:Use to rename table names.
 TRUNCATE :Use to truncate (delete all rows) a table.

Create
To create tables, views, synonyms, sequences, functions, procedures, packages
etc.

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-5 QB/VER 1.0


Unit – 5 Answer Page 5 of 24
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

Example

create table emp (empno number(5) primary key,


name varchar2(20),
sal number(10,2),
job varchar2(20),
mgr number(5),
Hiredate date,
comm number(10,2));

Alter

Use the ALTER TABLE statement to alter the structure of a table.

Examples:

To add column:
alter table emp add (addr varchar2(20), city varchar2(20),pin
varchar2(10),ph varchar2(20));
To Modify Column:
alter table emp modify (ename varchar2(30))
To drop columns:
alter table emp drop column (pin, city);

Rename
Use the RENAME statement to rename a table, view, sequence, or private
synonym for a table, view, or sequence.

Example

rename emp2 to employee2

Drop

Use the drop statement to drop tables, functions, procedures, packages, views,
synonym, sequences, tablespaces etc.

Example

drop table emp2;

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-5 QB/VER 1.0


Unit – 5 Answer Page 6 of 24
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

Truncate

 Use the Truncate statement to delete all the rows from table permanently.

 It deallocates free extents from the table. So that the free space can be use by
other tables.

Example

truncate table emp;

4. How to define a function in PL/SQL function? (Nov 2012)

A PL/SQL function is same as a procedure except that it returns a value.


Therefore, all the discussions of the previous chapter are true for functions too.

Creating a Function:

A standalone function is created using the CREATE FUNCTION statement.

Syntax:

CREATE [OR REPLACE] FUNCTION function_name


[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
<function_body>
END [function_name];

Note: The function must contain a return statement.

Example:

CREATE OR REPLACE FUNCTION totalCustomers


RETURN number IS
total number(2) := 0;
BEGIN
SELECT count(*) into total
FROM customers;
RETURN total;
END;

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-5 QB/VER 1.0


Unit – 5 Answer Page 7 of 24
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

Calling a Function:

 When a program calls a function, program control is transferred to the called


function.

 A called function performs defined task and when its return statement is executed.

 To call a function you simply need to pass the required parameters along with
function.

Example:

DECLARE
c number(2);
BEGIN
c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END;

5. Explain the different types of triggers. (Nov/Dec 2011)

A trigger is a pl/sql block structure which is fired when a DML statements like
Insert, Delete, Update is executed on a database table.

A trigger is triggered automatically when an associated DML statement is


executed.

Type of Triggers:

BEFORE Trigger:

 BEFORE trigger execute before the triggering DML statement (INSERT,


UPDATE, DELETE) execute.

 Triggering SQL statement is may or may not execute, depending on the


BEFORE trigger conditions block.

AFTER Trigger:

 AFTER trigger execute after the triggering DML statement (INSERT,


UPDATE, DELETE) executed.

 Triggering SQL statement is execute as soon as followed by the code of


trigger before performing Database operation.
RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-5 QB/VER 1.0
Unit – 5 Answer Page 8 of 24
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

ROW Trigger:

 ROW trigger fire for each and every record which are performing INSERT,
UPDATE, DELETE from the database table.

 If row deleting is define as trigger event, when trigger file, deletes the five
rows each times from the table.

Statement Trigger:

Statement trigger fire only once for each statement. If row deleting is define as
trigger event, when trigger file, deletes the five rows at once from the table.

Combination Trigger:

Combination trigger are combination of two trigger type,

Before Statement Trigger:

Trigger fire only once for each statement before the triggering DML statement.

Before Row Trigger:

Trigger fire for each and every record before the triggering DML statement.

After Statement Trigger:

Trigger fire only once for each statement after the triggering DML statement
executing.

After Row Trigger:

Trigger fire for each and every record after the triggering DML statement
executing.

6. Write note on Cursor management in PL/SQL. (Nov/Dec 2011)

 Cursor is the work area which Oracle reserves for internal processing of SQL
statements. This work area is private for oracles reserved are called cursor.

 Cursor area also saying session cursor. because session cursor store
information until the session end.

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-5 QB/VER 1.0


Unit – 5 Answer Page 9 of 24
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

How to Use Cursor?

 In PL/SQL block SELECT statement cannot return more than one row at a
time.

 So Cursor uses to some group of rows (more than one row) for implementing
certain logic to get all the group of records.

Classification of CURSORS:

 Implicit Cursor or Internal Cursor: Manage for Oracle itself or internal


process itself.

 Explicit Cursor or User-defined Cursor: Manage for user/programmer or


external processing.

Implicit Cursor:

 Oracle uses implicit cursors for its internal processing.

 Gathering information from cursor by using session attributes until another


SELECT statement or DML statement execute

Explicit Cursor:

 Explicit Cursor which is construct/manage by user itself calls explicit cursor.

 User itself to declare the cursor, open cursor to reserve the memory and
populate data, fetch the records from the active data set one at a time, apply
logic and last close the cursor.

 We cannot directly assign value to an explicit cursor variable you have to use
expression or create subprogram for assign value to explicit cursor variable.

Step for Using Explicit Cursor:

 Declare cursor
 Open cursor
 Loop
 Fetch data from cursor
 Exit loop
 Close cursor

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-5 QB/VER 1.0


Unit – 5 Answer Page 10 of 24
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

7. Write about PL/SQL block. (April/May 2014)

PL/SQL is a block-structured language, meaning that PL/SQL programs are


divided and written in logical blocks of code. Each block consists of three sub-parts:

SI.No Sections & Description


1 Declarations
This section starts with the keyword DECLARE. It is an optional section
and defines all variables, cursors, subprograms, and other elements to be
used in the program.

2 Executable Commands
This section is enclosed between the keywords BEGIN and END and it is
a mandatory section. It consists of the executable PL/SQL statements of
the program. It should have at least one executable line of code, which
may be just a NULL command to indicate that nothing should be
executed.
3 Exception Handling
This section starts with the keyword EXCEPTION. This section is again
optional and contains exception(s) that handle errors in the program.

Note:

 Every PL/SQL statement ends with a semicolon (;).

 PL/SQL blocks can be nested within other PL/SQL blocks using BEGIN and
END.

Syntax:

DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;

Example:

DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-5 QB/VER 1.0


Unit – 5 Answer Page 11 of 24
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

END;

8. Explain DCL commands in SQL. (Nov 2014)

 Data Control Statements are one of the SQL statement types which enforce
database security at database and object level.

 It deals with the access permissions and rights of a user.

 DCL commands are used to assign security levels in database, which involves
multiple user setups.

 They are used to grant defined role and access privileges to the users.

 There are two types of DCL commands in Oracle:

o GRANT

o REVOKE

GRANT:

A DBA or user can grant access permission on owned database objects to other
user or roles using GRANT command.

Syntax:

Code (Text):
GRANT [privilege]
ON [object]
TO {user |PUBLIC |role}
[WITH ADMIN | GRANT OPTION];

Example

U1 is a newly created user in the database. DBA shall grant below privileges to
user in order to connect to the database.

SQL> GRANT CREATE SESSION TO U1;

Above privilege will enable U1 to create a session in the database.

SQL> GRANT CONNECT, RESOURCE TO U1;

Above privilege will enable U1 to connect to the database.


RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-5 QB/VER 1.0
Unit – 5 Answer Page 12 of 24
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

Privileges:

 Privilege is the permission name, which is granted to the user.

 It may be SELECT, INSERT, UPDATE, DELETE, EXECUTE, ALL and


many others, on a database object.

Privileges are of two types

 System privilege – Schema level privilege which is granted by DBA to the


users is known as System privilege.
 Object privilege – Object level privilege can be granted from object owning
user (Grantor) to other user (GRANTEE).

REVOKE:

 The DCL command is used to revoke an existing privilege from a user.


 It can revoke a system privilege, object privilege or a role from a user.
 Only DBA or a user with ADMIN OPTION can revoke system privilege.

Syntax:

REVOKE [privilege]
ON [object]
FROM {USER |PUBLIC | ROLE}

Example:
SQL> REVOKE SELECT ON T1 FROM U1;

9. What is anonymous block in PL/SQL? Give example. (Nov 2014)

 PL/SQL blocks consists of procedure and function, the anonymous block has
no name associated with it.

 In fact, the anonymous block is missing the header section altogether.

 Instead it simply uses the DECLARE reserved word to mark the beginning of
its optional declaration section.

Fig: An anonymous block without declaration and exception sections

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-5 QB/VER 1.0


Unit – 5 Answer Page 13 of 24
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

Fig: An anonymous block defined inside a procedure

The Structure of an Anonymous Block:

The general format of an anonymous PL/SQL block is as follows:

[ DECLARE
... optional declaration statements ... ]
BEGIN
... executable statements ...
[ EXCEPTION
... optional exception handler statements ... ]
END;

Examples of Anonymous Blocks:

A block with BEGIN-END terminators, but no declaration or exception sections:

BEGIN
hiredate := SYSDATE;
END

An anonymous block with a declaration section, but no exception section:

DECLARE
right_now DATE := SYSDATE;
BEGIN
hiredate := right_now;
END

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-5 QB/VER 1.0


Unit – 5 Answer Page 14 of 24
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

PART – C QUESTIONS

1. Explain the various features of PL/SQL. (April/May 2013)

 PL/SQL is a completely portable, high-performance transaction-processing


language.

 PL/SQL provides a built-in interpreted and OS independent programming


environment.

 PL/SQL can also directly be called from the command-line SQL*Plus interface.

 Direct call can also be made from external programming language calls to
database.

 PL/SQL's general syntax is based on that of ADA and Pascal programming


language.

 Apart from Oracle, PL/SQL is available ten times in-memory database and IBM
DB2.

 PL/SQL is tightly integrated with SQL.

 It offers extensive error checking.

 It offers numerous data types.

 It offers a variety of programming structures.

 It supports structured programming through functions and procedures.

 It supports object-oriented programming.

 It supports developing web applications and server pages.

2. Explain in detail the DML commands in oracle. (Nov 2012)

Data manipulation language (DML) statements query and manipulate data in


existing schema objects. These statements do not implicitly commit the current
transaction.

The following are the DML statements available in Oracle.

 INSERT:Use to Add Rows to existing table.

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-5 QB/VER 1.0


Unit – 5 Answer Page 15 of 24
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

 UPDATE:Use to Edit Existing Rows in tables.

 DELETE:Use to Delete Rows from tables.

Insert

Use the Insert Statement to Add records to existing Tables.

Examples:

To add a new row to an emp table.

Insert into empvalues (101,’Sami’,’G.Manager’,’8-aug-1998’,2000);

Another method to insert date to an emp table.

Insert into emp (empno,ename,sal) values (102,’Ashi’,5000);

Sub query using Insert

Insert into emp (select empno, ename, sal from old_emp);

Update:

Update statement is used to update rows in existing tables which is in your own
schema or if you have update privilege on them.

Example:

updateemp set sal=sal+500 where empno = 104;

Sub query using update

updateemp set city=(select city from dept where deptno= emp.deptno);

Delete:

Use the DELETE statement to delete the rows from existing tables which are in
our schema or if you have DELETE privilege on them.

Example:

To delete the employee whose empno is 102.

delete from emp where empno=102;

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-5 QB/VER 1.0


Unit – 5 Answer Page 16 of 24
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

To delete all rows from emp table.

delete from emp;

Sub query using delete

delete from empwherecity=(select city from dept where city=”Chennai”);

Select:

 The SELECT statement is used to retrieve database values from a table/view


or set of tables/views based on given selection criteria.

 An unrestricted SELECT retrieves all rows.

 Additionally, the SELECT statement is the basis for all subqueries in all other
commands.

 Results are sorted in ascending order unless specified by DESC.

The minimum form of the SELECT statement is as follows.

SELECT * FROM <table_name>;

Example:

Select * from emp;

3. Discuss about Exception handling in detail. (Nov/Dec 2011,Nov/Dec 2015)

 An error condition during a program execution is called an exception in PL/SQL.

 PL/SQL supports programmers to catch such conditions using EXCEPTION


block in the program and anappropriate action is taken against the error condition.

 There are two types of exceptions:

 System-defined exceptions

 User-defined exceptions

Syntax for Exception Handling:

DECLARE
<declarations section>
RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-5 QB/VER 1.0
Unit – 5 Answer Page 17 of 24
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
........
WHEN others THEN
exception3-handling-statements
END;

Example

DECLARE
c_idcustomers.id%type := 8;
c_namecustomers.name%type;
c_addrcustomers.address%type;
BEGIN
SELECT name, address INTO c_name, c_addrFROMcustomersWHERE
id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;

Raising Exceptions:

 Exceptions are raised by the database server automatically whenever there is any
internal database error.

 But exceptions can be raised explicitly by the programmer by using thecommand


RAISE.

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-5 QB/VER 1.0


Unit – 5 Answer Page 18 of 24
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

 Following is the simple syntax of raising an exception:

DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_nameTHENstatement;
END;

User-defined Exceptions:

 PL/SQL allows you to define our own exceptions according to the need of our
program.

 Auser-defined exception must be declared and then raised explicitly, using either a
RAISE statement or the procedure

DBMS_STANDARD.RAISE_APPLICATION_ERROR.

The syntax for declaring an exception is:

DECLARE

my-exception EXCEPTION;

Pre-defined Exceptions:

PL/SQL provides many pre-defined exceptions, which are executed when any
database rule isviolated by a program.

Oracle
Exception SQLCODE Description
Error

It is raised when none of the choices in the


CASE_NOT_FOUND 06592 -6592 WHEN clauses of a CASE statement is
selected,and there is no ELSE clause.

It is raised when a SELECT INTO statement


NO_DATA_FOUND 01403 +100
returns no rows.
RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-5 QB/VER 1.0
Unit – 5 Answer Page 19 of 24
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

It is raised when a database call is issued


NOT_LOGGED_ON
withoutbeing connected to the database.
01012 -1012
It is raised when PL/SQL has an internal
PROGRAM_ERROR 06501 -6501
problem.

ROWTYPE_MISMAT It is raised when a cursor fetches value in a


06504 -6504
CH variablehaving incompatible data type.

It is raised when a member method is invoked,


SELF_IS_NULL 30625 -30625 butthe instance of the object type was not
initialized.

4. Explain about PL/SQL Procedures. (Nov/Dec 2011)

 A subprogram is a program unit/module that performs a particular task.

 A subprogram can be invoked by another subprogram or program which is


called the calling program.

A subprogram can be created:

 At schema level - is a standalone subprogram.It is created with the CREATE


PROCEDURE

 Inside a package - created inside a package is a packaged subprogram.

 Inside a PL/SQL block - can be invoked with a set of parameters

Procedures:

These subprograms do not return a value directly, mainly used to perform an


action.

Parts of a PL/SQL Subprogram:

SI.No Parts & Description


Declarative Part
It is an optional part.It contains declarations of types, cursors,
1
constants, variables, exceptions, and nested subprograms.

Executable Part
2
This is a mandatory part and contains statements that perform the

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-5 QB/VER 1.0


Unit – 5 Answer Page 20 of 24
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

designated action.

Exception-handling
This is an optional part. It contains the code that handles run-time
3
errors.

Creating a Procedure:

A procedure is created with the CREATE OR REPLACE PROCEDURE


statement.

Syntax:

CREATE [OR REPLACE] PROCEDURE procedure_name


[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS}
BEGIN
<procedure_body>
END procedure_name;

Eg:

CREATE OR REPLACE PROCEDURE greetings


AS
BEGIN
dbms_output.put_line('Hello World!');
END;

Execute Procedure:

BEGIN
procedure-name;
END;

Eg:

BEGIN
greetings;
END;

Drop procedure:

DROP PROCEDURE procedure-name;


RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-5 QB/VER 1.0
Unit – 5 Answer Page 21 of 24
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

Eg:

DROP PROCEDURE greetings;

Parameter Modes in PL/SQL Subprograms:

SI.No Parameter Mode & Description


1 IN

It is a read-only parameter. Inside the subprogram, an IN parameter acts like


a constant. It cannot be assigned a value.

2 OUT

An OUT parameter returns a value to the calling program. Inside the


subprogram, an OUT parameter acts like a variable.

5. Explain about PL/SQL Cursor. (Nov 2014,Apr/May 2016)

 Oracle creates a memory area, known as context area, for processing an SQL
statement, which contains all information needed for processing the statement.

 A cursor is a pointer to this context area. PL/SQL controls the context area
through a cursor.

 Acursor holds the rows (one or more) returned by a SQL statement. The set of
rows the cursorholds is referred to as the active set.

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 no explicit cursor for the statement.

 Programmers cannot control the implicitcursors and the information in it.

 Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an


implicit cursor isassociated with this statement.

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-5 QB/VER 1.0


Unit – 5 Answer Page 22 of 24
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

 For INSERT operations, the cursor holds the data that needs to be inserted.

 For UPDATE and DELETE operations, the cursor identifies the rows that
would be affected.

 In PL/SQL, we can refer to the most recent implicit cursor as the SQL cursor,

Explicit Cursors:

Explicit cursors are programmer defined cursors for gaining more control over the
context area.

An explicit cursor should be defined in the declaration section of the PL/SQL Block. It is
created on a SELECT Statement which returns more than one row.

Syntax:

CURSOR cursor_name IS select_statement;

Working with an explicit cursor involves four steps:

 Declaring the cursor for initializing in the memory (Eg: CURSOR


c_customers ISSELECT id, name, address FROM customers;)

 Opening the cursor for allocating memory (Eg: OPEN c_customers;)

 Fetching the cursor for retrieving data – (Eg: FETCH c_customers INTO c_id,
c_name, c_addr;)

 Closing the cursor to release allocated memory – (Eg: CLOSE c_customers;)

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-5 QB/VER 1.0


Unit – 5 Answer Page 23 of 24
ACADEMIC YEAR: 2015 – 2016 REGULATION CBCS - 2012

Example:

DECLARE
c_idcustomers.id%type;
c_namecustomers.name%type;
c_addrcustomers.address%type;

CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
EXIT WHEN c_customers%notfound;
END LOOP;
CLOSE c_customers;
END;

----------

RAAK/B.SC(CS)/M.USHA/III YEAR/V Sem/UCS 51/DBMS/UNIT-5 QB/VER 1.0


Unit – 5 Answer Page 24 of 24

You might also like