DBMS Paper
DBMS Paper
DBMS Paper
Advantages of DBMS
The database management system has promising potential advantages, which are
explained below:
1. Controlling Redundancy: In file system, each application has its own private files,
which cannot be shared between multiple applications. 1: his can often lead to
considerable redundancy in the stored data, which results in wastage of storage space.
By having centralized database most of this can be avoided. It is not possible that all
redundancy should be eliminated. Sometimes there are sound business and technical
reasons for· maintaining multiple copies of the same data. In a database system,
however this redundancy can be controlled.
2. Integrity can be enforced: Integrity of data means that data in database is always
accurate, such that incorrect information cannot be stored in database. In order to
maintain the integrity of data, some integrity constraints are enforced on the database.
A DBMS should provide capabilities for defining and enforcing the constraints.
3. Inconsistency can be avoided : When the same data is duplicated and changes are
made at one site, which is not propagated to the other site, it gives rise to inconsistency
and the two entries regarding the same data will not agree. At such times the data is said
to be inconsistent. So, if the redundancy is removed chances of having inconsistent data
is also removed.
4. Data can be shared: As explained earlier, the data about Name, Class, Father
__name etc. of General_Office is shared by multiple applications in centralized DBMS
as compared to file system so now applications can be developed to operate against the
same stored data. The applications may be developed without having to create any new
stored files.
5. Standards can be enforced : Since DBMS is a central system, so standard can be
enforced easily may be at Company level, Department level, National level or
International level. The standardized data is very helpful during migration or
interchanging of data. The file system is an independent system so standard cannot be
easily enforced on multiple independent applications.
6. Restricting unauthorized access: When multiple users share a database, it is likely
that some users will not be authorized to access all information in the database. For
example, account office data is often considered confidential, and hence only authorized
persons are allowed to access such data. In addition, some users may be permitted only
to retrieve data, whereas other are allowed both to retrieve and to update. Hence, the
type of access operation retrieval or update must also be controlled. Typically, users or
user groups are given account numbers protected by passwords, which they can use to
gain access to the database. A DBMS should provide a security and authorization
subsystem, which the DBA uses to create accounts and to specify account restrictions.
The DBMS should then enforce these restrictions automatically.
7. Solving Enterprise Requirement than Individual Requirement: Since many
types of users with varying level of technical knowledge use a database, a DBMS should
provide a variety of user interface. The overall requirements of the enterprise are more
important than the individual user requirements. So, the DBA can structure the database
system to provide an overall service that is "best for the enterprise".
For example: A representation can be chosen for the data in storage that gives fast access
for the most important application at the cost of poor performance in some other
application. But, the file system favors the individual requirements than the enterprise
requirements
8. Providing Backup and Recovery: A DBMS must provide facilities for recovering
from hardware or software failures. The backup and recovery subsystem of the DBMS
is responsible for recovery. For example, if the computer system fails in the middle of
a complex update program, the recovery subsystem is responsible for making sure that
the .database is restored to the state it was in before the program started executing.
9. Cost of developing and maintaining system is lower: It is much easier to respond
to unanticipated requests when data is centralized in a database than when it is stored
in a conventional file system. Although the initial cost of setting up of a database can
be large, but the cost of developing and maintaining application programs to be far
lower than for similar service using conventional systems. The productivity of
programmers can be higher in using non-procedural languages that have been
developed with DBMS than using procedural languages.
10. Data Model can be developed : The centralized system is able to represent the
complex data and interfile relationships, which results better data modeling properties.
The data madding properties of relational model is based on Entity and their
Relationship, which is discussed in detail in chapter 4 of the book.
11. Concurrency Control : DBMS systems provide mechanisms to provide concurrent
access of data to multiple users.
Disadvantages of DBMS
The disadvantages of the database approach are summarized as follows:
1. Complexity : The provision of the functionality that is expected of a good DBMS
makes the DBMS an extremely complex piece of software. Database designers,
developers, database administrators and end-users must understand this functionality to
take full advantage of it. Failure to understand the system can lead to bad design
decisions, which can have serious consequences for an organization.
2. Size : The complexity and breadth of functionality makes the DBMS an extremely
large piece of software, occupying many megabytes of disk space and requiring
substantial amounts of memory to run efficiently.
3. Performance: Typically, a File Based system is written for a specific application,
such as invoicing. As result, performance is generally very good. However, the DBMS
is written to be more general, to cater for many applications rather than just one. The
effect is that some applications may not run as fast as they used to.
4. Higher impact of a failure: The centralization of resources increases the
vulnerability of the system. Since all users and applications rely on the ~vailabi1ity of
the DBMS, the failure of any component can bring operations to a halt.
5. Cost of DBMS: The cost of DBMS varies significantly, depending on the
environment and functionality provided. There is also the recurrent annual maintenance
cost.
6. Additional Hardware costs: The disk storage requirements for the DBMS and the
database may necessitate the purchase of additional storage space. Furthermore, to
achieve the required performance it may be necessary to purchase a larger machine,
perhaps even a machine dedicated to running the DBMS. The procurement of additional
hardware results in further expenditure.
7. Cost of Conversion: In some situations, the cost oftlle DBMS and extra hardware
may be insignificant compared with the cost of converting existing applications to run
on the new DBMS and hardware. This cost also includes the cost of training staff to use
these new systems and possibly the employment of specialist staff to help with
conversion and running of the system. This cost is one of the main reasons why some
organizations feel tied to their current systems and cannot switch to modern database
technology.
The network model was the first attempt to address the inefficiencies of the
hierarchical model. In the network model, you could create a network showing how
data related to each other. The network model never caught on, and was eventually
replaced by the relational model. Click here for more information on the network
model.
The relational model has proven to be the most efficient and most flexible database
model in use today. There are many advantages of the relational model over the other
models, which is why the most popular databases in use today employ this
methodology. Click here for more information on the relational model.
1 e List and explain Codd’s rule in detail.
Ans
.
1f Explain ER diagram and its components. Give the distinction between disjoint,
overlapping, total and partial constraints. Draw E-R diagram for the following
situations that correctly models this domain and its constraints.
A small racing league want a database to keep track of teams, drivers, races and
scores in the league. The league is run for teams, which are identified by their names.
Each team has one or more drivers signed up, and each driver is registered with the
league and has a unique league licence number. First and last names of the drivers
should also be included. A driver may only participate for a single team throughout
the season. Races are identified simply by the dates when they are run. For each race,
the league also wants to store the venue where it took place. Drivers participate in
races, and for each participating driver the database should store the total race time
for that driver, and the league score they got from that race.
Ans. An E-R diagram can express the overall logical structureofa databasegraphically. E-R
diagramsaresimpleand clear—qualities that may well account in large part for the
widespreaduse of the E-R model.
An E-R diagram consists of the following major components:
Rectangles divided into two parts represententity sets.The firstpart,which
inthistextbookisshadedblue,containsthenameoftheentityset.Thesecond part contains
the names of all the attributes of the entity set.
•Diamonds represent relationship sets.
• Undivided rectangles represent the attribute so far elationshipset.Attributes that are
part of the primary key are underlined.
• Lines link entitysets to relationship sets.
• Dashed lines link attributes of a relationship set to the relationship set.
• Double lines indicate total participation of an entity in a relationship set.
• Double diamonds represent identifying relationship sets linked to weak entitysets.
Disjoint. A disjointness constraint requires that an entity belong to no more than one
lower-level entity set. In our example, student entity can satisfy only one condition
for the student type attribute; an entity can be either a graduate student or an
undergraduate student, but cannot be both.
• Overlapping. In overlapping generalizations, the same entity may belong to More
than one lower-level entity set within a single generalization. For an e.g., consider the
employee work-team example, and assume that Certain employees participate in
more than one work team. Given employee May therefore appear in more than one of
the team entity sets that are lower level Entity sets of employee. Thus, the
generalization is overlapping.
Final constraint, the completeness constraint on a generalization or specialization,
Specifies whether or not an entity in the higher-level entity set must belong
to at least one of the lower-level entity sets within the generalization/specialization.
This constraint may be one of the following:
• Total generalization or specialization. Each higher-level entity must belong
to a lower-level entity set.
• Partial generalization or specialization. Some higher-level entities may not
Belong to any lower-level entity set.
2a Why are entity integrity and referential integrity important in a database? Explain in
detail.
Ans. Referential and entity integrity are crucial to preserving valid relationships between
tables and data within a database. SQL queries will begin to fail if the data keys that
connect the dots between their relationships do not match. If an entity or table is relying
on the keys in another entity or table, then relationships between the two can be lost if
bad data is entered into one location. For instance, referential integrity can be used to
ensure foreign key values are valid. For instance, a database table listing all the parts
installed on a specific aircraft should have referential integrity connecting the part
numbers to a table listing valid part numbers for that aircraft so that in the event of a bad
part number being “fat-fingered” into the database, the RBDMS will return an error
concerning the bad data .
INTEGRITY RULES
2b Explain why normalization is necessary in database system & also explain database
anomalies in detail.
You are given the following set of functional dependencies for a relation
R(A,B,C,D,E,F),
F ={AB→C,DC →AE,E →F }
a. What are the keys of this relation?
b. Is this relation in BCNF? If not, explain why by showing one violation.
c. Is the decomposition (A, B, C, D) (B, C, D, E, F) a dependency preserving
decomposition? If not, explain briefly.
Ans. Database normalization is the process of organizing the attributes and tables of a
relational database to minimize data redundancy.
If a database design is not perfect it may contain anomalies, which are like a bad
dream for database itself. Managing a database with anomalies is next to impossible.
Normalization is a method to remove all these anomalies and bring database to
consistent state and free from any kinds of anomalies.
At a basic level, normalization is the simplification of any bulk quantity to an optimum
value. In the digital world, normalization usually refers to database normalization
which is the process of organizing the columns (attributes) and tables (relations) of a
relational database to minimize data repetition. In the process of database creation,
normalization involves organizing data into optimal tables in such a way that the
results obtained are always unambiguous and clear in concept.
Though database normalization can have the effect of duplication of data, it
completely removes data redundancy. This process can be considered as a refinement
process after the initial identification of data objects that are to be included in the
database. It involves identification of the relationship between the data objects and
defining the tables required and the columns to be added within each table.
If a database design is not done properly, it may cause several anomalies to occur in it.
Normalization is essential for removing various anomalies like:
Anomalies in Database
1) Update Anomalies: When several instances of the same data are scattered across the
database without proper relationship/link, it could cause strange conditions where a
few of the instances will get updated with new values whereas some of them will not.
This leaves the database in an inconsistent state.
2) Deletion Anomalies: Incomplete deletion of a particular data section which leaves
some residual instances. The database creator remains unaware of such unwanted data
as it is present at a different location.
3) Insertion Anomalies: This occurs when an attempt to insert data into a non-existent
record.
Paying attention to these anomalies can help to maintain a consistent database.
2c Write short note on Cartesian product with its syntax and example.
Ans. The Cartesian-product operation, denoted by a cross (×), allows us to combine
information from any two relations. We write the Cartesian product of relations r1 and
r2 as r1 × r2.A relation is by definition a subset of a Cartesian product of a setof
domains. From that definition, we should already have an intuition about thedefinition
of the Cartesian-product operation. However, since the same attributename may appear
in both r1 and r2, we need to devise a naming schema todistinguish between these
attributes. We do so here by attaching to an attributethe name of the relation from
which the attribute originally came.
For example,the relation schema for r = instructor × teaches is:
(instructor.ID, instructor.name, instructor.dept name, instructor.salary
teaches.ID, teaches.course id, teaches.sec id, teaches.semester, teaches.year)
With this schema, we can distinguish instructor.ID from teaches.ID. For those
attributes that appear in only one of the two schemas, we shall usually drop the relation-
name prefix. This simplification does not lead to any ambiguity. We canthen write the
relation schema for r as:
(instructor.ID, name, dept name, salary
teaches.ID, course id, sec id, semester, year)
This naming convention requires that the relations that are the arguments of the
Cartesian-product operation have distinct names.
r ∪ s = { t | t ∈ r or t ∈ s}
Notation − r U s
Where r and s are either database relations or relation result set (temporary relation).
Intersect operator ( ):
The intersect operators is denoted by the symbol ( ). The sql intersect operator is used
to combine two select statement but retrurns rows only from the first select statement
that are identical to a row in the second select statement. This means INTERSECT
returns only common rows returned by the two select statement.
Notation − r s
Notation − r − s
Order Relational Algebra describes the order Relational Calculus does not
performed.
language.
3a What are constraints? What are the different types of constraints? Explain.
Ans. SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This ensures the
accuracy and reliability of the data in the table. If there is any violation between the
constraint and the data action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a
column, and table level constraints apply to the whole table.
3b When can a view be updated? Explain the syntax of updating a view. And also state the
difference between views and table.
An A view be updated: ---
s.
1. The view is defined based on one and only one table.
2. The view must include the PRIMARY KEY of the table based upon which the view
has been created.
3. The view should not have any field made out of aggregate functions.
4. The view must not have any DISTINCT clause in its definition.
5. The view must not have any GROUP BY or HAVING clause in its definition.
7. If the view you want to update is based upon another view, the later should be
updatable.
8. Any of the selected output fields (of the view) must not use constants, strings or value
expressions.
Syntax:
Parameters:
As
Where deptno=10;
VIEWS TABLES
1. There is one type of relation which is not a part 1. A base relation is a relation that is not a derived
of the physical database. relation.
2. It has no direct or physical relation with the 2. While it can manipulate the conceptual or
database. relations stored in the data.
3. Views can be used to provide security 3. It does not provide security.
mechanism.
4. Modification through a view (e.g. insert, update, 4. Modification may be done with a base relation.
delete) not permitted).
3d Write in brief about SQL with its advantages and also explain NULL value concept.
How NULL values are different from EMPTY values.
Ans. SQL is Structured Query Language, which is a computer language for storing,
manipulating and retrieving data stored in a relational database.
SQL is the standard language for Relational Database System. All the Relational
Database Management Systems (RDMS) like MySQL, MS Access, Oracle, Sybase,
Informix, Postgres and SQL Server use SQL as their standard database language. SQL
is widely popular because it offers the following advantages −
• Allows users to define the data in a database and manipulate that data.
• Allows to embed within other languages using SQL modules, libraries & pre-
compilers.
The NULL is the term used to represent a missing value. A NULL value in a table is a
value in a field that appears to be blank.
A field with a NULL value is a field with no value. It is very important to understand
that a NULL value is different than a zero value or a field that contains spaces.
Syntax
SQL> 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)
);
Here, NOT NULL signifies that column should always accept an explicit value of the
given data type. There are two columns where we did not use NOT NULL, which means
these columns could be NULL.
A field with a NULL value is the one that has been left blank during the record creation.
NULL values are different from EMPTY values:--
An empty string is a value, but is just empty. NULL is special to a database. NULLhas
no bounds, it can be used for string , integer , date , etc. fields in a database. NULL isn't
allocated any memory, the string with NULL value is just a pointer which is pointing
to nowhere in memory. A NULL value represents the absence of a value for a record in
a field (other software calls it a missing value). An empty value is a "field-formatted"
value with no significant data in it. Null has no bounds, it can be used for string, integer,
date, etc. fields in a database. Empty string is just regarding a string. If you have no
value for a field, use null, not an empty string.
3e Define Join and List its type and explain any two in details. Consider the following
relation and solve the below query:
Sample table: departments
( DEPARTMENT_ID,DEPARTMENT_NAME ,MANAGER_ID , LOCATION_ID )
Sample table: employees
(EMPLOYEE_ID , FIRST_NAME , LAST_NAME , EMAIL , PHONE_NUMBER
,HIRE_DATE , JOB_ID , SALARY , COMMISSION_PCT , MANAGER_ID ,
DEPARTMENT_ID )
i) Write a query in SQL to display the first name, last name, department number, and
department name for each employee.
ANS An SQL join clause combines columns from one or more tables in a relational
database. It creates a set that can be saved as a table or used as it is. A JOIN is a means
for combining columns from one (self-join) or more tables by using values common to
each.
Oracle proprietary joins are:
• Equijoin
• Non-equijoin
• Outer join
• Self join
ANSI-standard SQL specifies five types of JOIN: INNER, LEFT OUTER, RIGHT
OUTER, FULL OUTER and CROSS. As a special case, a table (base table, view, or
joined table) can JOIN to itself in a self-join.
Defining Joins
When data from more than one table in the database is required, a join condition is
used. Rows in one table can be joined to rows in another table according to common
values existing in corresponding columns, that is, usually primary and foreign key
columns.
To display data from two or more related tables, write a simple join condition in the
WHERE clause.
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column1 = table2.column2;
In the syntax:
table1.column denotes the table and column from which data is
retrieved
table1.column1 = is the condition that joins (or relates) the tables together
table2.column2
• When writing a SELECT statement that joins tables, precede the column name with
the table name for clarity and to enhance database access.
• If the same column name appears in more than one table, the column name must
be prefixed with the table name.
• To join n tables together, you need a minimum of n-1 join conditions. For example,
to join four tables, a minimum of three joins is required. This rule may not apply if
your table has a concatenated primary key, in which case more than one column is
required to uniquely identify each row.
3f Differentiate between ANY and ALL operators with example & also explain
hierarchical query.
ANS ANY ALL
:
1. The ANY operator returns TRUE if any of the The ALL operator returns TRUE if all of th
subquery values meet the condition. subquery values meet the condition.
2. Evaluates to FALSE if the query returns no 2. Evaluates to TRUE if the query returns no rows
rows.
ANY compares a value to each value in a list or results from a query and evaluates to
true if the result of an inner query contains at least one row. ANY must be preceded
by comparison operators. Suppose using greater than ( >) with ANY means greater
than at least one value.
Syntax:
Name Description
comparison_operator Compares the expression to the subquery. The comparison must be a standard
comparison operator (=, <>, !=, >, >=, <, or <=).
Syntax:
HIERARCHAIL QUERIES:--
A hierarchial query is the one that works on tree like relationship.It loops
through a result set and returns rows in a hierarchial sequence.It is used when a parent
has a child element and each child elememt may have one or more child elements.
Syntax:--
SELECT column_list
FROM tablename
[WHERE Search_condition]
[ORDER BY list]
FROM emp
Where empid<7500
View Serializability
o A schedule will view serializable if it is view equivalent to a serial schedule.
o If a schedule is conflict serializable, then it will be view serializable.
o The view serializable which does not conflict serializable contains blind writes.
View Equivalent
Two schedules S1 and S2 are said to be view equivalent if they satisfy the following
conditions:
1. Initial Read
An initial read of both schedules must be the same. Suppose two schedule S1 and S2.
In schedule S1, if a transaction T1 is reading the data item A, then in S2, transaction T1
should also read A.
Above two schedules are view equivalent because Initial read operation in S1 is done
by T1 and in S2 it is also done by T1.
2. Updated Read
3. Final Write
A final write must be the same between both the schedules. In schedule S1, if a
transaction T1 updates A at last then in S2, final writes operations should also be done
by T1.
Above two schedules is view equal because Final write operation in S1 is done by T3
and in S2, the final write operation is also done by T3.
Example:
Schedule S
Schedule S1
In both schedules S and S1, there is no read except the initial read that's why we don't
need to check that condition.
The initial read operation in S is done by T1 and in S1, it is also done by T1.
The final write operation in S is done by T3 and in S1, it is also done by T3. So, S and
S1 are view Equivalent.
The first schedule S1 satisfies all three conditions, so we don't need to check another
schedule.
1. T1 → T2 → T3
4c What are concurrent transaction? Explain in details the main features of concurrent
execution.
ANS The database system must control the interaction among the concurrent transaction to
prevent them from destroying the consistency of the database is termed as concurrent
control scheme.
The main features of the concurrent execution are given below:-
1.Improved throughput and resources utilization
2.Reducing waiting time
4d What are some disadvantages of time stamping methods for concurrency control?
And also explain timestamp ordering protocol in detail.
ANS
The locking protocols that we have described thus far determine the order between
every pair of conflicting transactions at execution time by the first lock that both
members of the pair request that involves incompatible modes. Another method for
determining the serializability order is to select an ordering among transactions
inadvance.The mostcommon method fordoingsoistouse a timestamp-ordering
scheme.
15.4.1 Timestamps With each transaction T i in the system, we associate a unique
fixed timestamp, denoted by TS(T i). This timestampis assigned by the database
systembefore the transaction T i starts execution. If a transaction T i has been
assigned timestamp TS(T i), and a new transaction Tj enters the system, then TS(T i)
< TS(Tj). There are two simple methods for implementingthis scheme:
1. Use the value of thes ¯
ystem clock as the timestamp; that is, a transaction’s timestampisequaltothe
valueoftheclockwhenthetransaction entersthe system. 2. Use a logical counter that is
incremented after a new timestamp has been assigned; that is, a transaction’s
timestamp is equal to the value of the counter when the transaction enters the system.
4e What benefit does rigorous two-phase locking provide? How does it compare with
other forms of two-phase locking?
ANS Rigorous two-phase locking has the advantages of strict 2PL. In addition
it has the property that for two conflicting transactions, their commit order
is their serializability order. In some systems users might expect this behavior.
Also, it's implementation is easier than strict 2PL.
In rigorous two-phase locking protocol a transaction is not allowed to release any
lock ( shared and exclusive until it commit ). This means that until the transaction
commits , other transactions might aquired a shared lock on a data items , on which
the un-commited transaction has shared lock but can not aquire any lock on an data
items , on which the uncommited transaction has an exclusive lock.
• Two-Phase Locking (2PL) is a concurrency control method which divides the
execution phase of a transaction into three parts.
• It ensures conflict serializable schedules.
• If read and write operations introduce the first unlock operation in the transaction,
then it is said to be Two-Phase Locking Protocol.
Syntax
cursor_variable_name
A PL/SQL cursor variable previously declared within the current scope. Only the value
of another cursor variable can be assigned to a cursor variable.
db_table_name.column_name
A table and column that must be accessible when the declaration is elaborated.
object_name
An instance of an object type, previously declared within the current scope.
record_name
A user-defined or %ROWTYPE record, previously declared within the current scope.
record_name.field_name
A field in a user-defined or %ROWTYPE record, previously declared within the current
scope.
variable_name
A variable, previously declared in the same scope.
The %TYPE attribute is particularly useful when declaring variables, fields, and
parameters that refer to database columns. Your code can keep working even when the
lengths or types of the columns change.The NOT NULL column constraint is not
inherited by items declared using %TYPE.Examples
DECLARE
EMPLOYEEID EMP.EMPID%TYPE;
BEGIN
SELECT EMPID INTO EMPLOYEEID FROM EMP
WHERE ENAME = ‘KING’;
DBMS_OUTPUT.PUT_LINE(EMPLOYEEID);
END;
/
%ISOPEN:--Always returns FALSE for implicit cursors, because Oracle closes the
SQL cursor automatically after executing its associated SQL statement.
DECLARE
Huge_quantity EXCEPTION;
CURSOR product_quantity is
SELECT p.product_name as name, sum (o.total_units) as units
FROM order_tems o, product p
WHERE o.product_id = p.product_id;
Quantity order_tems.total_units%type;
Up_limit CONSTANT order_tems.total_units%type: = 20;
Message VARCHAR2 (50);
BEGIN
FOR product_rec in product_quantity LOOP
Quantity: = product_rec. Units;
IF quantity > up_limit THEN
RAISE huge_quantity;
ELSIF quantity < up_limit THEN
v_message:= 'The number of unit is below the discount limit.’
END IF;
Dbms_output.put_line (message);
END LOOP;
EXCEPTION
WHEN huge_quantity THEN
raise_application_error (-2100, 'The number of unit is above the discount
limit.');
END;
/
5d List & explain the various features of PL/SQL & also differentiate between
Anonymous blocks and Subprograms.
Ans. High performance: PL/SQL is high performance transaction processing language.
• Code Re-usability: It support code re-usability, it means no need to write code
again and again same like SQL.
• Error Handling: when any error are occurred then it return user friendly error
message.
• Procedural Language Capability: It consists of procedural language constructs
such as conditional statements (if...else) and loops statements (for loop)
• Block Statement: It consists of blocks of code, which can be nested within each
other. Each and every block forms a unit of a task or a logical module.
• Better performance: oracle engine processes multiple SQL statements
simultaneously as a single block, due to this reducing network traffic.
• Declare variable: It give you control to declare variable and access them within
the block.
5e What are packages in PL/SQL? List and explain the various advantages of packages.
Create a package to display the employee name and salary.
Ans. Packages bundle related PL/SQL types, items, and subprograms into one container. For
example, a Human Resources package can contain hiring and firing procedures,
commission and bonus functions, and tax exemption variables.
A package usually has a specification and a body, stored separately in the database.
The specification is the interface to your applications. It declares the types, variables,
constants, exceptions, cursors, and subprograms available for use. The package
specification may also include PRAGMAs, which are directives to the compiler.
The body fully defines cursors and subprograms, and so implements the specification.
The package itself cannot be called, parameterized, or nested. Still, the format of a
package is similar to that of a subprogram. Once written and compiled, the contents can
be shared by many applications.
When you call a packaged PL/SQL construct for the first time, the whole package is
loaded into memory. Thus, later calls to constructs in the same package require no disk
input/output (I/O).
Advantages of package:--
-----------------------
A. Modularity:--Encapsulate related constructs.
B. Easier Application Design: -- Code and compile specification and body separately.
E. Better Performance:--The entire package is loaded into memory when the package
is first referenced. There is only one copy in memory for all users. The dependency
hierarchy is simplified.
5f What are triggers? Explain the syntax for creating a trigger in PL/SQL.List the
benefits of creating trigger in PL/SQL.
Ans. Triggers are stored programs, which are automatically executed or fired when some
events occur. Triggers are, in fact, written to be executed in response to any of the
following events –
• A database manipulation (DML) statement (DELETE, INSERT, or
UPDATE)
[OF col_name]
ON table_name
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
Where,
• CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an
existing trigger with the trigger_name.
• {BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be
executed. The INSTEAD OF clause is used for creating trigger on a view.
• [OF col_name] − This specifies the column name that will be updated.
• [ON table_name] − This specifies the name of the table associated with the
trigger.
• [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be
executed for each row being affected. Otherwise the trigger will execute just
once when the SQL statement is executed, which is called a table level trigger.
• WHEN (condition) − This provides a condition for rows for which the trigger
would fire. This clause is valid only for row-level triggers.
Benefits of Triggers