0% found this document useful (0 votes)
173 views44 pages

Unit 3 Advanced SQL

This document discusses advanced SQL features including accessing SQL from programming languages using dynamic and embedded SQL. Dynamic SQL constructs queries as strings at runtime while embedded SQL identifies queries at compile time using a preprocessor. The document also covers integrity constraints like not null, unique, and check constraints which ensure data consistency and prevent accidental data damage. It provides examples of each constraint type and explains how they are declared in CREATE TABLE statements.

Uploaded by

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

Unit 3 Advanced SQL

This document discusses advanced SQL features including accessing SQL from programming languages using dynamic and embedded SQL. Dynamic SQL constructs queries as strings at runtime while embedded SQL identifies queries at compile time using a preprocessor. The document also covers integrity constraints like not null, unique, and check constraints which ensure data consistency and prevent accidental data damage. It provides examples of each constraint type and explains how they are declared in CREATE TABLE statements.

Uploaded by

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

UNIT 3

ADVANCED SQL
Some of the advanced features of SQL are
Accessing SQL from a Programming Language: -
SQL provides a powerful declarative query language. Writing queries in SQL is usually much easier
than coding the same queries in a general-purpose programming language. However, a database
programmer must have access to a general-purpose programming language for at least two
reasons:
1. Not all queries can be expressed in SQL, since SQL does not provide the full expressive power of a
general-purpose language. That is, there exist queries that can be expressed in a language such as
C, Java, or Cobol that cannot be expressed in SQL. To write such queries, we can embed SQL
within a more powerful language.
2. Non declarative actions— such as printing a report, interacting with a user, or sending the
results of a query to a graphical user interface — cannot be done from within SQL. Applications
usually have several components, and querying or updating data is only one component; other
components are written in general-purpose programming languages. For an integrated
application, there must be a means to combine SQL with a general-purpose programming
language.

There are two approaches to accessing SQL from a general-purpose programming language:
• Dynamic SQL: A general-purpose program can connect to and communicate with a database
server using a collection of functions (for procedural languages) or methods (for object-oriented
languages). Dynamic SQL allows the program to construct an SQL query as a character string at
runtime, submit the query, and then retrieve the result into program variables a tuple at a time.
The dynamic SQL component of SQL allows programs to construct and submit SQL queries at
runtime.
The two standards for connecting to an SQL database and performing queries and updates. One,
JDBC, is an application program interface for the Java language. The other, ODBC, is an
application program interface originally developed for the C language, and subsequently
extended to other languages such as C++, C#, and Visual Basic.
• Embedded SQL: Like dynamic SQL, embedded SQL provides a means by which a program can
interact with a database server. However, under embedded SQL, the SQL statements are
identified at compile time using a preprocessor. The preprocessor submits the SQL statements to
the database system for pre compilation and optimization; then it replaces the SQL statements
in the application program with appropriate code and function calls before invoking the
programming-language compiler.

What is Dynamic SQL?


When the pattern of database access is known in advance then static SQL is very adequate to serve
us. Sometimes, in many applications we may not know the pattern of database access in advance.
For example, a report writer must be able to decide at run time that which SQL statements will be
needed to access the database. Such a need can’t be fulfilled with static SQL and requires an
advanced form of static SQL known as dynamic SQL. There are several limitations in static SQL.
Although using the host variables (host variables allows us to input values for search condition at
run time), we can achieve a little bit dynamicness, for e.g.,
exec sql select tname, gender from teacher where salary > :sal;
Here the salary will be asked on run time. But getting column name or table asked at run time not possible
with embedded SQL. For having such a feature we need dynamic SQL.

Department of IT Page 1
Need for Embedded SQL in DBMS
When you embed SQL with another language. The language that is embedded is known as host
language and the SQL standard which defines the embedding of SQL is known as embedded SQL.
• The result of a query is made available to the program which is embedded as one tuple or record
at a time.
• For identification of this, we request to the preprocessor via EXEC SQL statement: EXEC SQL
embedded SQL statement END-EXEC
• Its statements are declare cursor, fetch and open statements.
• It can execute the update, insert and delete statement.

Difference between Static and Dynamic SQL


Static or Embedded SQL are SQL statements in an application that do not change at runtime and,
therefore, can be hard-coded into the application. Dynamic SQL is SQL statements that are
constructed at runtime; for example, the application may allow users to enter their own queries.

Below mentioned are the basic differences between Static or Embedded and Dynamic or
Interactive SQL:

STATIC (EMBEDDED) SQL DYNAMIC (INTERACTIVE) SQL

In Static SQL, how database will be accessed is


predetermined in the embedded SQL In Dynamic SQL, how database will be
statement. accessed is determined at run time.

It is more swift and efficient. It is less swift and efficient.

SQL statements are compiled at compile time. SQL statements are compiled at run time.

Parsing, Validation, Optimization and Parsing, Validation, Optimization and


Generation of application plan are done at Generation of application plan are done at
compile time. run time.

It is generally used for situations where data is It is generally used for situations where data
distributed uniformly. is distributed non uniformly.

EXECUTE IMMEDIATE, EXECUTE and EXECUTE IMMEDIATE, EXECUTE and


PREPARE statements are not used. PREPARE statements are used.

It is less flexible. It is more flexible.

Limitation of Dynamic SQL: We cannot use some of the SQL statements dynamically.
Performance of these statements is poor as compared to Static SQL.
Limitations of Static SQL: They do not change at runtime thus are hard-coded into applications.

INTEGRITY CONSTRAINTS
Integrity constraints ensure that changes made to the database by authorized users do not result
in a loss of data consistency. Thus, integrity constraints guard against accidental damage to the
database.
Examples of integrity constraints are:
• An instructor name cannot be null.
• No two instructors can have the same instructor ID.
Department of IT Page 2
• Every department name in the course relation must have a matching depart- ment name in the
department relation.
• The budget of a department must be greater than $0.00.

Integrity constraints are usually identified as part of the database schema design process, and
declared as part of the create table command used to create relations. However, integrity
constraints can also be added to an existing relation by using the command alter table table-name
add constraint, where constraint can be any constraint on the relation. When such a command is
executed, the system first ensures that the relation satisfies the specified constraint. If it does, the
constraint is added to the relation; if not, the command is rejected.

Constraints on a Single Relation


The create table command may also include integrity-constraint statements. In addition to the
primary-key constraint, there are a number of other ones that can be included in the create table
command. The allowed integrity constraints include
• not null
• unique
• check(<predicate>)

Not Null Constraint: -


Consider a tuple in the student relation where name is null. Such a tuple gives student
information for an unknown student; thus, it does not contain useful information. Similarly, we
would not want the department budget to be null. In cases such as this, we wish to forbid null
values, and we can do so by restricting the domain of the attributes name and budget to exclude null
values, by declaring it as follows:

name varchar(20) not null


budget numeric(12,2) not null

The not null specification prohibits the insertion of a null value for the attribute. Any
database modification that would cause a null to be inserted in an attribute declared to be not null
generates an error diagnostic.
There are many situations where we want to avoid null values. In particular, SQL prohibits
null values in the primary key of a relation schema. Thus, in our university example, in the
department relation, if the attribute dept name is declared as the primary key for department, it
cannot take a null value. As a result it would not need to be declared explicitly to be not null.

Unique Constraint: -
SQL also supports an integrity constraint: unique ( Aj1 , Aj2 , . . . , Ajm )
The unique specification says that attributes Aj1 , Aj2 ,..., Ajm form a candidate key; that is,
no two tuples in the relation can be equal on all the listed attributes. However, candidate key
attributes are permitted to be null unless they have explicitly been declared to be not null. Recall
that a null value does not equal any other value.

The check Clause: -


When applied to a relation declaration, the clause check( P) specifies a predicate P that must
be satisfied by every tuple in a relation.
A common use of the check clause is to ensure that attribute values satisfy specified
conditions, in effect creating a powerful type system. For instance, a clause check (budget > 0) in
the create table command for relation department would ensure that the value of budget is
nonnegative.

Department of IT Page 3
As another example, consider the following:

Here, we use the check clause to simulate an enumerated type, by specifying that semester must be
one of ’Fall’, ’Winter’, ’Spring’, or ’Summer’. Thus, the check clause permits attribute domains to be
restricted in powerful ways that most programming-language type systems do not permit.

