Block-1 Unit-1 Relational Database Design: T (Enrolment Number) Is 00, Then T (Marks) Are Valid."
Block-1 Unit-1 Relational Database Design: T (Enrolment Number) Is 00, Then T (Marks) Are Valid."
Block-1 Unit-1 Relational Database Design: T (Enrolment Number) Is 00, Then T (Marks) Are Valid."
BLOCK-1 UNIT-3
ADVANCED SQL
Q1 What are assertions? What is the syntax for declaration of an assertion? Also give
an example of assertion.
Ans Assertions are constraints that are normally of general nature. For example, the
age of the student in a hypothetical University should not be more than 25 years or the
minimum age of the teacher of that University should be 30 years. Such general
constraints can be implemented with the help of an assertion statement.
The syntax for creating assertion is:
Syntax:
CREATE ASSERTION <Name>
CHECK (<Condition>);
Thus, the assertion on age for the University as above can be implemented as:
CREATE ASSERTION age-constraint
CHECK (NOT EXISTS (
SELECT *
FROM STUDENT s
WHERE s.age > 25
OR s.age > (
SELECT MIN (f.age)
FROM FACULTY f
));
The assertion name helps in identifying the constraints specified by the assertion. These
names can be used to modify or delete an assertion later. But how are these assertions
enforced? The database management system is responsible for enforcing the assertion on
to the database such that the constraints stated in the assertion are not violated. Assertions
are checked whenever a related relation changes.
Now try writing an assertion for a university system that stores a database of faculty as:
FACULTY (code, name, age, basic salary, medical-allow, other benefits)
MEDICAL-CLAIM (code, date, amount, comment)
Assertion: The total medical claims made by a faculty member in the current financial
year should not exceed his/her medial allowance.
CREATE ASSERTION med-claim
CHECK (NOT EXISTS (
SELECT code, SUM (amount), MIN(medical-allow)
FROM (FACULTY NATRUAL JOIN MEDICAL-CLAIM)
WHERE date>”31-03-2006”
GROUP BY code
HAVING MIN(medical-allow) < SUM(amount)
));
OR
CREATE ASSERTION med-claim
CHECK (NOT EXISTS (
SELECT *
FROM FACULT f
WHERE (f.code IN
(SELECT code, SUM(amount)
FROM MEDICAL-CLAIM m
WHERE date>”31-03-2006” AND f.code=m.code AND
f.medical-allow<SUM(amount)
Dynamic SQL
Dynamic SQL, unlike embedded SQL statements, are built at the run time and placed in a
string in a host variable. The created SQL statements are then sent to the DBMS for
processing. Dynamic SQL is generally slower than statically embedded SQL as they
require complete processing including access plan generation during the run time.
However, they are more powerful than embedded SQL as they allow run time application
logic. The basic advantage of using dynamic embedded SQL is that we need not compile
and test a new program for a new query. Let us explain the use of dynamic SQL with the
help of an example:
Example: Write a dynamic SQL interface that allows a student to get and modify
permissible details about him/her. The student may ask for subset of information also.
Assume that the student database has the following relations.
STUDENT (enrolno, name, dob)
RESULT (enrolno, coursecode, marks)
In the table above, a student has access rights for accessing information on his/her
enrolment number, but s/he cannot update the data. Assume that user names are
enrolment number.
Solution: A sample program segment may be (please note that the syntax may change
for different commercial DBMS).
/* declarations in SQL */
EXEC SQL BEGIN DECLARE SECTION;
char inputfields (50);
char tablename(10)
char sqlquery ystring(200)
EXEC SQL END DECLARE SECTION;
printf (“Enter the fields you want to see \n”);
scanf (“SELECT%s”, inputfields);
printf (“Enter the name of table STUDENT or RESULT”);
scanf (“FROM%s”, tablename);
sqlqueryystring = “SELECT” +inputfields +“ ”+
“FROM” + tablename
+ “WHERE enrolno + :USER”
/*Plus is used as a symbol for concatenation operator; in some DBMS it may be ||*/
/* Assumption: the user name is available in the host language variable USER*/
EXEC SQL PREPARE sqlcommand FROM :sqlqueryystring;
EXEC SQL EXECUTE sqlcommand;
Please note the following points in the example above.
• The query can be entered completely as a string by the user or s/he can be suitably
prompted.
• The query can be fabricated using a concatenation of strings. This is language
dependent in the example and is not a portable feature in the present query.
• The query modification of the query is being done keeping security in mind.
• The query is prepared and executed using a suitable SQL EXEC commands.
Q4. What is SQLJ? Explain the syntax of Declarations and Executable Statements.
Also show that SQLJ uses Embedded SQL.
Ans. Till now we have talked about embedding SQL in C, but how can we embed SQL
statements into JAVA Program? For this purpose we use SQLJ. In SQLJ, a preprocessor
called SQLJ translator translates SQLJ source file to JAVA source file. The JAVA file
compiled and run on the database. Use of SQLJ improves the productivity and
manageability of JAVA Code as:
• The code becomes somewhat compact.
• No run-time SQL syntax errors as SQL statements are checked at compile time.
• It allows sharing of JAVA variables with SQL statements. Such sharing is not possible
otherwise.
Please note that SQLJ cannot use dynamic SQL. It can only use simple embedded SQL.
SQLJ provides a standard form in which SQL statements can be embedded in JAVA
program. SQLJ statements always begin with a #sql keyword. These embedded SQL
statements are of two categories – Declarations and Executable Statements.
Declarations have the following syntax:
#sql <modifier> context context_classname;
The executable statements have the following syntax:
#sql {SQL operation returning no output};
OR
#sql result = {SQL operation returning output};
Example:
Let us write a JAVA function to print the student details of student table, for the student
who have taken admission in 2005 and name are like ‘Shyam’. Assuming that the first
two digits of the 9-digit enrolment number represents a year, the required input
conditions may be:
• The enrolno should be more than “05000000” and
• The name contains the sub string “Shyam”.
Please note that these input conditions will not be part of the Student Display function,
rather will be used in the main ( ) function that may be created separately by you. The
following display function will accept the values as the parameters supplied by the main (
).
Public void DISPSTUDENT (String enrolno, String name, int phone)
{
try {
if ( name equals ( “ ” ) )
name = “%”;
if (enrolno equals (“ ”) )
enrolno = “%”;
SelRowIter srows = null;
# sql srows = { SELECT Enrolno, name, phone
FROM STUDENT
WHERE enrolno > :enrolno AND name like :name
};
while ( srows.next ( ) ) {
int enrolno = srows. enrolno ( );
String name = srows.name ( );
System.out.println ( “Enrollment_No = ” + enrolno);
System.out.println (“Name =” +name);
System.out.println (“phone =” +phone);
}
} Catch (Exception e) {
System.out.println ( “ error accessing database” + e.to_string);
}
}
Q5. What are Stored Procedures?
Ans. Stored procedures are collections of small programs that are stored in compiled
form and have a specific purpose. For example, a company may have rules such as:
• A code (like enrolment number) with one of the digits as the check digit, which checks
the validity of the code.
• Any date of change of value is to be recorded.
These rules are standard and need to be made applicable to all the applications that may
be written. Thus, instead of inserting them in the code of each application they may be
put in a stored procedure and reused. The use of procedure has the following advantages
from the viewpoint of database application development.
• They help in removing SQL statements from the application program thus making it
more readable and maintainable.
• They run faster than SQL statements since they are already compiled in the database.
Stored procedures can be created using CREATE PROCEDURE in some commercial
DBMS.
Syntax:
CREATE [or replace] PROCEDURE [user]PROCEDURE_NAME
[(argument datatype
[, argument datatype]….)]
BEGIN
Host Language statements;
END;
For example, consider a data entry screen that allows entry of enrolment number, first
name and the last name of a student combines the first and last name and enters the
complete name in upper case in the table STUDENT. The student table has the following
structure:
STUDENT (enrolno:char(9), name:char(40));
The stored procedure for this may be written as:
CREATE PROCEDURE studententry (
enrolment IN char (9);
f-name INOUT char (20);
l-name INOUT char (20)
BEGIN
/* change all the characters to uppercase and trim the length */
f-name TRIM = UPPER (f-name);
l-name TRIM = UPPER (l-name);
name TRIM = f-name . . l-name;
INSERT INTO CUSTOMER
VALUES (enrolment, name);
END;
INOUT used in the host language indicates that this parameter may be used both for input
and output of values in the database.
While creating a procedure, if you encounter errors, then you can use the show errors
command. It shows all the error encountered by the most recently created procedure
object.
You can also write an SQL command to display errors. The syntax of finding an error in a
commercial database is:
SELECT *
FROM USER_ERRORS
WHERE Name=‘procedure name’ and type=‘PROCEDURE’;
Procedures are compiled by the DBMS. However, if there is a change in the tables, etc.
referred to by the procedure, then the procedure needs to be recompiled. You can
recompile the procedure explicitly using the following command:
ALTER PROCEDURE procedure_name COMPILE;
You can drop a procedure by using DROP PROCEDURE command.
Q6. What are Triggers?
Ans Triggers are somewhat similar to stored procedures except that they are activated
automatically. When a trigger is activated? A trigger is activated on the occurrence of a
particular event. What are these events that can cause the activation of triggers? These
events may be database update operations like INSERT, UPDATE, DELETE etc. A
trigger consists of these essential components:
• An event that causes its automatic activation.
• The condition that determines whether the event has called an exception such that the
desired action is executed.
• The action that is to be performed.
Triggers do not take parameters and are activated automatically, thus, are different to
stored procedures on these accounts. Triggers are used to implement constraints among
more than one table. Specifically, the triggers should be used to implement the constraints
that are not implementable using referential integrity/constraints. An instance, of such a
situation may be when an update in one relation affects only few tuples in another
relation. However, please note that you should not be over enthusiastic for writing
triggers – if any constraint is implementable using declarative constraints such as
PRIMARY KEY, UNIQUE, NOT NULL, CHECK, FOREIGN KEY, etc. then it should
be implemented using those declarative constraints rather than triggers, primarily due to
performance reasons. You may write triggers that may execute once for each row in a
transaction – called Row Level Triggers or once for the entire transaction Statement
Level Triggers. Remember, that you must have proper access rights on the table on which
you are creating the trigger. For example, you may have all the rights on a table or at least
have UPDATE access rights on the tables, which are to be used in trigger. The following
is the syntax of triggers in one of the commercial DBMS:
CREATE TRIGGER <trigger_name>
[BEFORE | AFTER|
<Event>
ON <tablename>
[WHEN <condition> | FOR EACH ROW]
<Declarations of variables if needed is – may be used when creating trigger using host
language>
BEGIN
<SQL statements OR host language SQL statements>
[EXCEPTION]
<Exceptions if any>
END:
Let us explain the use of triggers with the help of an example:
Example:
Consider the following relation of a students database
STUDENT(enrolno, name, phone)
RESULT (enrolno, coursecode, marks)
COURSE (course-code, c-name, details)
Assume that the marks are out of 100 in each course. The passing marks in a subject are
50. The University has a provision for 2% grace marks for the students who are failing
marginally – that is if a student has 48 marks, s/he is given 2 marks grace and if a student
has 49 marks then s/he is given 1 grace mark. Write the suitable trigger for this situation.
Please note the requirements of the trigger:
Event: UPDATE of marks
OR
INSERT of marks
Condition: When student has 48 OR 49 marks
Action: Give 2 grace marks to the student having 48 marks and 1 grace mark to the
student having 49 marks.
The trigger for this thus can be written as:
CREATE TRIGGER grace
AFTER INSERT OR UPDATE OF marks ON RESULT
WHEN (marks = 48 OR marks =49)
UPDATE RESULT
SET marks =50;
We can drop a trigger using a DROP TRIGGER statement
DROP TRIGGER trigger_name;
The triggers are implemented in many commercial DBMS. Please refer to them in the
respective DBMS for more details.
BLOCK-1 UNIT-4
DATABASE SYSTEM CATALOGUE
Q1. What is Data Dictionary? Write the benefits and advantages of Data Dictionary.
Ans. A Data Dictionary is a data structure that stores meta-data, i.e., data about data.
The software package for a stand-alone data dictionary or data repository may interact
with the software modules of theDBMS, but it is mainly used by the designers, users, and
administrators of a computer system for information resource management. These
systems are used to maintain information on system hardware and software
configurations, documentation, applications, and users, as well as other information
relevant to system administration.
If a data dictionary system is used only by designers, users, and administrators, and not
by the DBMS software, it is called a passive data dictionary; otherwise, it is called an
active data dictionary or data directory. An active data dictionary is automatically
updated as changes occur in the database. A passive data dictionary must be manually
updated.
The data dictionary consists of record types (tables) created in the database by system-
generated command files, tailored for each supported back-end DBMS. Command files
contain SQL statements for CREATE TABLE, CREATE UNIQUE INDEX, ALTER
TABLE (for referential integrity), etc., using the specific SQL statement required by that
type of database.
Data Dictionary Features
A comprehensive data dictionary product will include:
• support for standard entity types (elements, records, files, reports, programs, systems,
screens, users, terminals, etc.), and their various characteristics (e.g., for elements, the
dictionary might maintain Business name, Business definition, name, Data type, Size,
Format, Range(s), Validation criteria, etc.)
• support for user-designed entity types (this is often called the “extensibility” feature);
this facility is often exploited in support of data modelling, to record and cross-reference
entities, relationships, data flows, data stores, processes, etc.
• the ability to distinguish between versions of entities (e.g., test and production)
• enforcement of in-house standards and conventions.
• comprehensive reporting facilities, including both “canned” reports and a reporting
language for user-designed reports; typical reports include:
• detail reports of entities
• summary reports of entities
• component reports (e.g., record-element structures)
• cross-reference reports (e.g., element keyword indexes)
• where-used reports (e.g., element-record-program cross-references).
• a query facility, both for administrators and casual users, which includes the ability to
perform generic searches on business definitions, user descriptions, synonyms, etc.
• language interfaces, to allow, for example, standard record layouts to be automatically
incorporated into programs during the compile process.
• automated input facilities (e.g., to load record descriptions from a copy library).
• security features
• adequate performance tuning abilities
• support for DBMS administration, such as automatic generation of DDL (Data
Definition Language).
Data Dictionary Benefits
The benefits of a fully utilised data dictionary are substantial. A data dictionary has the
potential to:
• facilitate data sharing by
• enabling database classes to automatically handle multi-user coordination, buffer
layouts, data validation, and performance optimisations,
• improving the ease of understanding of data definitions,
• ensuring that there is a single authoritative source of reference for all users
• facilitate application integration by identifying data redundancies,
• reduce development lead times by
• simplifying documentation
• automating programming activities.
• reduce maintenance effort by identifying the impact of change as it affects:
• users,
• data base administrators,
• programmers.
• improve the quality of application software by enforcing standards in the development
process
• ensure application system longevity by maintaining documentation beyond project
completions
• data dictionary information created under one database system can easily be used to
generate the same database layout on any of the other database systems BFC supports
(Oracle, MS SQL Server, Access, DB2, Sybase, SQL Anywhere, etc.)
These benefits are maximised by a fully utilised data dictionary. As the next section will
show, our environment is such that not all of these benefits are immediately available to
us.
Disadvantages of Data Dictionary
A DDS is a useful management tool, but it also has several disadvantages. It needs
careful planning. We would need to define the exact requirements designing its contents,
testing, implementation and evaluation. The cost of a DDS includes not only the initial
price of its installation and any hardware requirements, but also the cost of collecting the
information entering it into the DDS, keeping it up-to-date and enforcing standards. The
use of a DDS requires management commitment, which is not easy to achieve,
particularly where the benefits are intangible and long term.