Ucs 51 - Database Management Systems Unit-1 - Introduction: Type: 100% Theory Question Bank
Ucs 51 - Database Management Systems Unit-1 - Introduction: Type: 100% Theory Question Bank
PART – A QUESTIONS
Finance
Universities
Airlines
Telecommunications
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.
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.
PART – B QUESTIONS
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.
CLR integration.
Service Broker.
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 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.
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.
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.
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.
[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.
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:
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.
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]
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
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.
The following SQL creates a PRIMARY KEY on the "P_Id" column when the "Persons"
table is created:
MySQL:
FirstNamevarchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
)
FOREIGN KEY:
Let's illustrate the foreign key with an example. Look at the following two tables:
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.
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.
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.
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.
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:
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
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.
Key is an attribute or collection of attributes that uniquely identifies an entity among entity
set.
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.
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.
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:
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.
[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.
Entity
Entities are represented by means of rectangles. Rectangles are named with the entity set they
represent.
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).
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.
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.
[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
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.
---------------
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
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
Example:Adepositorrelationshipassociatesacustomerwitheachaccountthat he/shehas.
Adatadictionary isadatastructurewhichstoresmetadataaboutthestructureof
thedatabaseie. theschemaofthedatabase.
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
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.
Any relationthatisnotpartofthelogicalmodel,butismadevisibletoauserasa
virtual relation is called aview.
WedefineviewinSQLbyusingthecreateviewcommand.Theformofthe
createviewcommand is
Createviewvas <queryexpression>
Asubqueryisaselect-from-whereexpressionthatisnestedwithinanother
query.Acommonuseofsubqueriesisto performtestsforsetmembership,make
setcomparisons, and determineset cardinality.
Any relationthatisnotpartofthelogicalmodel,butismadevisibletoauserasa
virtual relation is called aview.
WedefineviewinSQLbyusingthecreateviewcommand.Theformofthecreatevie
wcommand is
Createviewvas <queryexpression>
TheWITHclauseprovidesawayofdefiningatemporaryviewwhosedefinitionis
availableonlyto thequeryin which theWITHclauseoccurs.
Deletion
Insertion
Updates
Updateofaview
Commit work
Rollback work
Triggersarestatementsthatareexecutedautomaticallybythesystemastheside
effect ofamodification to thedatabase.
21. Whataredomainconstraints?
Adomainisasetofvaluesthatmaybeassignedtoanattributeallvaluesthat
appearina column ofarelation must betaken from thesamedomain.
Avaluethatappearsinonerelationforagivensetofattributesalsoappearsfora
certain set ofattributes in anotherrelation.
Anassertionisapredicateexpressingaconditionthatwewishthedatabase always
to satisfy.
Domain integrityconstraints.
Referential integrityconstraints
Createassertion<assertion name>check<predicate>
Triggersareusefulmechanismsforalertinghumansorforstartingcertaintasks
automaticallywhen certain conditions aremet.
Theprojectoperationisaunary operationthatreturnsitsargumentrelationwith
certain attributes left out. Projection is denoted bypie (π).
PART – B QUESTIONS
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
Cartesian Product
A complete query language also contains facilities to insert and delete tuples
as well as to modify parts of existing tuples.
Entity
Attributes
Types:
Domain:
Examples: A field for gender may have the domain {male, female,
unknown} where those three values are the only permitted entries in
that column.
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.
Themostcrucialaspectindesigninga relationaldatabaseistoidentifythe
relationshipsamongtables.Thetypesofrelationshipinclude:
one‐to‐many
many‐to‐many
one‐to‐one
Normalization:
Applythenormalizationrules
tocheckwhetheryourdatabaseisstructurallycorrectand optimal.
First
NormalFo r m ﴾1NF﴿:Atableis1NFifeverycellcontainsasinglevalue,
notalistofvalues. Thispropertyis knownasatomic.
Third Normal
Form﴾3NF﴿:Atableis3NF,ifitis2NFandthenon‐keycolumnsare
independentof eachothers.
Insertion
Updating
Deletion:
Examples:
Delete all loans with loan numbers between 1300 and 1500.
Insertion:
Examples:
To insert a tuple for Smith who has $1200 in account 9372 at the SFU
branch.
Updating:
Examples:
To increase all balances by 5 percent.
For example, to select tuples (rows) of the borrow relation where the
branch is “SFU", we would write
The new relation created as the result of this operation consists of one tuple:
(SFU; 15; Hayes; 1500).
For example:
b) Project:
Project copies its argument relation for the specified attributes only.
Since a relation is a set, duplicate rows are eliminated.
πbname, cname(borrow)
πcname(σcname=banker(client))
o Ensuring the sum of loan amounts for each branch is less than
the sum of all account balances at the branch.
o Ensuring the sum of loan amounts for each branch is less than
the sum of all account balances at the branch.
Eg:
A constant relation
E1 U E2
E1 - E2
E1 x E 2
Union
Intersection
Set difference
Cartesian product
Select
Project
Rename
Join
Division
A view is object that gives the user a logical view of data from an
underlying table or tables.
Simplifies queries
Creation of Views:
Syntax
CREATE VIEW view_name as
SELECT column1, column2.....
FROM table_name
WHERE [condition];
Example
Create view on book table which contains two fields title,and author name.
Select Title,Author_name
From book;
Title Author_Name
Oracle Arora
DBMS Basu
DOS Sinha
ADBMS Basu
Unix Kapoor
Selecting Data from a View
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.
Destroying a View
Syntax:
DROP VIEW viewname;
Example
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:
where is a formula.
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:
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.
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.
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
Tuple: A single row of a table, which contains a single record for that
relation, is called a tuple.
Relation key: Each row has one or more attributes which can identify
the row in the relation (table) uniquely, is called the relation key.
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.
Basic Structure:
Database Schema:
Keys:
The notions of superkey, candidate key and primary key all apply to the
relational model.
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 complete query language also contains facilities to insert and delete tuples
as well as to modify parts ofexisting tuples.
The content of the database may be modified using the following operations:
Deletion
Insertion
Updating
Deletion:
Examples:
Insertion:
Example:
Updating:
Examples
Select
Project
Union
Set different
Cartesian product
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)
For example:
Selects and projects columns named as subject and author from relation
Books.
Union operation performs binary union between two given relations and is
defined as:
r∪ s = {t | t ∈ r or t ∈ s}
Notation: rUs
For examples:
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:
Notation: rΧs
For example:
Notation: ρ x (E)
Set intersection
Assignment
Natural join
For binary relationship sets between entity sets A and B, the mapping
cardinalitymust be one of:
Existence Dependencies:
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.
-----
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.
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.
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.
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
Select
From
where
Rename operation is used to rename both relations and a attributes. It uses the as
clause, taking the form:
Old-name as new-name
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.
Union
Intersect operation
Set Difference
Cartesian Product
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.
Average: avg()
Minimum: min()
Maximum: max()
Total: sum()
Count: count()
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
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.
Deletion
Insertion
Updates
Update of a view
Commit work
Rollback work
6) date.
PART – B QUESTIONS
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
This renaming is highly useful when one has to compare a set of tuples of the
same relation with other tuples of that relation.
The ‘as’ clauses can appear in both the select and from clauses.
For example:
TITLE NEW_PRICE
Oracle 458.85
DBMS 460
DOS 287.5
ADBMS 517.5
Unix 345
Note:
To do this in SQL, we specify that we want to change the structure of the table
using the ALTER TABLE command.
For example:
Char*sqlprog=”Update account
set balance=balance*1.05
where acc_no=?”
Char acc[10]=”101”;
The dynamic SQL program contains acc_no=?,which is a place holder for a value that is
provided when the SQL program is executed.
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.
Basic structure of an SQL expression consists of select, from and where clauses.
i)Select Clause
This command is used to display all fields/or set of selected fields for all/selected
records from a relation.
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
Oracle
DBMS
ADBMS
To ensure that duplicates are not removed, we use the all keyword.
a) Primary key:
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.
To clear the primary key constraints from the table, Use Syntax:
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.
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.
o The relation does not have two distinct tuples with the same values for
these attributes
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.
LENGTH
The LENGTH function returns the number of characters (including spaces and
hidden characters) in the string passed to it.
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
REPLACE
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.
Output:RAAK
UPPER
The UPPER function is used to convert all of the character in a string to upper
case.
LOWER
The LOWER function is used to convert all of the character in a string to lower
case.
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)
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
For example:
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:
For example:
ALTER statement
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.
SYNTAX:
Eg:
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.
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.
EXEC SQL
END-EXEC
Statements:
Note: Embedded SQL can execute any valid update, insert, or delete statements.
Why SQL?
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
Numeric Functions
Ex:
String Functions
Eg:
Date Formats
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
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;
Average Price
359.8
MAX ():
MIN ():
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 ():
2. Explain the various clauses of select statement with example. (April /May 2013)
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:
WHERE - clause specifies which table rows are used. The WHERE clause
is optional; if missing, all table rows are used.
SELECT Clause
For example,
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
FROM Clause:
The FROM clause always follows the SELECT clause. It lists the tables accessed
by the query.
For example,
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:
For example,
The SQL Modification Statements make changes to database data in tables and
columns. There are 3 modification statements:
INSERT Statement:
and,
VALUES Clause
Value-1 and value-2 are Literal Values or Scalar Expressions involving literals.
Examples
Before After
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
SET Clause
The SET Clause in the UPDATE Statement updates (assigns new value to)
columns in the selected table rows.
Value-1 and value-2 are expressions that can reference columns from the update
table.
Examples
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
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
Examples
Before After
sno pno qty sno pno qty
S1 P1 NULL S3 P2 200
S2 P1 200 =>
S3 P1 1000
S3 P2 200
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
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
SQL numeric functions are used primarily for numeric manipulation and/or
mathematical calculations. The following table details the numeric functions:
Function Description
-----
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
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.
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
Updation
Insertion
Deletion
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.
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
NF is always achievable. BCNF is not. BCNF may result in Loss-less Join Decomposition
and lead to loss of Dependency Preserving Decompositions.
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
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 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
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.
These could be same situation when a 3NF relation may not be in BCNF the following
conditions are found true.
The relation diagram for the above relation is given as the following:
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.
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
A non-atomic value, as the name suggests, can be further decomposed and simplified.
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.
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.
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
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)
All Eliminate variable length record. Remove multi-attribute lines in table. 1NF
Relations
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
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.
Eg:
Using Exception Handling we can test the code and avoid it from exiting abruptly.
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
ALTER: Use to Alter Objects like ALTER TABLE, ALTER USER, ALTER
TABLESPACE, ALTER DATABASE. Etc.
Eg:
Stud_name varchar(25;)
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.
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:
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.
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.
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.
PL/SQL Packages is schema object and collection of related data type (variables,
constants), cursors, procedures, functions are defining within a single context.
Package Specification
Package Body
PART – B QUESTIONS
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)
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:
Exception handlers. :
We cannot return to that block after you finish handling the exception.
Instead, control is passed to the enclosing block, if any.
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
To create tables, views, synonyms, sequences, functions, procedures, packages
etc.
Example
Alter
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
Drop
Use the drop statement to drop tables, functions, procedures, packages, views,
synonym, sequences, tablespaces etc.
Example
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
Creating a Function:
Syntax:
Example:
Calling a 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;
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.
Type of Triggers:
BEFORE Trigger:
AFTER Trigger:
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:
Trigger fire only once for each statement before the triggering DML statement.
Trigger fire for each and every record before the triggering DML statement.
Trigger fire only once for each statement after the triggering DML statement
executing.
Trigger fire for each and every record after the triggering DML statement
executing.
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.
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:
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.
Declare cursor
Open cursor
Loop
Fetch data from cursor
Exit loop
Close cursor
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:
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);
END;
Data Control Statements are one of the SQL statement types which enforce
database security at database and object level.
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.
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.
Privileges:
REVOKE:
Syntax:
REVOKE [privilege]
ON [object]
FROM {USER |PUBLIC | ROLE}
Example:
SQL> REVOKE SELECT ON T1 FROM U1;
PL/SQL blocks consists of procedure and function, the anonymous block has
no name associated with it.
Instead it simply uses the DECLARE reserved word to mark the beginning of
its optional declaration section.
[ DECLARE
... optional declaration statements ... ]
BEGIN
... executable statements ...
[ EXCEPTION
... optional exception handler statements ... ]
END;
BEGIN
hiredate := SYSDATE;
END
DECLARE
right_now DATE := SYSDATE;
BEGIN
hiredate := right_now;
END
PART – C QUESTIONS
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.
Apart from Oracle, PL/SQL is available ten times in-memory database and IBM
DB2.
Insert
Examples:
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:
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:
Select:
Additionally, the SELECT statement is the basis for all subqueries in all other
commands.
Example:
System-defined exceptions
User-defined exceptions
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.
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.
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
Procedures:
Executable Part
2
This is a mandatory part and contains statements that perform the
designated action.
Exception-handling
This is an optional part. It contains the code that handles run-time
3
errors.
Creating a Procedure:
Syntax:
Eg:
Execute Procedure:
BEGIN
procedure-name;
END;
Eg:
BEGIN
greetings;
END;
Drop procedure:
Eg:
2 OUT
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:
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:
Fetching the cursor for retrieving data – (Eg: FETCH c_customers INTO c_id,
c_name, c_addr;)
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;
----------