Referential Integrity: -
Often, we wish to ensure that a value that appears in one relation for a given set of
attributes also appears for a certain set of attributes in another relation. This condition is called
referential integrity.
Foreign keys can be specified as part of the SQL create table statement by using the foreign
key clause. We illustrate foreign-key declarations by using the SQL DDL definition of part of our
university database, shown in the below figure. The definition of the course table has a declaration
“foreign key (dept name) references department”. This foreign-key declaration specifies that for
each course tuple, the department name specified in the tuple must exist in the department relation.
Without this constraint, it is possible for a course to specify a nonexistent department name.
By default, in SQL a foreign key references the primary-key attributes of the referenced
table. SQL also supports a version of the references clause where a list of attributes of the
referenced relation can be specified explicitly.
We can use the following short form as part of an attribute definition to declare that the
attribute forms a foreign key:
dept name varchar(20) references department
When a referential-integrity constraint is violated, the normal procedure is to reject the
action that caused the violation. However, a foreign key clause can specify that if a delete or
update action on the referenced relation violates the constraint, then, instead of rejecting the
action, the system must take steps to change the tuple in the referencing relation to restore the
constraint.

Department of IT Page 4
NESTED SUBQUERIES: -
SQL provides a mechanism for nesting subqueries. A subquery is a select-from where expression
that is nested within another query.

Set Membership: -
SQL allows testing tuples for membership in a relation. The in connective tests for set membership,
where the set is a collection of values produced by a select clause. The not in connective tests for
the absence of set membership.
Consider the query “Find all the courses taught in the both the Fall 2009 and Spring 2010
semesters”. We begin by finding all courses taught in Spring 2010, and we write the subquery

We then need to find those courses that were taught in the Fall 2009 and that appear in the set of
courses obtained in the subquery. We do so by nesting the subquery in the where clause of an outer
query. The resulting query is

Department of IT Page 5
This example shows that it is possible to write the same query several ways in SQL. This flexibility
is beneficial, since it allows a user to think about the query in the way that seems most natural.

We use the not in construct in a way similar to the in construct. For example, to find all the courses
taught in the Fall 2009 semester but not in the Spring 2010 semester, we can write:

The in and not in operators can also be used on enumerated sets. The following query selects the
names of instructors whose names are neither “Mozart” nor “Einstein”.

Set Comparison: -
As an example of the ability of a nested subquery to compare sets, consider the query “Find the
names of all instructors whose salary is greater than at least one instructor in the Biology
department.”
The phrase “greater than atleast one” is represented in SQL by > some. This construct allows us to
write the query in a form that resembles closely our formulation of the query in English.

The subquery:

generates the set of all salary values of all instructors in the Biology department. The > some
comparison in the where clause of the outer select is true if the salary value of the tuple is greater
than atleast one member of the set of all salary values for instructors in Biology.
SQL also allows < some, <= some, >= some, = some, and<> some comparisons.

Department of IT Page 6
Now we modify our query slightly. Let us find the names of all instructors that have a salary value
greater than that of each instructor in the Biology department. The construct > all corresponds to
the phrase “greater than all”. Using this construct, we write the query as follows:

As it does for some, SQL also allows < all, <= all, >= all, = all, and<> all comparisons.

Test for Empty Relations : -


SQL includes a feature for testing whether a subquery has any tuples in its result. The exists
construct returns the value true if the argument subquery is non empty. Using the exists construct,
we can write the query “Find all courses taught in both the Fall 2009 semester and in the Spring
2010 semester” in still another way:

The above query also illustrates a feature of SQL where a correlation name from an outer query (S
in the above query), can be used in a subquery in the where clause. A subquery that uses a
correlation name from an outer query is called a correlated subquery.
We can test for the nonexistence of tuples in a subquery by using the not exists construct. We can
use the not exists construct to simulate the set containment (that is, superset)operation.

Test for the Absence of Duplicate Tuples: -


SQL includes a boolean function for testing whether a subquery has duplicate tuples in its result.
The unique construct returns the value true if the argument subquery contains no duplicate
tuples. Using the unique construct, we can write the query “Find all courses that were offered at
most once in 2009” as follows:

Note that if a course is not offered in 2009, the subquery would return an empty result, and the
unique predicate would evaluate to true on the empty set.
We can test for the existence of duplicate tuples in a subquery by using the not unique construct.

Department of IT Page 7
JOINS: -
The examples involve the two relations student and takes, shown in the below figures. Observe that
the attribute grade has a value null for the student with ID 98988, for the course BIO-301, section 1,
taken in Summer 2010. The null value indicates that the grade has not been awarded yet.

Join Conditions
SQL supports another form of join, in which an arbitrary join condition can be specified. The on
condition allows a general predicate over the relations being joined. This predicate is written like a
where clause predicate except for the use of the keyword on rather than where. Like the using
condition, the on condition appears at the end of the join expression. Consider the following query,
which has a join expression containing the on condition.

select *
from student join takes on student.ID= takes.ID;

The on condition above specifies that a tuple from student matches a tuple from takes if their ID
values are equal. The join expression in this case is almost the same as the join expression student
natural join takes, since the natural join operation also requires that for a student tuple and a takes
tuple to match. The one difference is that the result has the ID attribute listed twice, in the join result,
once for student and once for takes, even though their ID values must be the same.
In fact, the above query is equivalent to the following query (in other words, they generate
exactly the same results):

select *
from student, takes
where student.ID= takes.ID;

Outer Joins

Department of IT Page 8
Suppose we wish to display a list of all students, displaying their ID, and name, dept_name, and
tot_cred, along with the courses that they have taken. The following SQL query may appear to
retrieve the required information:

select *
from student natural join takes;

Unfortunately, the above query does not work quite as intended. Suppose that there is some
student who takes no courses. Then the tuple in the student relation for that particular student
would not satisfy the condition of a natural join with any tuple in the takes relation, and that
student’s data would not appear in the result. We would thus not see any information about
students who have not taken any courses. For example, in the student and takes relations of above
figures, note that student Snow, with ID 70557, has not taken any courses. Snow appears in
student, but Snow’s ID number does not appear in the ID column of takes. Thus, Snow does not
appear in the result of the natural join.
More generally, some tuples in either or both of the relations being joined may be “lost” in this
way. The outer join operation works in a manner similar to the join operations we have already
studied, but preserve those tuples that would be lost in a join, by creating tuples in the result
containing null values.
For example, to ensure that the student named Snow from our earlier example appears in the
result, a tuple could be added to the join result with all attributes from the student relation set to
the corresponding values for the student Snow, and all the remaining attributes which come from
the takes relation, namely course_id, sec_id, semester, and year, set to null. Thus the tuple for the
student Snow is preserved in the result of the outer join.

There are in fact three forms of outer join:


• The left outer join preserves tuples only in the relation named before (to the left of) the left
outer join operation.
• The right outer join preserves tuples only in the relation named after (to the right of) the right
outer join operation.
• The full outer join preserves tuples in both relations.

We now explain exactly how each form of outer join operates. We can compute the left outer-join
operation as follows. First, compute the result of the inner join as before. Then, for every tuple t in
the left-hand-side relation that does not match any tuple in the right-hand-side relation in the inner
join, add a tuple r to the result of the join constructed as follows:
• The attributes of tuple r that are derived from the left-hand-side relation are filled in with the
values from tuple t.
• The remaining attributes of r are filled with null values.
Figure below shows the result of:
select *
from student natural left outer join takes;

Department of IT Page 9
That result includes student Snow (ID 70557), unlike the result of an inner join, but the tuple for
Snow includes nulls for the attributes that appear only in the schema of the takes relation.
The right outer join is symmetric to the left outer join. Tuples from the right- hand-side
relation that do not match any tuple in the left-hand-side relation are padded with nulls and are
added to the result of the right outer join. Thus, if we rewrite our above query using a right outer
join and swapping the order in which we list the relations as follows:

select *
from takes natural right outer join student;

we get the same result except for the order in which the attributes appear in the result

Department of IT Page 10
The full outer join is a combination of the left and right outer-join types. After the operation
computes the result of the inner join, it extends with nulls those tuples from the left-hand-side
relation that did not match with any from the right-hand side relation, and adds them to the result.
Similarly, it extends with nulls those tuples from the right-hand-side relation that did not match
with any tuples from the left-hand-side relation and adds them to the result.

VIEWS: -
Aside from security concerns, we may wish to create a personalized collection of relations that is
better matched to a certain user’s intuition than is the logical model. We may want to have a list of
all course sections offered by the Physics department in the Fall 2009 semester, with the building
and room number of each section. The relation that we would create for obtaining such a list is:

SQL allows a “virtual relation” to be defined by a query, and the relation conceptually contains the
result of the query. The virtual relation is not pre computed and stored, but instead is computed by
executing the query when- ever the virtual relation is used.

Any such relation that is not part of the logical model, but is made visible to a user as a virtual
relation, is called a view. It is possible to support a large number of views on top of any given set of
actual relations.

Department of IT Page 11
View Definition
We define a view in SQL by using the create view command. To define a view, we must give the view
a name and must state the query that computes the view. The form of the create view command is:

where <query expression> is any legal query expression. The view name is represented by v. The
clerk who needs to access all data in the instructor relation, except salary. The clerk should not be
authorized to access the instructor relation. Instead, a view relation faculty can be made available to
the clerk, with the view defined as follows:

The view relation conceptually contains the tuples in the query result, but is not precomputed
and stored. Instead, the database system stores the query expression associated with the view
relation. Whenever the view relation is accessed, its tuples are created by computing the query
result. Thus, the view relation is created whenever needed, on demand.
To create a view that lists all course sections offered by the Physics department in the Fall 2009
semester with the building and room number of each section, we write:

Using Views in SQL Queries


Once we have defined a view, we can use the view name to refer to the virtual relation that the view
generates. Using the view physics fall 2009, we can find all Physics courses offered in the Fall 2009
semester in the Watson building by writing:

View names may appear in a query any place where a relation name may appear, The attribute
names of a view can be specified explicitly as follows:

The preceding view gives for each department the sum of the salaries of all the instructors at that
department. Since the expression sum(salary) does not have a name, the attribute name is specified
explicitly in the view definition.
Intuitively, at any given time, the set of tuples in the view relation is the result of evaluation of the
query expression that defines the view. Thus, if a view relation is computed and stored, it may
become out of date if the relations used to define it are modified. To avoid this, views are usually
implemented as follows. When we define a view, the database system stores the definition of the
view itself, rather than the result of evaluation of the query expression that defines the view.

Department of IT Page 12
Wherever a view relation appears in a query, it is replaced by the stored query expression. Thus,
whenever we evaluate the query, the view relation is recomputed.

Materialized Views
Certain database systems allow view relations to be stored, but they make sure that, if the actual
relations used in the view definition change, the view is kept up-to-date. Such views are called
materialized views.
For example, consider the view departments total salary. If the above view is materialized, its results
would be stored in the database. However, if an instructor tuple is added to or deleted from the
instructor relation, the result of the query defining the view would change, and as a result the
materialized view’s contents must be updated. Similarly, if an instructor’s salary is updated, the
tuple in departments total salary corresponding to that instructor’s department must be updated.
The process of keeping the materialized view up-to-date is called material- ized view
maintenance (or often, just view maintenance). View maintenance can be done immediately
when any of the relations on which the view is defined is updated. Some database systems,
however, per- form view maintenance lazily, when the view is accessed. Some systems update
materialized views only periodically; in this case, the contents of the materialized view may be stale,
that is, not up-to-date, when it is used, and should not be used if the application needs up-to-date
data. And some database systems permit the database administrator to control which of the above
methods is used for each materialized view.

Update of a View
Although views are a useful tool for queries, they present serious problems if we express updates,
insertions, or deletions with them. The difficulty is that a modification to the database expressed in
terms of a view must be translated to a modification to the actual relations in the logical model of
the database.
Suppose the view faculty, which we saw earlier, is made available to a clerk. Since we allow a
view name to appear wherever a relation name is allowed, the clerk can write:

This insertion must be represented by an insertion into the relation instructor, since instructor is the
actual relation from which the database system constructs the view faculty. However, to insert a tuple
into instructor, we must have some value for salary. There are two reasonable approaches to dealing
with this insertion:
• Reject the insertion, and return an error message to the user.
• Insert a tuple (’30765’, ’Green’, ’Music’, null) into the instructor relation.

Because of problems such as these, modifications are generally not permit- ted on view
relations, except in limited cases. Different database systems specify different conditions under
which they permit updates on view relations; see the database system manuals for details.
In general, an SQL view is said to be updatable (that is, inserts, updates or deletes can be
applied on the view) if the following conditions are all satisfied by the query defining the view:
• The from clause has only one database relation.
• The select clause contains only attribute names of the relation, and does not have any
expressions, aggregates, or distinct specification.
• Any attribute not listed in the select clause can be set to null; that is, it does not have a not null
constraint and is not part of a primary key.
• The query does not have a group by or having clause.

Department of IT Page 13
PROCEDURES & FUNCTIONS: -
"A procedures or function is a group or set of SQL and PL/SQL statements that perform a specific
task." A function and procedure is a named PL/SQL Block which is similar . The major difference
between a procedure and a function is, a function must always return a value, but a procedure may
or may not return a value.

Procedures: -
A procedure is a named PL/SQL block which performs one or more specific task. This is similar to a
procedure in other programming languages. A procedure has a header and a body.
The header consists of the name of the procedure and the parameters or variables passed to the
procedure. The body consists or declaration section, execution section and exception section
similar to a general PL/SQL Block. A procedure is similar to an anonymous PL/SQL Block but it is
named for repeated usage.

We can pass parameters to procedures in three ways:

Parameters Description

IN type These types of parameters are used to send values to stored procedures.

OUT type These types of parameters are used to get values from stored procedures.
This is similar to a return type in functions.

IN OUT type These types of parameters are used to send values and get values from stored
procedures.
A procedure may or may not return any value.

Syntax:
CREATE [OR REPLACE] PROCEDURE procedure_name (<Argument> {IN, OUT, IN OUT}
<Datatype>,…)
IS
Declaration section<variable, constant> ;
BEGIN
Execution section
EXCEPTION
Exception section
END
IS - marks the beginning of the body of the procedure and is similar to DECLARE in anonymous
PL/SQL Blocks.
The code between IS and BEGIN forms the Declaration section.
The syntax within the brackets [ ] indicate they are optional.
By using CREATE OR REPLACE together the procedure is created if no other procedure with the
same name exists or the existing procedure is replaced with the current code.
How to execute a Procedure?
There are two ways to execute a procedure:
• From the SQL prompt : EXECUTE [or EXEC] procedure_name;
• Within another procedure – simply use the procedure name : procedure_name;

Example: -
create table named emp have two column id and salary with number datatype.
Department of IT Page 14
CREATE OR REPLACE PROCEDURE p1(id IN NUMBER, sal IN NUMBER)
AS
BEGIN
INSERT INTO emp VALUES(id, sal);
DBMS_OUTPUT.PUT_LINE('VALUE INSERTED.');
END;
/

Output:
Run SQL Command Line
SQL>set serveroutput on
SQL>start D://pr.sql
Procedure created.

SQL>exec p1(5,4);
VALUE INSERTED.
PL/SQL procudere successfully completed.

SQL>select * from emp;


ID SALARY
----- --------
2 5000

Functions:
A function is a named PL/SQL Block which is similar to a procedure. The major difference between
a procedure and a function is, a function must always return a value, but a procedure may or may
not return a value.
Syntax:
CREATE [OR REPLACE] FUNCTION function_name [parameters]
RETURN return_datatype; {IS, AS}
Declaration_section <variable,constant> ;
BEGIN
Execution_section
Return return_variable;
EXCEPTION
exception section
Return return_variable;
END;
RETURN TYPE: The header section defines the return type of the function.
The return datatype can be any of the oracle datatype like varchar, number etc.
The execution and exception section both should return a value which is of the datatype defined in
the header section.

How to execute a Function?


A function can be executed in the following ways.
• As a part of a SELECT statement : SELECT emp_details_func FROM dual;
• In a PL/SQL Statements like, : dbms_output.put_line(emp_details_func);
This line displays the value returned by the function .

Department of IT Page 15
Example:
create or replace function getsal (no IN number) return number
is
sal number(5);
begin
select salary into sal from emp where id=no;
return sal;
end;
/
Output:
Run SQL Command Line
SQL>select * from emp;
ID SALARY
----- --------
2 5000

SQL>start D://fun.sql
Function created.

SQL>select getsal(2) from dual;


GETSAL(2)
---------
5000
In the example we are retrieving the ‘salary’ of employee with id 2 to variable ‘sal’.
The return type of the function is number.

Calling a Function
While creating a function, you give a definition of what the function has to do. To use a function,
you will have to call that function to perform the defined task. When a program calls a function, the
program control is transferred to the called function.
A called function performs the defined task and when its return statement is executed or when
the last end statement is reached, it returns the program control back to the main program.
Example
The following example demonstrates Declaring, Defining, and Invoking a Simple PL/SQL Function
that computes and returns the maximum of two values.
DECLARE
a number;
b number;
c number;
FUNCTION findMax(x IN number, y IN number)
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
z:= y;
END IF;

Department of IT Page 16
RETURN z;
END;
BEGIN
a:= 23;
b:= 45;
c := findMax(a, b);
dbms_output.put_line(' Maximum of (23,45): ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Maximum of (23,45): 45

PL/SQL procedure successfully completed.

PL/SQL Recursive Functions


We have seen that a program or subprogram may call another subprogram. When a subprogram
calls itself, it is referred to as a recursive call and the process is known as recursion.
To illustrate the concept, let us calculate the factorial of a number. Factorial of a number n is
defined as −
n! = n*(n-1)!
= n*(n-1)*(n-2)!
...
= n*(n-1)*(n-2)*(n-3)... 1
The following program calculates the factorial of a given number by calling itself recursively −
DECLARE
num number;
factorial number;

FUNCTION fact(x number)


RETURN number
IS
f number;
BEGIN
IF x=0 THEN
f := 1;
ELSE
f := x * fact(x-1);
END IF;
RETURN f;
END;

BEGIN
num:= 6;
factorial := fact(num);
dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Factorial 6 is 720

PL/SQL procedure successfully completed.

Department of IT Page 17
Destroying procedure and function:
Syntax:
DROP PROCEDURE/FUNCTION PROCEDURE/FUNCTION_NAME;

Procedures VS Functions:
• A function MUST return a value but a procedure cannot return a value.
• Procedures and functions can both return data in OUT and IN OUT parameters
• The return statement in a function returns control to the calling program and returns the results
of the function but the return statement of a procedure returns control to the calling program
and cannot return a value
• Functions can be called from SQL, procedure cannot
• Functions are considered expressions, procedure are not

TRIGGERS: -
Suppose we are updating the marks in the STUDENT database for some of the students after
re-evaluation. When we are updating the marks, their old values are lost. But in general view it is
better to keep the old marks too – just to know what was the mark before and what is now. But we
do not have any columns to store old marks in the MARKS table. We have to have a separate table to
store the update log for marks updates. But this cannot be done in single MARKS table update. In
this case, we need to update MARKS table as well as we need to insert an entry in the MARKS_LOG
table. Both are different transactions.
What can be done in this case? We can write a procedure to update and insert and call it
every time we have to update marks. But main purpose of the person who is updating the mark is
only to update the marks. But inserting into log table is secondary for him or least important for
him, but at the same it is an important to store that information somewhere. So he will use only
UPDATE statement to correct the marks. In such case triggers are used to insert the record into log
files.
Triggers are blocks of PL/SQL code, which are executed as a result of any insert / update /
delete on the table. There will not be any explicit call for triggers. It is always automatically
executed. It might perform single query or set of queries to meet the goal. But it will be always
written as a PL/SQL block. It is always associated with insert / update / delete of a table. But the set
of transaction inside the trigger can be performed on the same table or one or more other tables.
The general syntax of a trigger is as follows:

Department of IT Page 18
A typical trigger has 3 main components
1. Triggering SQL Statement: - This is the DML statement which causes the triggers to be invoked.
That is it tells when to call the trigger – before or after, on which DML statement of the table –
INSERT/ UPDATE/ DELETE and whether to call trigger when whole table is processed or only
few columns are processed. BEFORE and AFTER is used on tables and INSTEAD OF is used on
views to create triggers. For example, it tells when to call the trigger to insert the logs – whether
to call it on Inserting, deleting or updating MARKS table, before or after updating the MARKS
table, whether to call the trigger on updating all columns of MARKS table or on particular
columns of MARKS table.

2. Trigger Restriction: - This is the part of trigger which tells how many times the trigger needs to
be executed. It informs, if the trigger has to be called for each row insert /update/delete, or only
once for the transaction. In our example, it would be for each row, because, we need to have log
for each row of student marks update. There would be some cases where if we perform some
DML statement on table, say first and last entry of days’ transaction in the supermarket billing to
be logged in some other table. In this case, each INSERT will not call the trigger, instead it will
call only twice in a day to log the entry.

3. Trigger Action: - This part will actually perform set of transaction as result of original DML
statement. For example, inserting the records into log tables. It need not be inserting logs always.
It can be any transaction. For example, when date of birth of a student is inserted, trigger might
calculate his age and insert into the same table.

Types of Triggers: -
There are two types of triggers.
1. Row level trigger: - Row level trigger is executed when each row of the table is inserted/
updated/ deleted. If it is a row level trigger, then we have to explicitly specify while creating the
trigger, as we did in the above example. Also, we have to specify the WHEN (condition) in the
trigger.
2. Statement level trigger: - this trigger will be executed only once for DML statement. This DML
statement may insert / delete/ update one row or multiple rows or whole table. Irrespective of
number of rows, this trigger will be fired for the statement. If we have not specified the type of
trigger while creating, by default it would be a statement level trigger.
In addition to above types of trigger, we can have triggers which are called so because of the time
when they are executed.
• BEFORE trigger: - This trigger is called before the execution of the DML statement. This BEFORE
trigger can be used for some condition check or it can be used to alter the whole DML statement
so that it cannot be executed on the table. For example, if the student age is less than 10, don’t
allow to insert the record into the table.
• After Trigger: - this trigger is called after once DML statement is executed. It can perform any
kind of transaction.
• Combination of triggers: - We can have combination of row, statement, BEFORE and AFTER
triggers.
• BEFORE STATEMENT: - This trigger is executed only once before executing the DML statement.
• BEFORE ROW: - This trigger is executed for each row of the table, but before the DML execution.
• AFTER STATEMENT:- This trigger is executed only once after the DML execution is complete
• AFTER ROW: - This trigger is executed once the DML statement is complete, but for each row of
the table.

Example: -
To start with, we will be using the CUSTOMERS table
Select * from customers;
Department of IT Page 19
+----+----------+-----+-----------+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+-----+-----------+----------+
The following program creates a row-level trigger for the customers table that would fire for
INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This trigger will
display the salary difference between the old values and new values
CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END
/
When the above code is executed at the SQL prompt, it produces the following result −
Trigger created.

The above trigger has been written in such a way that it will fire before any DELETE or INSERT
or UPDATE operation on the table, but you can write your trigger on a single or multiple operations,
for example BEFORE DELETE, which will fire whenever a record will be deleted using the DELETE
operation on the table. If you want to query the table in the same trigger, then you should use the
AFTER keyword, because triggers can query the table or change it again only after the initial
changes are applied and the table is back in a consistent state.

Triggering a Trigger: -
Perform some DML operations on the CUSTOMERS table. Here is one INSERT statement, which will
create a new record in the table
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (7, 'Kriti', 22, 'HP', 7500.00 );
When a record is created in the CUSTOMERS table, the above create
trigger, display_salary_changes will be fired and it will display the following result −
Old salary:
New salary: 7500
Salary difference:
Because this is a new record, old salary is not available and the above result comes as null. Let us
now perform one more DML operation on the CUSTOMERS table. The UPDATE statement will
update an existing record in the table
UPDATE customers
SET salary = salary + 500
Department of IT Page 20
WHERE id = 2;
When a record is updated in the CUSTOMERS table, the above create
trigger, display_salary_changes will be fired and it will display the following result −
Old salary: 1500
New salary: 2000
Salary difference: 500

Need for Triggers


Triggers can be used to implement certain integrity constraints that cannot be specified using the
constraint mechanism of SQL. Triggers are also useful mechanisms for alerting humans or for
starting certain tasks automatically when certain conditions are met. As an illustration, we could
design a trigger that, whenever a tuple is inserted into the takes relation, updates the tuple in the
student relation for the student taking the course by adding the number of credits for the course to
the student’s total credits. As another example, suppose a warehouse wishes to maintain a
minimum inventory of each item; when the inventory level of an item falls below the minimum
level, an order can be placed automatically. On an update of the inventory level of an item, the
trigger compares the current inventory level with the minimum inventory level for the item, and if
the level is at or below the minimum, a new order is created.
Note that trigger systems cannot usually perform updates outside the database, and hence, in the
inventory replenishment example, we cannot use a trigger to place an order in the external world.
Instead, we add an order to a relation holding reorders. We must create a separate permanently
running system process that periodically scans that relation and places orders. Some database
systems provide built-in support for sending email from SQL queries and triggers, using the above
approach.

DATABASE DESIGN AND THE E-R MODEL: -


OVERVIEW OF THE DESIGN PROCESS: -
The task of creating a database application is a complex one, involving design of the
database schema, design of the programs that access and update the data, and design of a security
scheme to control access to data. The needs of the users play a central role in the design process.
The design of a complete database application environment that meets the needs of the
enterprise being modeled requires attention to a broad set of issues. These additional aspects of the
expected use of the database influence a variety of design choices at the physical, logical, and view
levels.

Design Phases: -
For small applications, it may be feasible for a database designer who understands the application
requirements to decide directly on the relations to be created, their attributes, and constraints on
the relations. However, such a direct design process is difficult for real-world applications, since they
are often highly complex. Often no one person understands the complete data needs of an
application. The database designer must interact with users of the application to understand the
needs of the application, represent them in a high-level fashion that can be understood by the users,
and then translate the requirements into lower levels of the design. A high-level data model serves
the database designer by providing a conceptual framework in which to specify, in a systematic
fashion, the data requirements of the database users, and a database structure that fulfills these
requirements.
• The initial phase of database design is to characterize fully the data needs of the prospective
database users. The database designer needs to interact extensively with domain experts and
users to carry out this task. The outcome of this phase is a specification of user requirements.
• Next, the designer chooses a data model and, by applying the concepts of the chosen data model,

Department of IT Page 21
translates these requirements into a conceptual schema of the database. The schema developed
at this conceptual-design phase provides a detailed overview of the enterprise. The entity-
relationship model, is typically used to represent the conceptual design. Stated in terms of the
entity-relationship model, the conceptual schema specifies the entities that are represented in the
database, the attributes of the entities, the relationships among the entities, and constraints on the
entities and relationships. Typically, the conceptual-design phase results in the creation of an
entity-relationship diagram that provides a graphic representation of the schema.
The designer reviews the schema to confirm that all data requirements are indeed satisfied
and are not in conflict with one another. She can also examine the design to remove any redundant
features. Her focus at this point is on describing the data and their relationships, rather than on
specifying physical storage details.
• A fully developed conceptual schema also indicates the functional requirements of the
enterprise. In a specification of functional requirements, users describe the kinds of
operations (or transactions) that will be performed on the data. Example operations include
modifying or updating data, searching for and retrieving specific data, and deleting data. At this
stage of conceptual design, the designer can review the schema to ensure it meets functional
requirements.
• The process of moving from an abstract data model to the implementation of the database
proceeds in two final design phases.
1. In the logical-design phase, the designer maps the high-level conceptual schema onto the
implementation data model of the database system that will be used. The implementation
data model is typically the relational data model, and this step typically consists of mapping
the conceptual schema defined using the entity-relationship model into a relation schema.
2. Finally, the designer uses the resulting system-specific database schema in the subsequent
physical-design phase, in which the physical features of the database are specified. These
features include the form of file organization and choice of index structures.
The physical schema of a database can be changed relatively easily after an application has been
built. However, changes to the logical schema are usually harder to carry out, since they may affect
a number of queries and updates scattered across application code. It is therefore important to
carry out the database design phase with care, before building the rest of the database application.

Design Alternatives: -
A major part of the database design process is deciding how to represent in the design the various
types of “things” such as people, places, products, and the like. We use the term entity to refer to
any such distinctly identifiable item. In a university database, examples of entities would include
instructors, students, departments, courses, and course offerings. The various entities are related to
each other in a variety of ways, all of which need to be captured in the database design. For
example, a student takes a course offering, while an instructor teaches a course offering; teaches
and takes are examples of relationships between entities. In designing a database schema, we must
ensure that we avoid two major pitfalls:
1. Redundancy: - A bad design may repeat information. For example, if we store the course
identifier and title of a course with each course offering, the title would be stored redundantly
(that is, multiple times, unnecessarily) with each course offering. It would suffice to store only
the course identifier with each course offering, and to associate the title with the course
identifier only once, in a course entity. Redundancy can also occur in a relational schema.
The biggest problem with such redundant representation of information is that the copies of
a piece of information can become inconsistent if the information is updated without taking
precautions to update all copies of the information. Ideally, information should appear in exactly
one place.
2. Incompleteness: - A bad design may make certain aspects of the enterprise difficult or
impossible to model. In terms of relations, suppose we have a single relation where we repeat all

Department of IT Page 22
of the course information once for each section that the course is offered. It would then be
impossible to represent information about a new course, unless that course is offered. We might
try to make do with the problematic design by storing null values for the section information.
Such a work-around is not only unattractive, but may be prevented by primary-key constraints.
Avoiding bad designs is not enough. There may be a large number of good designs from which we
must choose.

THE E-R MODEL: -


The entity-relationship (E-R) data model was developed to facilitate database design by
allowing specification of an enterprise schema that represents the overall logical structure of a
database. The ER or (Entity Relational Model) is a high-level conceptual data model diagram.
Entity-Relation model is based on the notion of real-world entities and the relationship between
them.
ER modeling helps you to analyze data requirements systematically to produce a well-
designed database. So, it is considered a best practice to complete ER modeling before
implementing your database. The E-R data model employs three basic concepts: entity sets,
relationship sets, and attributes. The E-R model also has an associated diagrammatic
representation, the E-R diagram.

Components of the ER Diagram: -


This model is based on three basic concepts:
• Entities
• Attributes
• Relationships
Example: -
Consider in a University database, we might have entities for Students, Courses, and Lecturers.
Students entity can have attributes like Rollno, Name, and DeptID. They might have relationships
with Courses and Lecturers.

Entity: -
A real-world thing either living or non-living that is easily recognizable and nonrecognizable.
It is anything in the enterprise that is to be represented in our database. It may be a physical thing
or simply a fact about the enterprise or an event that happens in the real world.

Department of IT Page 23
An entity can be place, person, object, event or a concept, which stores data in the database.
The characteristics of entities are must have an attribute, and a unique key. Every entity is made up
of some 'attributes' which represent that entity.
Examples of entities:
• Person: Employee, Student, Patient
• Place: Store, Building
• Object: Machine, product, and Car
• Event: Sale, Registration, Renewal
• Concept: Account, Course

Entity set: -
An entity set is a group of similar kind of entities. It may contain entities with attribute sharing
similar values. Entities are represented by their properties, which also called attributes. All
attributes have their separate values. For example, a student entity may have a name, age, class, as
attributes. An Entity is an object of Entity Type and set of all entities is called as entity set. e.g.; E1 is
an entity having Entity Type Student and set of all students is called Entity Set. In ER diagram,
Entity Type is represented as:

Example of Entities:
A university may have some departments. All these departments employ various lecturers and offer
several programs. Some courses make up each program. Students register in a particular program
and enroll in various courses. A lecturer from the specific department takes each course, and each
lecturer teaches a various group of students.

Relationship
Relationship is nothing but an association among two or more entities. E.g., Tom works in the
Chemistry department. Entities take part in relationships. We can often identify relationships with
verbs or verb phrases.
For example:
• You are attending this lecture
• I am giving the lecture
• A student attends a lecture
• A lecturer is giving a lecture.

Relationship Type and Relationship Set: -


A relationship type represents the association between entity types. For example,‘Enrolled in’ is a
relationship type that exists between entity type Student and Course. In ER diagram, relationship
type is represented by a diamond and connecting the entities with lines.

Department of IT Page 24
A set of relationships of same type is known as relationship set. The following relationship set
depicts S1 is enrolled in C2, S2 is enrolled in C1 and S3 is enrolled in C3.

Degree of a relationship set:


The number of different entity sets participating in a relationship set is called as degree of a
relationship set.
1. Unary Relationship: -
When there is only ONE entity set participating in a relation, the relationship is called as
unary relationship. For example, one person is married to only one person.

2. Binary Relationship: -
When there are TWO entities set participating in a relation, the relationship is called as
binary relationship. For example, Student is enrolled in Course.

3. n-ary Relationship: -
When there are n entities set participating in a relation, the relationship is called as n-ary
relationship.

Attribute(s):
Attributes are the properties which define the entity type. For example, Roll_No, Name, DOB,
Age, Address, Mobile_No are the attributes which defines entity type Student. In ER diagram,
attribute is represented by an oval.

1. Key Attribute: - The attribute which uniquely identifies each entity in the entity set is called
key attribute. For example, Roll_No will be unique for each student. In ER diagram, key attribute
is represented by an oval with underlying lines.

Department of IT Page 25
2. Composite Attribute: - An attribute composed of many other attribute is called as composite
attribute. For example, Address attribute of student Entity type consists of Street, City, State, and
Country. In ER diagram, composite attribute is represented by an oval comprising of ovals.

3. Multi valued Attribute: - An attribute consisting more than one value for a given entity. For
example, Phone_No (can be more than one for a given student). In ER diagram, multivalued
attribute is represented by double oval.

4. Derived Attribute: - An attribute which can be derived from other attributes of the entity
type is known as derived attribute. e.g.; Age (can be derived from DOB). In ER diagram, derived
attribute is represented by dashed oval.

The complete entity type Student with its attributes can be represented as:

CONSTRAINTS: -
Cardinality
The number of times an entity of an entity set participates in a relationship set is known as
cardinality. Cardinality can be of different types:
1. One-to-One Relationships
2. One-to-Many Relationships
3. Many to One Relationships
4. Many-to-Many Relationships
1. One to one: -When each entity in each entity set can take part only once in the relationship,
the cardinality is one to one. Let us assume that a male can marry to one female and a female can
marry to one male. So the relationship will be one to one.

Department of IT Page 26
Using Sets, it can be represented as:

2. One-to-many: - One entity from entity set X can be associated with multiple entities of entity set
Y, but an entity from entity set Y can be associated with at least one entity. For example, one
class is consisting of multiple students.

3. Many to one – When entities in one entity set can take part only once in the relationship set
and entities in other entity set can take part more than once in the relationship
set, cardinality is many to one. Let us assume that a student can take only one course but one
course can be taken by many students. So the cardinality will be n to 1. It means that for one
course there can be n students but for one student, there will be only one course.

Using Sets, it can be represented as:

In this case, each student is taking only 1 course but 1 course has been taken by many students.
4. Many to many – When entities in all entity sets can take part more than once in the
relationship cardinality is many to many. Let us assume that a student can take more than one
course and one course can be taken by many students. So the relationship will be many to many.

Using sets, it can be represented as:

In this example, student S1 is enrolled in C1 and C3 and Course C3 is enrolled by S1, S3 and S4.
So it is many to many relationships.
Participation Constraint :
Participation Constraint is applied on the entity participating in the relationship set.
Department of IT Page 27
1. Total Participation – Each entity in the entity set must participate in the relationship. If each
student must enroll in a course, the participation of student will be total. Total participation is
shown by double line in ER diagram.
2. Partial Participation – The entity in the entity set may or may NOT participate in the
relationship. If some courses are not enrolled by any of the student, the participation of course
will be partial.

The diagram depicts the ‘Enrolled in’ relationship set with Student Entity set having total
participation and Course Entity set having partial participation.

Using set, it can be represented as,

Every student in Student Entity set is participating in relationship but there exists a course C4
which is not taking part in the relationship.

Keys: -
• The key is defined as the column or attribute of the database table.
• They are used to establish and identify relation between tables.
• They also ensure that each record within a table can be uniquely identified by combination of
one or more fields within a table.
Types of Keys
1. Super key: An attribute (or combination of attributes) that uniquely identifies each row in a
table. It is a super set of candidate key.
2. Candidate key: An attribute (or set of attributes) that uniquely identifies a row. Let K be a set of
attributes of relation R. Then K is a candidate key for R if it possess the following properties:
a. Uniqueness: -No legal value of R ever contains two distinct tuples with the same value of K
b. Irreducibility: - No proper subset of K has the uniqueness property
3. Primary key: - Primary key is the candidate key which is selected as the principal unique
identifier. It is a key that uniquely identify each record in the table. Cannot contain null entries.

Department of IT Page 28
4. Composite Key: - Key that consists of two or more attributes that uniquely identifies an entity
occurrence is called composite key.

5. Foreign Key: - A foreign key is generally a primary key from one table that appears as a field in
another where the first table has a relationship to the second.
In other words, if we had a table A with a primary key X that linked to a table B where X was a
field in B, then X would be a foreign key in B.

ENTITY-RELATIONSHIP DIAGRAMS: -
What is ER Diagrams?
Entity relationship diagram displays the relationships of entity set stored in a database. In other
words, we can say that ER diagrams help you to explain the logical structure of databases. At first
look, an ER diagram looks very similar to the flowchart. However, ER Diagram includes many
specialized symbols, and its meanings make this model unique.
Facts about ER Diagram Model:
• ER model allows you to draw Database Design
• It is an easy to use graphical tool for modeling data
• Widely used in Database Design
• It is a GUI representation of the logical structure of a Database
• It helps you to identifies the entities which exist in a system and the relationships between those
entities
Why use ER Diagrams?
Here, are prime reasons for using the ER Diagram

Department of IT Page 29
• Helps you to define terms related to entity relationship modeling
• Provide a preview of how all your tables should connect, what fields are going to be on each
table
• Helps to describe entities, attributes, relationships
• ER diagrams are translatable into relational tables which allows you to build databases quickly
• ER diagrams can be used by database designers as a blueprint for implementing data in specific
software applications
• The database designer gains a better understanding of the information to be contained in the
database with the help of ERP diagram
• ERD is allowed you to communicate with the logical structure of the database to users

ER- Diagram Notations


ER- Diagram is a visual representation of data that describe how data is related to each other.
• Rectangles: This symbol represent entity types
• Ellipses : Symbol represent attributes
• Diamonds: This symbol represents relationship types
• Lines: It links attributes to entity types and entity types with other relationship types
• Primary key: attributes are underlined
• Double Ellipses: Represent multi-valued attributes

Roles in E-R Diagrams


The function that an entity plays in a relationship is called its role. Roles are normally
explicit and not specified. They are useful when the meaning of a relationship set needs
clarification.
For example, the entity sets of a relationship may not be distinct. The relationship works-
for might be ordered pairs of employees (first is manager, second is worker).
In the E-R diagram, this can be shown by labelling the lines connecting entities (rectangles) to
relationships (diamonds).

E-R diagram with role indicators


Weak Entities: -
A weak entity is a type of entity which doesn't have its key attribute. It can be identified
uniquely by considering the primary key of another entity. For that, weak entity sets need to have
participation.
The entity set which does not have sufficient attributes to form a primary key is called as
Weak entity set. An entity set that has a primary key is called as Strong entity set. Consider an entity
Department of IT Page 30
set Payment which has three attributes: payment_number, payment_date and payment_amount.
Although each payment entity is distinct but payment for different loans may share the same
payment number. Thus, this entity set does not have a primary key and it is an entity set. Each weak
set must be a part of one-to-many relationship set.
A member of a strong entity set is called dominant entity and member of weak entity set is
called as subordinate entity. A weak entity set does not have a primary key but we need a means of
distinguishing among all those entries in the entity set that depend on one particular strong entity
set. The discriminator of a weak entity set is a set of attributes that allows this distinction be made.
For example, payment_number acts as discriminator for payment entity set. It is also called as the
Partial key of the entity set.
The primary key of a weak entity set is formed by the primary key of the strong entity set on
which the weak entity set is existence dependent plus the weak entity sets discriminator. In the
above example {loan_number, payment_number} acts as primary key for payment entity set.
The relationship between weak entity and strong entity set is called as Identifying
Relationship. In example, loan-payment is the identifying relationship for payment entity. A weak
entity set is represented by doubly outlined box

Let's learn more about a weak entity by comparing it with a Strong Entity
Strong Entity Set Weak Entity Set

Strong entity set always has a primary key. It does not have enough attributes to build
a primary key.

It is represented by a rectangle symbol. It is represented by a double rectangle


symbol.

It contains a Primary key represented by It contains a Partial Key which is


the underline symbol. represented by a dashed underline symbol.

The member of a strong entity set is called The member of a weak entity set called as a
as dominant entity set. subordinate entity set.

Primary Key is one of its attributes which In a weak entity set, it is a combination of
helps to identify its member. primary key and partial key of the strong
entity set.

In the ER diagram the relationship The relationship between one strong and a
between two strong entity set shown by weak entity set shown by using the double
using a diamond symbol. diamond symbol.

Department of IT Page 31
The connecting line of the strong entity set The line connecting the weak entity set for
with the relationship is single. identifying relationship is double.

E-R diagram for the University Enterprise: - we show an E-R diagram that corresponds to the
university enterprise that we have been using thus far in the text. This E-R diagram is equivalent to
the textual description of the university E-R model that we saw in Section 7.4, but with several
additional constraints, and section now being a weak entity. In our university database, we have a
constraint that each instructor must have exactly one associated department. As a result, there is a
double line in Figure7.15 between instructor and inst dept, indicating total participation of
instructor in inst dept; that is, each instructor must be associated with a department. Further, there
is an arrow from inst dept to department, indicating that each instructor can have at most one
associated department.

Department of IT Page 32
Similarly, entity sets course and student have double lines to relationship sets course dept and stud
dept respectively, as also entity set section to relationship set sec time slot. The first two
relationships, in turn, have an arrow pointing to the other relationship, department, while the third
relationship has an arrow pointing to time slot. Further, Figure 7.15 shows that the relationship set
takes has a descriptive attribute grade, and that each student has at most one advisor. The figure
also shows that section is now a weak entity set, with attributes sec id, semester, and year forming
the discriminator; sec course is the identifying relationship set relating weak entity set section to
the strong entity set course. In Section 7.6, we shall show how this E-R diagram can be used to
derive the various relation schemas we use.

Steps to Create an ERD


Following are the steps to create an ERD.

Let's study them with an example:


In a university, a Student enrolls in Courses. A student must be assigned to at least one or more
Courses. Each course is taught by a single Professor. To maintain instruction quality, a Professor
can deliver only one course
Step 1) Entity Identification
We have three entities
• Student
• Course
• Professor

Step 2) Relationship Identification


We have the following two relationships
• The student is assigned a course
• Professor delivers a course

Step 3) Cardinality Identification


For them problem statement we know that,
• A student can be assigned multiple courses
• A Professor can deliver only one course

Department of IT Page 33
Step 4) Identify Attributes
You need to study the files, forms, reports, data currently maintained by the organization to identify
attributes. You can also conduct interviews with various stakeholders to identify entities. Initially,
it's important to identify the attributes without mapping them to a particular entity.
Once, you have a list of Attributes, you need to map them to the identified entities. Ensure an
attribute is to be paired with exactly one entity. If you think an attribute should belong to more than
one entity, use a modifier to make it unique.
Once the mapping is done, identify the primary Keys. If a unique key is not readily available, create
one.
Entity Primary Key Attribute

Student Student_ID StudentName

Professor Employee_ID ProfessorName

Course Course_ID CourseName

For Course Entity, attributes could be Duration, Credits, Assignments, etc. For the sake of ease we
have considered just one attribute.
Step 5) Create the ERD
A more modern representation of ERD Diagram

Best Practices for Developing Effective ER Diagrams


• Eliminate any redundant entities or relationships
• You need to make sure that all your entities and relationships are properly labeled
• There may be various valid approaches to an ER diagram. You need to make sure that the ER
diagram supports all the data you need to store
• You should assure that each entity only appears a single time in the ER diagram

Department of IT Page 34
• Name every relationship, entity, and attribute are represented on your diagram
• Never connect relationships to each other
• You should use colors to highlight important portions of the ER diagram

ENTITY-RELATIONSHIP DESIGN ISSUE: -


There are number of different ways to define set of entities and relationship among them. We
examine basic issues in the design of an E-R model. These are:
• Use of entity sets vs. attributes.
• Use of entity sets vs. relationship sets
• Binary versus n-ary relationship sets
• Placement of relationship attributes

Use of entity sets vs. attributes


• Treating telephone as an attribute telephone-number implies that employees have exactly one
telephone number each
• Treating telephone as an entity permits employees to have several telephone numbers
associated with them.
• The distinctions to consider an object as attribute or entity depends on the structure of real-
world enterprise being modeled.

Use of entity sets vs. relationship sets


• Each loan is represented by a relationship between a customer and a branch, if every loan is
associated with exactly one customer and is associated with exactly one branch
• If several customers hold a joint loan then, loan should be considered as an entity

Department of IT Page 35
The guideline in determining whether to use an entity set or a relationship set is to designate a
relationship set to describe an action that occurs between entities

Binary versus n-ary relationship sets


Although it is possible to replace any nonbinary (n-ary, for n > 2) relationship set by a number of
distinct binary relationship sets, a n-ary relationship set shows more clearly that several entities
participate in a single relationship.
• There is one advantage of using binary relationship, with this it is possible to store partial
information but in ternary relationship it is not possible to represent it.
• But there are some relationships that are naturally non-binary.

Placement of relationship attributes


• The cardinality ratio of a relationship can affect the placement of relationship attributes
• Example: Let us take two entities instructor and student with relationship advisor, if we want to
add attribute date ( which specifies when the instructor became advisor)
• If relationship is one to many then the date must be placed to the entity set on the “many” side of
relationship
• For one to one relationship, it could be placed on either side
• For many to many relationship, the date must be placed as the relationship attribute

EXTENDED E-R FEATURES: -


Although the basic E-R concepts can model most database features, some aspects of a database may
be more aptly expressed by certain extensions to the basic E-R model. In this section, we discuss the
extended E-R features of specialization, generalization, higher-and lower-level entity sets, attribute
inheritance, and aggregation.
1. Specialization: -
In specialization, an entity is divided into sub-entities based on their characteristics. It is a
top-down approach where higher level entity is specialized into two or more lower level entities.

Department of IT Page 36
We can see that we have a higher level entity “Employee” which we have divided in sub
entities “Technician”, “Engineer” & “Accountant”. All of these are just an employee of a company,
however their role is completely different and they have few different attributes. Just for the
example, I have shown that Technician handles service requests, Engineer works on a project
and Accountant handles the credit & debit details. All of these three employee types have few
attributes common such as name & salary which we had left associated with the parent entity
“Employee” as shown in the above diagram.

Types of Specialization: -

a. Overlapping specialization: - An entity may belong to multiple specialized entity sets. In


an overlapping specialization, an individual of of the parent class may be a member of more than
one of the specialized subclasses.
Example: - Instance of Super-type Person can be member of multiple Sub-
types being Woman, Driver and Engineer. (A person can be a Woman and that same Woman
can be Driver and that same Woman can be Engineer at the same time).

b. disjoint specialization: - An entity may belong to at most one specialized entity sets. In
a disjoint specialization, also called an exclusive specialization, an individual of the parent
class may be a member of only one specialized subclass.
Example: - Instance of Super-type Animal can only be member of exactly one of these Sub-
types being Panda, Cheetah and Dog (An animal can either be Panda or be Dog or be Cheetah
but can't be any two or more at the same time)

2. Generalization: - Generalization is a process in which the common attributes of more than one
entities form a new entity. This newly formed entity is called generalized entity. It is a bottom-up
approach in which two or more entities can be generalized to a higher level entity if they have
some attributes in common.
Generalization Example: -
Let’s say we have two entities Student and Teacher.
• Attributes of Entity Student are: Name, Address & Grade
• Attributes of Entity Teacher are: Name, Address & Salary
The ER diagram before generalization looks like this:

Department of IT Page 37
These two entities have two common attributes: Name and Address, we can make a generalized
entity with these common attributes. Let’s have a look at the ER model after generalization.
The ER diagram after generalization: -
We have created a new generalized entity Person and this entity has the common attributes of
both the entities. As you can see in the following ER diagram that after the generalization process
the entities Student and Teacher only has the specialized attributes Grade and Salary
respectively and their common attributes (Name & Address) are now associated with a new
entity Person which is in the relationship with both the entities (Student & Teacher).

3. Attribute Inheritance: -
A crucial property of the higher- and lower –level entities created by specialization and
generalization is attribute inheritance. The attributes of the higher-level entity sets are said to be
inherited by the lower-level entity sets. For example, student and employee inherit the attributes
of person. Thus, student is described by its ID, name, and address attributes, and additionally a
tot_cred attribute; employee is described by its ID, name, and address attributes, and
additionally a salary attribute. Attribute inheritance applies through all tiers of lower-level entity
sets; thus, instructor and secretary, which are sub classes of employee, inherit the attributes ID,
name, and address from person, in addition to inheriting salary from employee. A lower-level
entity set (or sub class) also inherits participation in the relationship sets in which its higher-
level entity (or super class) participates. Like attribute inheritance, participation inheritance
applies through all tiers of lower-level entity sets. For example, suppose the person entity set
participates in a relationship person dept with department. Then, the student, employee,
instructor and secretary entity sets, which are sub classes of the person entity set, also implicitly
participate in the person dept relationship with department. The above entity sets can
participate in any relationships in which the person entity set participates.
Whether a given portion of an E-R model was arrived at by specialization or generalization,
the outcome is basically the same:
• A higher-level entity set with attributes and relationships that apply to all of its lower-level
entity sets.
• Lower-level entity sets with distinctive features that apply only within a particular lower-level
entity set.
In what follows, although we often refer to only generalization, the properties that we discuss
belong fully to both processes. Figure 7.21 depicts a hierarchy of entity sets. In the figure,
employee is a lower-level entity set of person and a higher-level entity set of the instructor and

Department of IT Page 38
secretary entity sets. In a hierarchy, a given entity set may be involved as a lower level entity set
in only one ISA relationship; that is, entity sets in this diagram have only single inheritance. If an
entity set is a lower-level entity set in more than one ISA relationship, then the entity set has
multiple inheritance, and the resulting structure is said to be a lattice.

4. Constraints on Generalizations: -
To model an enterprise more accurately, the database designer may choose to place certain
constraints on a particular generalization. One type of constraint involves determining which
entities can be members of a given lower-level entity set. Such membership may be one of the
following:
• Condition-defined: - In condition-defined lower-level entity sets, membership is evaluated on
the basis of whether or not an entity satisfies an explicit condition or predicate. For example,
assume that the higher-level entity set student has the attribute student_type. All student
entities are evaluated on the defining student_type attribute. Only those entities that satisfy
the condition student_type = “graduate” are allowed to belong to the lower-level entity set
graduate_student. All entities that satisfy the condition student_type = “undergraduate” are
included in undergraduate_student. Since all the lower-level entities are evaluated on the
basis of the same attribute (in this case, on student_type), this type of generalization is said to
be attribute-defined.
• User-defined. User-defined lower-level entity sets are not constrained by a membership
condition; rather, the database user assigns entities to a given entity set.

The lower- level entity sets may be one of the following:


• 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.

A 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.

Partial generalization is the default. We can specify total generalization in an E-R diagram by

Department of IT Page 39
adding the keyword “total” in the diagram and drawing a dashed line from the keyword to the
corresponding hollow arrow-head to which it applies (for a total generalization), or to the set
of hollow arrow-heads to which it applies (for an overlapping generalization).
The student generalization is total: All student entities must be either graduate or
undergraduate.

5. Aggregation: -
In aggregation, the relation between two entities is treated as a single entity. In aggregation,
relationship with its corresponding entities is aggregated into a higher level entity.
For Example, Employee working for a project may require some machinery. So, REQUIRE
relationship is needed between relationship WORKS_FOR and entity MACHINERY. Using
aggregation, WORKS_FOR relationship with its entities EMPLOYEE and PROJECT is aggregated
into single entity and relationship REQUIRE is created between aggregated entity and
MACHINERY.

ALTERNATIVE NOTATIONS FOR MODELING DATA


A diagrammatic representation of the data model of an application is a very important part
of designing a database schema. Creation of a database schema requires not only data modeling
experts, but also domain experts who know the requirements of the application but may not be
familiar with data modeling.
A number of alternative notations for modeling data have been proposed, of which E-R
diagrams and UML class diagrams the most are widely used. There is no universal standard for E-R
diagram notation. The set of symbols we have used in our E-R diagram notation are shown in the
below figure.

Department of IT Page 40
Alternative E-R Notations: -
The below Figure indicates some of the alternative E-R notations that are widely used. One
alternative representation of attributes of entities is to show them in ovals connected to the box
representing the entity; primary key attributes are indicated by underlining them. The above
notation is shown at the top of the figure. Relationship attributes can be similarly represented, by
connecting the ovals to the diamond representing the relationship.

Department of IT Page 41
In one alternative, shown on the left side of the figure, labels ∗ and 1 on the edges out of the
relationship are used for depicting many-to-many, one-to-one, and many-to-one relationships. The
case of one-to many is symmetric to many-to-one, and is not shown.
In another alternative notation shown on the right side of the figure, relationship sets are
represented by lines between entity sets, without diamonds; only binary relationships can be
modeled thus. Cardinality constraints in such a notation are shown by “crow’s-foot” notation, as in
the figure. In a relationship R between E1 and E2, crow’s feet on both sides indicate a many-to-
many relationship, while crow’s feet on just the E1 side indicate a many-to-one relationship from
E1 toE2.
Total participation is specified in this notation by a vertical bar. Note however, that in a
relationship R between entities E1 and E2, if the participation of E1 in R is total, the vertical bar is
placed on the opposite side, adjacent to entity E2. Similarly, partial participation is indicated by
using a circle, again on the opposite side.

The Unified Modeling Language UML: -


Entity-relationship diagrams help model the data representation component of a software system.
Data representation, however, forms only one part of an overall system design. Other components
include models of user interactions with the system, specification of functional modules of the
system and their interaction, etc. The Unified Modeling Language (UML) is a standard developed

Department of IT Page 42
under the auspices of the Object Management Group (OMG) for creating specifications of various
components of a software system. Some of the parts of UML are:
• Class diagram: - A class diagram is similar to an E-R diagram.
• Use case diagram: - Use case diagrams show the interaction between users and the system, in
particular the steps of tasks that users perform (such as withdrawing money or registering for a
course).
• Activity diagram: -Activity diagrams depict the flow of tasks between various components of a
system.
• Implementation diagram: - Implementation diagrams show the system components and their
inter connections, both at the software component level and the hardware component level.

UNIT WISE IMPORTANT QUESTIONS: -


TWO MARK QUESTIONS: -
1. What is the purpose of trigger in SQL? [APRIL 2019]
2. Define Weak entity set in ER Model. [APRIL 2019]
3. Define Candidate key and super key. [APRIL 2019]
4. What is weak entity? Draw the diagrammatic representation. [APRIL 2018]
5. What are ‘Where’ clause predicates? (UNIT 2) [APRIL 2018]
6. Define Entity and Attribute. Give an example. [APRIL 2017]
7. Define Assertions. [APRIL 2017]

Department of IT Page 43
8. What is meant by correlated queries? [MAY 2016]
9. List the requirements needed to design a trigger. [MAY 2016]
10. What is the use of rename operator? (UNIT 2) [MAY 2016]
11. What is entity set? [MAY 2016]
12. Define super key. [MAY 2016]
13. What is an attribute and diagrammatic representation of derived attribute? [OCTOBER 2018]
14. What do you known about Integrity Constraints? [OCTOBER 2018]
15. What is the purpose of triggers in SQL? [OCTOBER 2017]
16. In ER Diagrams, give an example of aggregation. [OCTOBER 2017]
17. What is the difference between weak entity and string entity sets? [DECEMBER 2016]

ESSAY QUESTIONS: -
1. Explain various types of joins in SQL with examples. [APRIL 2019]
2. Discuss following E-R features with neat diagrams. [APRIL 2019]
i) Generalization
ii) Specialization.
iii) Aggregation.
iv) Binary relationship sets.
3. Explain about Integrity Constraints and Enforcing Integrity Constraint. [APRIL 2018]
4. Explain the features of E-R Diagram with suitable examples. [APRIL 2018]
5. We can convert any weak entity set to strong entity set by simply adding appropriate attributes. Analyze
why, then, do we have weak entity sets? [APRIL 2017]
6. What is a view? How we use views in SQL queries? [APRIL 2017]
7. What is a view? How do views support logical data independence? [MAY 2016]
8. Explain the purpose of the ER Diagrams and describe how the Entities, Attributes and relations are
represented with an example. [MAY 2016]
9. What is trigger in SQL explain different types of triggers with examples. [OCTOBER 2018]
10. Discuss about ER-Diagrams with an Example. [OCTOBER 2018]
11. Write about different Integrity constraints on a single relation. [OCTOBER 2017]
12. Construct an E-R diagram for a car insurance company whose customer own one or more cars each.
Each car has associated with it zero to any number of recorded accidents. [OCTOBER 2017]
13. Explain the purpose of the ER Diagrams and draw the ER diagram for library management system.
[DECEMBER 2016]
14. What is trigger and explain in brief about different types of Triggers? [DECEMBER 2016]

Department of IT Page 44

You might also like