DBMS LAB Manual (R20) Print
DBMS LAB Manual (R20) Print
Database Management
Systems Lab
Dr K ARUNA KUMARI
D N S B KAVITHA
Dr K ARUNA KUMARI: She got her PhD from KL University, M.Tech from Archarya Nagarjuna
University and MCA from Bharathidasan University,. Presently working as Assistant Professor in
the Department of Computer Science and Engineering, SRKR Engineering College, Bhimavaram,
India.
D N S B KAVITHA: She is pursuing PhD from Andhra University, M.Tech and B.Tech from JNTU
Kakinada. Presently working as Assistant Professor in the Department of Computer Science and
Engineering, SRKR Engineering College, Bhimavaram, India.
Copyright of any copyrighted material included in this book rests with the owners. The authors’
intention is not to infringe any copyright. It is for private circulation among B.Tech. (CSE) students.
Evaluation Scheme
Examination Marks
Day to Day Evaluation 5
Record 5
Internal Exam 5
External Exam 35
2
Preface
Database management systems are now an indispensable tool for managing information, and a
course on the principles and practice of database systems is now an integral part of computer
science curricula.
This manual is intended for the second-year students of Computer Science and Engineering in
the subject of Database Management System. This manual typically contains practical/Lab
sessions related to Database Management Systems to enhance understanding.
Students are advised to thoroughly go through this manual rather than only topics mentioned in
the syllabus as practical aspects are the key to understanding and conceptual visualization of
theoretical aspects covered in the books.
3
Course Plan
Second Semester
15 Lab Internal
16 Theory Mid exams
4
Contents
1 Database Creation 6
10 Functions 41
11 Cursors 43
12 Triggers 45
15 Case Studies 64
16 Viva Questions 68
5
Session #1
Data Base Creation
Learning Objective
To familiarize the students with database management systems environment (SQL Developer)
and to create a new user for daily log in.
Learning Context
DBMS is a software system that allows the user to define, to create and maintain the database and
provide control access to the data. The following procedure is to be used to create a user for daily
log in.
3. After getting SQL Developer prompt type the following command to create a new user
user001 for daily log in with 100 mb of space.
5. Now copy emp and dept tables from scott to user001 using the following commands,
commit;
exit;
6
7. Again, go to ORACLE SQL DEVELOPER prompt.
Username : user001
Password : 001
Host string : cse
10. Now start doing the queries and note down the queries and results.
It may be noted that after executing every SQL command we have to execute
and check manually that the result is the desired one or not.
Text Books
1. Abraham Silberschatz, Henry F. Korth, S. Sudarshan, "Database System Concepts",
McGraw-Hill, 4th Edition, 2002.
2. Ivan Bayross, “SQL, PL/SQL The programming language of oracle”, BPB publications, 4th
Revised Edition, 2010.
3. Ramez Elmasri, Shamkant, B. Navathe, “Database Systems”, Pearson Education, 6th
Edition, 2013.
4. Peter Rob, Carles Coronel, “Database System Concepts”, Cengage Learning, 7th Edition,
2008.
5. M L Gillenson, “Introduction to Database Management”, Wiley Student Edition, 2012.
Web References:
1. https://www.tutorialspoint.com/dbms/
2. https://www.javatpoint.com/dbms-tutorial
7
Session #2
DDL and DML Commands
Learning Objective
Creation of Tables and usage of DML commands insert, update and delete.
Learning Context
Create table: Tables are defined using the create command. The simplified form of create
command is
r
INSERT: Tables are constructed using the insert command. The simplified form
of insert command is
8
- Insert, into and values are key words.
- r is the name of relation
- A1, A2, … , An, are attributes of the relation and v1, v2 ,.., vn are the corresponding
values. If the optional attribute list is not given, all the attributes in the relation
are assumed.
- The optional select statement can be used to insert values from another table.
But here it is to be ensured that both tables possess compatible data types.
UPDATE: The attributes values are updated using the update command. The simplified form
of update command is
DROP TABLE: Table can be dropped using drop table. The syntax of the command
is
ALTER TABLE: Table structure can be altered using alters table command. The syntax of
alter table command is
9
- alter table, add, modify, drop, column are key words.
- add, modify, drop are used to append an attribute, to change the data typeof
an existing attribute, and to delete an attribute respectively.
- A is attribute and D is domain type.
Procedure
1. Logon into SQL prompt/ livesql.oracle.com
2. Set the line size using the following command.
set line size 100;
3. Create the tables with create table command.
4. Type the following command after creation or modification of each table to view the
structure of the table.
desc table_name;
5. In between insertions and after all the data is inserted, save the data.
6. After inserting all the data or after modification to data, we can view the data by typing
Select * from table_name;
7. Use the following commands after all the task is completed.
commit;
exit;
Learning Outcome
After undergoing this laboratory module, the student should be able to create, alter and delete
tables using DDL commands and modify the table data using DML commands insert, update and
delete.
Exercise
1. Create three tables with the following schema
Sailors(sid:integer, sname:string, rating:integer, age:real)
Boats(bid:integer, bname:string, color:string)
Reserves(sid:integer, bid:integer, day:date)
Impose the appropriate integrity constraints.
10
2. Insert the following values into the above tables.
11
Session #3
Working with Queries and Nested Queries
Learning Objective
To practice select queries and nested queries.
Learning Context
Nested Queries
A nested query is a query that has another query embedded within it; the embedded query is called a
subquery. Subqueries are an alternate way of returning data from multiple tables.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the
operators like =, <, >, >=, <=, IN, BETWEEN, etc.
SQL subqueries are most frequently used with the Select statement.
Syntax
SELECT column_name
FROM table_name
WHERE column_name expression operator
(SELECT column_name from table_name WHERE ...);
Example:
SELECT sname FROM sailors s
WHERE s.sid = (SELECT DISTINCT r.sid from reserves r WHERE s.sid=r.sid);
This nested query displays the names of sailors who have reserved at least one boat.
IN Operator: - The IN operator allows us to test whether a value is in a given set of elements; an SQL
query is used to generate the set to be tested.
Syntax
SELECT ColumnName(s)
FROM TableName
WHERE ColumnName IN (Value1, Value2...);
Example: -
Find the names of sailors who have reserved boat 103 using IN Operator.
SELECT S.SNAME FROM SAILORS S WHERE S.SID
IN (SELECT R.SID FROM RESERVES R WHERE R.BID = 103);
12
NOT IN Operator: - The NOT IN is used in an opposite manner to IN.
Example: -
Find the names of sailors who have not reserved boat 103 using NOT IN Operator.
SELECT S.SNAME FROM SAILORS S WHERE S.SID
NOT IN (SELECT R.SID FROM RESERVES R WHERE R.BID = 103);
EXISTS Operator: - This is a Correlated Nested Queries operator. The EXISTS operator is another set
comparison operator, such as IN. It allows us to test whether a set is nonempty, an implicit comparison
with the empty set.
Syntax
SELECT ColumnName(s)
FROM TableName
WHERE EXISTS
(SELECT ColumnName FROM TableName WHERE condition);
Example: - Find the names of sailors who have reserved boat number 103.
SELECT S.SNAME FROM SAILORS S WHERE
EXISTS (SELECT * FROM RESERVES R WHERE R.BID = 103 AND R.SID = S.SID );
NOT EXISTS Operator: - The NOT EXISTS is used in an opposite manner to EXISTS.
Example: - Find the names of sailors who have not reserved boat number 103.
SELECT S.SNAME FROM SAILORS S WHERE NOT EXISTS (SELECT * FROM RESERVES
R WHERE R.BID = 103 AND R.SID = S.SID);
ALL Operator: - It is a comparison operator. The ALL operator is used with a WHERE or HAVING clause
and returns TRUE if all of the subquery values meet the condition.
Syntax
SELECT ColumnName(s)
FROM TableName
WHERE ColumnName operator ALL
(SELECT ColumnName FROM TableName WHERE condition);
where the operator is one of the arithmetic, comparison operators {<, <=, =, <>, >=, >}.
SELECT S.SID FROM SAILORS S WHERE S.RATING >= ALL (SELECT S2.RATING FROM
SAILORS S2);
13
ANY Operator: - Similar to the ALL operator, the ANY operator is also used with a WHERE or HAVING
clause and returns true if any of the subquery values meet the condition.
Syntax
SELECT ColumnName(s)
FROM TableName
WHERE ColumnName operator ANY
(SELECT ColumnName FROM TableName WHERE condition);
Example: - Find sailors whose rating is better than some sailor called Horatio
SELECT S.SID FROM SAILORS S WHERE S.RATING > ANY (SELECT S2.RATING FROM
SAILORS S2 WHERE S2.SNAME = ' Horatio ');
BETWEEN Operator: - The BETWEEN operator is used, when you want to select values within a given
range. Since this is an inclusive operator, both the starting and ending values are considered.
Syntax
SELECT ColumnName(s)
FROM TableName
WHERE ColumnName BETWEEN Value1 AND Value2;
LIKE Operator: - The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column of a table.
There are mainly two wildcards that are used in conjunction with the LIKE operator:
% : It matches 0 or more characters.
_ : It matches exactly one character.
Syntax
SELECT ColumnName(s)
FROM TableName
WHERE ColumnName LIKE pattern;
AND Operator: - This operator is used to filter records that rely on more than one condition. This operator
displays the records, which satisfy all the conditions separated by AND, and give the output TRUE.
Syntax
SELECT Column1, Column2, ..., ColumnN
FROM TableName
WHERE Condition1 AND Condition2 AND Condition3 ...;
OR Operator: - This operator displays all those records which satisfy any of the conditions separated by
OR and give the output TRUE.
Syntax
SELECT Column1, Column2, ..., ColumnN
FROM TableName
WHERE Condition1 OR Condition2 OR Condition3 ...;
14
NOT Operator: - The NOT operator is used when you want to display the records which do not satisfy a
condition.
Syntax
SELECT Column1, Column2, ..., ColumnN
FROM TableName
WHERE NOT Condition;
SET OPERATIONS
SQL supports the set operations union, intersection and minus with the keyword’s union, intersect, and
except (minus in oracle).
UNION: The UNION operator returns records from the result of both queries after eliminating the
duplicate records which are common in both. There is another option of union, the UNION ALL operator,
which returns records from the result of both queries, including duplicate records which are common in
both.
Syntax
SELECT ColumnName(s) FROM Table1
UNION
SELECT ColumnName(s) FROM Table2;
INTERSECT: The INTERSECT operator returns the records which are common in the result of both
queries.
Syntax
SELECT Column1 , Column2 ....
FROM TableName
WHERE Condition
INTERSECT
SELECT Column1 , Column2 ....
FROM TableName
WHERE Condition;
EXCEPT: The EXCEPT operator returns the records which are in the result of the first query but not in
the result of the second one.
Syntax
SELECT ColumnName
FROM TableName
EXCEPT
SELECT ColumnName
FROM TableName;
15
Learning Outcome
After undergoing this laboratory module, the student should be able to use SQL select
command in queries and nested queries by including various operators to select the
rows.
Exercise
3. Find the names of sailors who have reserved at least one boat.
4. Find the ids of sailors who reserved a red boat and a green boat.
5. Find the ids of sailors who reserved a red boat or a green boat.
6. Find the ids of sailors who reserved a red boat but not a green boat.
7. Find the names of sailors who reserved every boat.
8. Find the names of sailors who reserved every red boat.
9. Find all sids of sailors who have a rating of 10 or reserved boat number 101.
10. Find the ids of sailors whose rating is more than the average rating of all sailors
11. Find the sids of sailors whose rating is better than some sailors called horatio.
12. Find the sailors whose rating is better than every sailor called horatio.
13. Find the names of boats reserved by dustin and by no one else.
14. Display the details of sailors whose names start with letter r.
15. Display the details of sailors whose names end with letter r.
16. Display the name, rating and age of sailors whose rating is between 8 and 10.
16
Session #4
Aggregate Functions & Views
Learning Objective
To implement Aggregate functions and create, drop views
Learning Context
Aggregate functions: that take a collection of values as input and return a single value.
SQL offers five built-in aggregate functions.
❖ MIN (A) : returns minimum of column values
❖ MAX (A) : returns maximum of column values
❖ AVG ([ distinct] A) : returns average of unique column values
❖ SUM ([ distinct] A) : returns total of unique column values
❖ COUNT ([ distinct] A) : returns number of unique column values
The input to SUM and AVG must be a collection of numbers but the other operators can operate on
collection of non -numeric data types like strings.
For example,
select sum(rating) from sailors; displays total rating of all the sailors.
select count(sid) from sailors; displays no. of sailors.
select count (*) from sailors; displays no. of records in sailors.
All the functions except COUNT (*) ignore null values in their input collection. For SQL null value means
unknown or inapplicable.
group by & having Clauses:
The select statement syntax including optional group by and having clauses is as under:
select [distinct ] select-list from from-list
[where qualification ]
[group by group-list ]
[having group-qualification];
The result of the GROUP BY clause is a grouped table i.e., a set of groups of rows derived from the
table by conceptually rearranging it into the minimum number of groups such that within any one group
all rows have the same value for the combination of columns identified by GROUP BY clause.
Example
select sum(sal) from emp group by job;
17
Using this statement, we get the total salary for each designation of the employees. There is a restriction
on the select clause while using group by. Select item in the select clause must be single valued per
group as for the other aggregate functions. Therefore, a statement like
select empno, sum(sal) from emp group by job;
select * from emp group by job; are invalid.
But we can give
select job from emp group by job;
and
select job, avg(sal) from emp group by job; are valid.
HAVING: clause works very much like a where clause except that its logic is related only to the result
of group functions i.e., having clause is used to eliminate groups whereas where clause is used to
eliminate rows from the whole table.
Example
select deptno, avg(sal) from emp group by deptno having max(sal) > 1500;
Displays average salaries depart wise for departments which have average salary greater than 1500.
VIEWS:
A view is a table whose rows are not explicitly stored in the database, but are computed as needed from
the view definition.
Example
The below command creates a view for dbms teacher to view student name and marks in dbms. But
the original table contains sno, sname and all subject marks.
CREATE VIEW dbms (name, dbmarks) AS SELECT sname, s1 FROM Students;
In SQL, view is said to be updatable (i.e. insert, update or delete) if the following conditions are all
satisfied:
⚫ The from clause has only one relation.
⚫ The select clause contains only attributes of the relation and does not have any expressions,
aggregate functions, or distinct specification.
⚫ Any attribute not in the select clause can be set to null.
NOTE: If we insert a row which does not satisfy condition in the where clause of create view then it is
allowed and that row doesn't appear in the view. To avoid such insertions, we have to use with check
option in the create view.
18
Learning Outcome
After undergoing this laboratory module, the student should be able to use aggreg ate functions
and create views
Exercise
19
Session #5
Queries using Conversion Functions
Learning Objective
To implement conversion functions, String, and Date functions
Learning Context
Date functions
Function Description
Add_months(d, n) Returns a date after adding a specified date with the specified
number of months
Last_day(d) Returns the date corresponding to the last day of the month
Months_between(d1, d2) Returns the number of months between two dates
Next_day(d, day) Displays the next day
Round(d, [fmt]) Returns the date which is rounded to the unit specified by the
format model
Trunc(d, [fmt]) Returns the date with the time portion of day truncated to the unit
specified by format model
Greatest(d1, d2, d3…) Returns the latest date present in the arguments
Character Functions
Function Example
Initcap(char) Select initcap(‘hello’) from dual;
Lower(char) Select lower(‘FUN’) from dual;
Uppder(char) Select upper(‘sun’) from dual;
Ltrim(char, set) Select ltrim(‘xyzadams’,’xyz’) from dual;
Rtrim(char, set) Select rtrim(‘xyzadams’,’ams’) from dual;
Translate(char, from, to) Select translate(‘jack’, ’j’, ’b’) from dual;
Replace(char, searchstring, [rep string]) Select replace(‘jack and jue’, ‘j’, ‘bl’) from dual;
Substr(char, m, n) Select substr(‘abcdefg’, 3, 2) from dual;
20
Conversion Functions
Function Description
To_char(d, [fmt]) Converts date to a value of varchar2 datatype in a form specified
by date format fmt. If fmt is neglected then it converts date to
varchar2 in the default date format
To_date(char, [fmt]) Converts char or varchar datatype to date datatype.
Numeric Functions
Function Example
Abs Select abs(-15) from dual;
Ceil(n) Select ceil(44.778) from dual;
Cos(n) Select cos(180) from dual;
Cosh(n) Select cosh(0) from dual;
Exp(n) Select exp(4) from dual;
Floor(n) Select floor(100.2) from dual;
Power(m,n) Select power(4,2) from dual;
Mod(m,n) Select mod(10,2) from dual;
Round(m,n) Select round(100.256,2) from dual;
Trunc(m,n) Select trunc(100.256,2) from dual;
Sqrt(n) Select sqrt(4) from dual;
Learning Outcome
After undergoing this laboratory module, the student should be able to write queries using
convers ion func tions , stri ng, number and date functions .
Exercise
22
Session #6
PL/SQL
Learning Objective
To implement PL/SQL and Commit, Rollback, and Savepoint
Learning Context
PL/SQL stands for Procedural Language/Structured Query Language. PL/SQL is the
procedural extension to SQL with design features of programming languages. Data
manipulation and query statements of SQL are included within procedural units of code.
PL/SQL Block Structure is as follows.
Exception
Section Description
Required for named blocks. Specifies the way the program
is called by other PL/SQL blocks. Anonymous blocks
Header do not have a header. They start with the DECLARE
keyword if there is a declaration section, or with
the BEGIN keyword if there are no declarations.
It is optional. Declares variables, cursors, TYPEs, and
Declaration local programs that are used in the block’s execution
and exception sections.
Optional in package and TYPE specifications; contains
Execution
statements that are executed when the block is run.
Optional; describes error-handling behavior for
Exception
exceptions raised in the executable section.
23
As we want output of PL/SQL program on screen, before starting writing anything type (Only Once
per session) SET SERVEROUTPUT ON
The following code declares today as date data type and the default value is system date which
can be obtained from the environment variable SYSDATE. Display the date after concatenating
it with the string.
Learning Outcome
After undergoing this laboratory module, the student should be able to write PL/SQL block
and workout with TCL commands commit, sav epoint and ro llback.
Exercise
1. Create a simple PL/SQL program which includes a declaration section, executable section and
exception –Handling section (Ex. Student marks can be selected from the table and printed for those
who secured first class and an exception can be raised if no records were found).
2. Insert data into student table and use COMMIT, ROLLBACK and SAVEPOINT in PL/SQL block.
Solution:
i). We have to create the student table and insert the records in to the table as follows:
SQL> create table student(sid number(10),sname varchar2(20),rank varchar(10));
Table created.
SQL> insert into student values(501,'Ravi','second');
1 row created.
SQL> insert into student values(502,'Raju','third');
1 row created.
SQL> insert into student values(503,'Ramu','');
1 row created.
SQL> select *from student;
SID SNAME RANK
---------- -------------------- ----------
501 Ravi second
502 Raju third
503 Ramu
24
set serveroutput on;
declare
temp1 number(10);
temp2 varchar2(10);
begin
select sid, sname into temp1, temp2 from student where rank='first';
dbms_output.put_line('Student No:'|| temp1 ||' Name:'||temp2||' got first rank');
exception
when no_data_found then
dbms_output.put_line('********************************************');
dbms_output.put_line('# Error: there is no student got first rank');
end;
/
update student set rank='first' where sid=503;
1 row updated.
SQL> select * from student;
SID SNAME RANK
---------- -------------------- ----------
501 Ravi second
502 Raju third
503 Ramu first
Student No:503 Name:Ramu got first rank
PL/SQL procedure successfully completed
PL/SQL CODE:
-- Procedure to execute in livesql worksheet
DECLARE
sno student.sid%type;
name student.sname%type;
srank student.rank%type;
BEGIN
sno := 504;
name := 'Karthik';
srank := 'first';
INSERT into student values(sno, name, srank);
25
dbms_output.put_line('One record inserted');
COMMIT;
-- adding savepoint
SAVEPOINT s1;
-- second time asking user for input
sno := 505;
name := 'Manasa';
srank := 'second';
INSERT into student values(sno,name,srank);
dbms_output.put_line('One record inserted');
ROLLBACK TO SAVEPOINT s1;
END;
/
select * from student;
26
Enter value for name: ali
old 8: name := '&name';
new 8: name := 'ali';
Enter value for srank: first
old 9: srank := '&srank';
new 9: srank := 'first';
Enter value for sno: 505
old 16: sno := &sno;
new 16: sno := 505;
Enter value for name: haji
old 17: name := '&name';
new 17: name := 'haji';
Enter value for srank: third
old 18: srank := '&srank';
new 18: srank := 'third';
One record inserted
One record inserted
27
Session #7
Control Statements, NULLIF, COALESCE
Learning Objective
Develop a program that includes the features NESTED IF, CASE and CASE expression. The program
can be extended using the NULLIF and COALESCE functions.
Learning Context
Decision Making Statements in PL/SQL
In PL/SQL. Decision-making structures require that the programmer specify one or more conditions
to be evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the condition
is determined to be false.
IF STATEMENT:
The IF statement associates a condition with a sequence of statements enclosed by the keywords
THEN and END IF. If the condition is TRUE, the statements get executed, and if the condition is
FALSE or NULL, then the IF statement does nothing.
Syntax:
IF condition THEN
Executable statement(s)
END IF;
28
DECLARE
a number(2) := 10;
BEGIN
a:= 10;
-- check the boolean condition using if statement
IF( a < 20 ) THEN
-- if condition is true then print the following
dbms_output.put_line('a is less than 20 ' );
END IF;
dbms_output.put_line('value of a is : ' || a);
END;
/
IF – ELSE STATEMENT
A sequence of IF-THEN statements can be followed by an optional sequence
of ELSE statements, which execute when the condition is FALSE.
Syntax
IF condition THEN
TRUE sequence of_ executable statement(s)
ELSE
FALSE/ NULL sequence_ of_ executable statement(s)
END IF;
ELSIF STATEMENT
The IF-THEN-ELSIF statement allows you to choose between several alternatives. An IF- THEN
statement can be followed by an optional ELSIF...ELSE statement. The ELSIF clause lets you add
additional conditions.
29
When using IF-THEN-ELSIF statements there are a few points to keep in mind.
• It's ELSIF, not ELSEIF.
• An IF-THEN statement can have zero or one ELSE's and it must come after any ELSIF's.
• An IF-THEN statement can have zero to many ELSIF's and they must come before the
ELSE.
• Once an ELSIF succeeds, none of the remaining ELSIF's or ELSE's will be tested.
IF condition-1 THEN
Statements-1
ELSIF condition- N THEN
Statements-N
[ELSE
ELSE statements]
END IF;
CASE STATEMENT
Like the IF statement, the CASE statement selects one sequence of statements to execute.
However, to select the sequence, the CASE statement uses a selector rather than multiple Boolean
expressions. A selector is an expression, the value of which is used to select one of several
alternatives.
Syntax
CASE selector
WHEN expression1 THEN result 1
WHEN expression2 THEN result 2
...
WHEN expressionN THEN result N [ ELSE] result N+ 1; ]
END CASE;
30
Example
DECLARE
grade char(1) := 'A';
BEGIN
CASE grade
when 'A' then dbms_output.put_line('Excellent');
when 'B' then dbms_output.put_line('Very good');
when 'C' then dbms_output.put_line('Well done');
when 'D' then dbms_output.put_line('You passed');
when 'F' then dbms_output.put_line('Better try again');
else dbms_output.put_line('No such grade');
END CASE;
END;
/
DATA TYPES
The PL/SQL variables, constants and parameters must have a valid data type, which specifies a
storage format, constraints, and a valid range of values.
- CHAR [(maximum_ length)]
- VARCHAR2 (maximum_length )
- NUMBER [(precision, scale )]
- DATE
- % TYPE Attribute
Declares a variable according to a database column definition or previously declared variable.
Example:
Procedure that displays name of an employee if his empno is given. It uses the %
type.
31
NULLIF: Takes two arguments. If the two arguments are equal, then NULL is returned. Otherwise, the
first argument is returned.
Syntax
select column_name, NULLIF(argument1,argument2) from table_name;
Example
select ename, nullif('sita','sita1') from emp;
ENAME NUL
---------- ---
Ram Sita
Sita Sita
Lakshman Sita
Hanuma Sita
COALESCE: COALESCE () function accepts a list of arguments and returns the first one that evaluates
to a non-null value.
Syntax
coalesce("expression1","expression2",...);
Example
SQL> select coalesce(NULL,'DBMS','OS',’JAVA’) from dual;
COALE
-------
DBMS
32
Learning Outcome
After undergoing this laboratory module, the student should be able to write PL/SQL blocks
using c ontr ol statements (if, case ) and the s ignificanc e of nullif and coalesce
functions .
Exercise
33
Session #8
Loop Statements, Exceptions
Learning Objective
Program development using WHILE LOOPS, numeric FOR LOOPS, nested loops using ERROR
Handling, BUILT –IN Exceptions, User defined Exceptions, RAISE APPLICATION ERROR.
Learning Context
PL/SQL LOOPS
There may be a situation when you need to execute a block of code several number of times. In
general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages −
Basic loop structure encloses sequence of statements in between the LOOP and END LOOP
statements. With each iteration, the sequence of statements is executed and then control resumes
at the top of the loop.
Syntax
LOOP
Sequence of statements;
END LOOP;
Here, the sequence of statement(s) may be a single statement or a block of statements. An
EXIT statement or an EXIT WHEN statement is required to break the loop.
34
Example
DECLARE
x number := 10;
BEGIN
LOOP
dbms_output.put_line(x);
x := x + 10;
IF x > 50 THEN
exit;
END IF;
END LOOP;
-- after exit, control resumes here
dbms_output.put_line('After Exit x is: ' || x);
END;
/
FOR LOOP
A FOR LOOP is a repetition control structure that allows you to efficiently write a loop that needs
to execute a specific number of times.
The REVERSE keyword causes PL/SQL to start with the highest_ number
and decrement down to the lowest_ number
Example
DECLARE
a number(2);
BEGIN
FOR a in 10 .. 20 LOOP
dbms_output.put_line('value of a: ' || a);
END LOOP;
END;
/
35
Example
DECLARE
a number(2) ;
BEGIN
FOR a IN REVERSE 10 .. 20 LOOP
dbms_output.put_line('value of a: ' || a);
END LOOP;
END;
/
WHILE STATEMENT
Example
DECLARE
a number(2) := 10;
BEGIN
WHILE a < 20 LOOP
dbms_output.put_line('value of a: ' || a);
a := a + 1;
END LOOP;
END;
/
Raising Exceptions
Exceptions are raised by the database server automatically whenever there is any internal database
error, but exceptions can be raised explicitly by the programmer by using the command RAISE.
36
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;
User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of your program. A user-defined
exception must be declared and then raised explicitly, using either a RAISE statement or the procedure.
DBMS_STANDARD.RAISE_APPLICATION_ERROR.
Pre-defined Exceptions
PL/SQL provides many pre-defined exceptions, which are executed when any database rule is violated
by a program. For example, the predefined exception NO_DATA-FOUND is raised when a SELECT
INTO statement returns no rows.
The following table lists few of the important pre-defined exceptions.
DUP_VAL_ON_INDEX ORA-00001 -1
37
PROGRAM_ERROR ORA-06501 -6501
Learning Outcome
After undergoing this laboratory module, the student should be able to write PL/SQL blocks
using loop s tatements (while, for) and the s ignificanc e of exc eption handling by
creating and raising th e ex ceptions
Exercise
1. Write a PL/SQL program to print the sum of N natural numbers using while loop.
2. Write a PL/SQL program to print the sum of even numbers using for loop.
3. Write a PL/SQL program to print prime numbers upto given N value using for loop.
4. Write a PL/SQL program to print a pyramid of stars using a nested for loop.
5. Write a PL/SQL program to show pre_defined exception ZERO_DIVIDE
6. Write a PL/SQL program to show pre_defined exception CASE_NOT_FOUND
7. Write a PL/SQL program to Raise user_defined exception
38
Session #9
Procedures
Learning Objective
To create and execute procedures passing IN and OUT parameters in PL/SQL.
Learning Context
Procedures: Procedures are standalone blocks of a program that can be stored in the database.
• Can receive multiple input parameters and return multiple output values (or no output values)
• Can perform an action such as insert, update or delete record
In an Oracle stored procedure, the specified arguments and parameters include IN,
OUT, or IN OUT. The parameter mode specifies whether a parameter can be read from or
write to.
IN
An IN parameter is read-only. You can reference an IN parameter inside a procedure, but you
cannot change its value. Oracle uses IN as the default mode. It means that if you don’t specify the
mode for a parameter explicitly, Oracle will use the IN mode.
OUT
An OUT parameter is writable. Typically, you set a returned value for the OUT parameter and
return it to the calling program. Note that a procedure ignores the value that you supply for an OUT
parameter.
INOUT
An INOUT parameter is both readable and writable. The procedure can read and modify it.
Note that OR REPLACE option allows you to overwrite the current procedure with the new code.
39
Example:
Procedure that computes and displays tax to be paid if income is passed as parameter
BEGIN
Execution
Exec tax1(1000);
output:80
Learning Outcome
After undergoing this laboratory module, the student should be able to write PL/SQL
procedures .
Exercise
1. Create a procedure to insert a new record into the emp table using the IN parameter.
2. Create a procedure to print the name of an employee if his id is given using OUT parameter.
40
Session #10
Functions
Learning Objective
Program development using creation of stored functions, invoke functions in SQL Statements and
write complex functions.
Learning Context
A function is similar to a procedure, except that it returns a single value
Example:
Function that returns tax to be paid if income is passed as parameter
Execution
a. select tax2(1000) from dual;
Or
b. Execute Following sequence of statements for getting the value returned by the function into bind
variable and print it.
variable v1 number;
exec :v1:=tax2(1000);
print v1;
41
In Oracle, user- defined functions and stored procedures are very similar in
composition and structure. The primary difference is that stored procedures cannot
return a value to the invoking process, while a function may return a single value to the
invoking process.
The IN qualifier is provided when invoking the function and passes a value in to the
function, while OUT arguments pass a value back to the invoking process. In other
words, the IN qualifier is supplied by the user or process that calls the function, while
the OUT argument is returned by the function. IN OUT arguments perform both IN and
OUT functionality.
Learning Outcome
After undergoing this laboratory module, the student should be able to write PL/SQL functions .
Exercise
1. Write a Function in PL/SQL to take your date_of_birth as input to your function and display the
calculated age.
2. Write a Function in PL/SQL to find the factorial of a given number using the IN parameter.
3. Write a Function in PL/SQL to find the reverse of a number using the INOUT parameter.
42
Session #11
CURSORS
Learning Objective
Develop programs using features parameters in a CURSOR, FOR UPDATE CURSOR, WHERE
CURRENT of clause and CURSOR variables.
Learning Context
CURSORS:
The syntax of cursor declaration is
The DECLARE CURSOR command enables the retrieval and manipulation of records
from a table one row at a time. This provides row-by-row processing, rather than the
traditional set processing offered by SQL. To use this procedure properly, you should:
Example
The following code creates procedure to display empno and ename of all employees in emp
table using cursors.
43
Example:
The following code creates procedure to update salaries of employees using cursors
Learning Outcome
After undergoing this laboratory module, the student should be able to manipulate record by
record data u s ing cursors.
Exercise
1. Create a procedure to display empno and ename of all employees in emp table using cursors.
2. Create a procedure to update salaries of employees using cursors
44
Session #12
Triggers
Learning Objective
To create triggers and to study the behavior of triggers.
Learning Context
A trigger is a special kind of stored procedure that fires automatically (hence, the term
trigger) when a data- modification statement is executed. Triggers are associated with
a specific data- modification statement (INSERT, UPDATE, or DELETE) on a specific
table.
Triggers, by default, fire once at the statement level. That is, a single INSERT statement
might insert 500 rows into a table, but an insert trigger on that table fires only one time.
Some vendors allow a trigger to fire for each row of the data- modification operation.
So, a statement that inserts 500 rows into a table that has a row- level insert trigger fires
500
Triggers that fire before or instead of the data- modification statement do not see the
changes that the statement renders, while those that fir e afterwards can see and act
upon the changes that the data- modification statement renders. It may be noted that
Oracle allows INSTEAD OF triggers to process only against views, not / tables.
45
Examples:
The first trigger is invoked whenever there is an update operation on the emp table rows
and if salary is changed. It records these changes in another table to know the changes
made to the table. The second trigger is invoked whenever there is an insert, delete or
update operation on the emp1 table rows and the changes are recorded in the empl and
empl1 tables.
IF;
Learning Outcome
After undergoing this laboratory module, the student should be able to write Triggers to
maintain databas e consistency at the time of manipulation.
Exercise
1. Create a trigger on ‘dbms’ table whenever there is an insertion of a row. If the marks
are < 0 insert 0 and insert 100 when marks is > 100.
2. Create a trigger which inserts the changes made into a dbms_change table on dbms
table before there is a deletion or modification of a row.
3. Create a trigger on account table which is invoked whenever an account is created
or an amount is withdrawn such that the balance should be always greater than or
equal to 500.
4. Create a trigger on account table which is invoked after an amount is deposited to
display the amount of balance in the account with account number.
46
APPENDIX
Creation of Forms and Reports in MS-Access
Learning Objective
To familiarize with MS Access, open an existing database, create new data base, to create forms
and reports in MS - Access.
Learning Context
MS Access is a relational database that facilitates the storage and retrieval of structured
information. Access databases are, ideally, a set of tables that are related in one way or
another. Along with tables,
Access allows us to create:
- Query-organizing or collecting a particular set of data
- Form-interfaces that allow you to maintain or edit records/ data
- Report-printable results
- Macros-extended functionality for the database, an advanced function all of
these objects is stored in a single file with “. mdb” file extension.
PROCEDURE:
Part-I Opening an Existing database:
- Click on the Windows Start button, select All Programs, and
then click Microsoft Access.
- Click on the FILE menu, then open and select the .mdb
file to be opened and then click open. Then the following
screen appears
- Double click the t able to open the table.
- The t able contents are displayed as shown below.
- Then we navigate to the required record using the record
navigation buttons.
- To add a record of data, move to the first empty record
and type in the data values and press TAB to move to the
next field.
- To save a record of data move to the first empty field below
these records. We do not require to do anything else to save
your data. When we l eave a record, either by moving to another
record or by closing a table, Microsoft access automatically
saves the data.
- Edit a record after moving to the required record and use
TAB and SHIFT+TAB to move to next field and previous field.
47
- Go to FILE menu and click exit to exit from Access.
48
7. Enter the field width in the field property window.
8. Right click the field which uniquely identifies a record in the table and
click primary key option.
9. Set the other properties like
- Required yes or no depending on whether the field value can be set
to null or not null.
- Validation rule like <= 100 for ensuring value in the marks field to be
not greater than 100.
10. Now save it with a new table name for example table1.
11. Close the design view and double click the table1 object to enter the
data.
12. After editing is completed close the data sheet view and
exit from MS Access.
Note: - we can also create table using create table by wizard or create
table by entering data.
You can use the Data Type property to specify the type of data stored in atable
field. Each field can store data consisting of only a single data type.The Data
Type property uses the following settings.
50
Text or combinations of text and Each part of the three parts of a
Hyperlink
numbers stored as text and used as Hyperlink data type can contain
A hyperlink address. A hyperlink up to 2048 characters
address can have up to three p arts: Each part of the three parts of a
text to display — the text that appears Hyperlink data type can contain
in a field or control. Address: the up to 2048 characters..
path to a file (UNC path) or page (URL).
Sub address: a location within the file or
page.
Screen tip: the text displayed as a
tooltip.
The easiest way to insert a
hyperlink address in a field
or control is to click Hyperlink on The
Insert menu.
Creates a field that allows you to The same size as the primary
Lookup
choose a value from another table key field used to perform the
Wizard
or from a list of values by using a list lookup, typically y 4 bytes.
box or combo box. Clicking this option
starts the Lookup Wizard, which creates
a Lookup field. After you complete the
wizard, Microsoft The same size as
the primary key field used to perform the
lookup, typically y 4 bytes.
Access sets the data type based on
the values selected in the wizard.
The form is a formatted display where data is entered, displayed and edited. It
provides greater flexibility than a table. A report is a like a query but is formatted for
printing. As the data is entered data into a form simultaneously data is adding to
the table. In man y cases the tables can become quite large and difficult to read,
especially when we only want information from individual records. An easier
way to view the information in a table is to use a form which is easily created in
Access. Microsoft Access divides a form into five sections in the Design view.
The form header prints at the top of the first page. When we are viewing data,
the form header appears once at the top of the window.
- The page header prints at the top of every page
- The p age header only app ears when printed or in print preview.
- The detail section contains the fields from the t able. When we are viewing
data, the detail section is repeated for each record. When we print the form,
the detail section shows as many records as will fit on a page.
- The page footer prints at the bottom of every page.
- The p age footer only appears when printed or in print preview.
- The form footer prints at the bottom of every page. When we are viewing data,
the footer appears once at the bottom of the window.
51
Design view of Form:
TOOL BOX:
The tool b ox is special kind of tool bar. Control is a
graphical user interface object, such as a text box, check
box, scroll bar, or command button, that lets users control
the program. We use controls to display data or choices,
perform an action, or make the user interface easier to read
Open a form, report, or data access page in Design view.
Toolbox is a set of tools that are available in Design view
to add controls to a form, report, or data access page. To
create a control using the tool box click the tool for the
control we want to create and then drag it and drop it.
TEXT BOXES
We use text boxes on a form, rep ort, or data access to display
data from a record source. This type of text box is called
a bound text box because it’s bound to data in a field. Text
boxes can also be unbound. For example, we can create an
unbound text box to display the results of a calculation or
to accept input from a user. Data in an unbound text box isn’t
stored anywhere.
LABELS
We use labels on a form, report, to display descriptive text
such as titles, captions, or brief instructions.
52
LIST BOXES
The list in a list b ox consists of rows of data. In a form, a list box can have one or more
columns, which can appear with or without headings. If a multiple- column list b
ox is bound .Bound control is a control used on a form, rep ort, or data access page to
enter or display the contents of a field in the underlying table, query, or SQL statement.
The control's Control Source property stores the field name to which the control is
bound. Access stores the values from one of the columns. In a data access page, a list box
has on e column without a heading.
COMBO BOXES
A combo box is like a text box and a list box combined, so it requires less room. We can type
new values in it, as well as select values from a list.
COMMAND BUTTONS
Command buttons provide us with a way of performing action(s) by simply clicking
them. When we choose the button, it not only carries out the appropriate action, it also
looks as if it's being pushed in and released. We use a command button on a form to
start an action or a set of actions. For example, we can create a command button that
opens another form. To make a command button do something on a form, we write
an event procedure and attach it to the button's On Click property.
CHECK BOXES
We can use a check box on a form, report, or as a stand- alone to display a Yes/No value from an
underlying table, query, or SQL statement.
OPTION BUTTONS
We can use an option button on a form, report, or data access page as a stand- alone control
to display a Yes/ No value from an underlying record source. We can also use option
buttons in an option group to display values to choose from.
The option group is the frame that surrounds the controls inside it. Only one option in
an option group can be selected at a time. If an option group is bound to a field, only
the group frame itself is bound not the check boxes, toggle buttons, or option buttons
inside the frame. Because the Control Source property of the group frame is set to
the field that the option group is bound to, we don’t set the Control Source property for
each in the option group. Instead, we set the Option Value (form or report) or the
Value(data access Page) property of each check box, toggle button, or option button. In
a form or report, set the control property to a number that's meaningful for the field the
group frame is bound to. In a data access page, set the control property to either a number
or any text that’s meaningful for the field the group frame is bound to. When we select
an option in an option group, Access sets the value of the field to which the option group
is bound to the value of the selected option's Option Value or Value property.
TOGGLE BUTTONS
We can use a toggle button on a form as a standalone to display a Yes/ No value from
an underlying record source.
53
TABBED PAGES ON FORMS
We can use a tab control to present several pages of information as a single set. This is especially
useful when we're working with many controls that can be sorted into two or more categories.
For example, we might use a tab control on an Employees form to separate employment history
and personal information. Information about employment history is displayed on this page.
Personal information, such as home address and phone number, is displayed on this page.
Procedure:-
Part-I
CREATION OF FORMS:
1. Click on Forms in the Objects column and select either the wizard or design view.
2. The wizard asks which table the form is to come from, and then which fields you
want. Give the table name and select the fields and move to the selected field list
by clicking right arrow button.
3. Select a layout, style, and a title to complete your form. This then opens in form view
for you to begin entering or viewing information.
4. Change to design view to customize.
Part II
CREATION OF REPORTS:
1. Click Report in the Object column and select the wizard or design view. The
wizard asks which t able or query you want to print.
2. Give the table name and then select the fields to print.
3. Select grouping levels grouping brings entries together in the same category,
say all people living in Dallas.
4. Select fields to sort and whether to sort ascending or d e s c e n d i n g order. Up
to four fields can be sorted.
5. Then select the layout i.e. columnar, tabular, or justified.
6. Finally, select a style and a title.
7. The report opens in print preview.
8. Switch to design view to change the formatting.
When we print the report, sections are repeated, as appropriate, until all the data in
the report is printed. The controls in each section tell Microsoft Access what data to print
in the section. The Report Header prints at the beginning of the report. The Page
Header and Footer prints on every page. The Category Header and Footer prints for
each category. The Details section prints for each record in the category Controls that
we can use to display, enter, filter, or organize data in Access.
54
Learning Outcome
After undergoing this laboratory module, the student should be able to c reate database
and generate f orms and reports in MS -ACCESS.
Exercise
1. Create a form for entering the data into student table
which is already created in the previous experiment.
2. Create a form for each subject teacher to enter marks
in the concerned subject.
3. Create a report to head of the department to view all
subject marks of the students.
4. Create a report displaying roll list (roll number and
name of the students) from the student table.
55
My SQL
Learning Objective
To practice simple MySQL commands for retrieving data.
Learning Context
MySQL is primarily an RDBMS and ships with no GUI tools to administer MySQL databases
or manage data contained within the databases. Users may use the included command line
tools,
MySQL uses all the standard ANSI SQL numeric data types, so if you’re coming to MySQL
from a different database system, these definitions will look familiar to you. The following
list shows the common numeric data types and their descriptions.
INT - A normal-sized integer that can be signed or unsigned. If signed, the allowable range
is from -2147483648 to 2147483647. If unsigned, the allowable range is from 0 to
4294967295. You can specify a width of up to 11 digits.
TINYINT - A very small integer that can be signed or unsigned. If signed, the allowable range
is from -128 to 127. If unsigned, the allowable range is from 0 to 255. You canspecify a width
of up to 4 digits.
SMALLINT - A small integer that can be signed or unsigned. If signed, the allowable range
is from -32768 to 32767. If unsigned, the allowable range is from 0 to 65535. You can specify
a width of up to 5 digits.
BIGINT - A large integer that can be signed or unsigned. If signed, the allowable range is
from -9223372036854775808 to 9223372036854775807. If unsigned, the allowable rangeis
from 0 to 18446744073709551615. You can specify a width of up to 11 digits.
FLOAT(M,D) - A floating-point number that cannot be unsigned. You can define the display
length (M) and the number of decimals (D). This is not required and will default to 10,2, where
2 is the number of decimals and 10 is the total number of digits (including decimals). Decimal
precision can go to 24 places for a FLOAT.
DATE - A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31. For example,
December 30th, 1973 would be stored as 1973-12-30.
YEAR(M) - Stores a year in 2-digit or 4-digit format. If the length is specified as 2 (for example
YEAR(2)), YEAR can be 1970 to 2069 (70 to 69). If the length is specified as 4, YEAR can
be 1901 to 2155. The default length is 4.
String Types:
Although numeric and date types are fun, most data you'll store will be in string format. This
list describes the common string datatypes in MySQL.
CHAR(M) - A fixed-length string between 1 and 255 characters in length (for example
CHAR(5)), right-padded with spaces to the specified length when stored. Defining a length
is not required, but the default is 1.
VARCHAR(M) - A variable-length string between 1 and 255 characters in length; for example
VARCHAR(25). You must define a length when creating a VARCHAR field.
BLOB or TEXT - A field with a maximum length of 65535 characters. BLOBs are "Binary
Large Objects" and are used to store large amounts of binary data, such as images or other
types of files. Fields defined as TEXT also hold large amounts of data; the difference
between the two is that sorts and comparisons on stored data are case sensitive on BLOBs
and are not case sensitive in TEXT fields. You do not specify a length with BLOB or TEXT.
Characteristic:
COMMENT 'string'
| LANGUAGE SQL
| [NOT] DETERMINISTIC
| { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
routine_body:
Valid SQL routine statement
PARAMETERS OF PROCEDURE
The real benefit of a stored procedure is of course when you can pass values to it, as well
as receive values back. The concept of parameters should be familiar to anyone who has
had experience with any procedural programming experience.
There are three types of parameter:
IN: The default. This parameter is passed to the procedure, and can change inside the
procedure, but remains unchanged outside.
OUT: No value is supplied to the procedure ( it is assumed to be NULL), but it can be
58
modified inside the procedure, and is available outside the procedure.
INOUT: The characteristics of both IN and OUT parameters. A value can be passed to the
procedure, modified there as well as passed back again.
Database
information_ schema cd col
mysql
phpmy
admin
test
5 rows in set ( 0. 03 sec)
Mysql> use mysql; Database
changed mysql> show
tables;
Tables in mysql
columns_ priv db
event
tables_ priv
time_ zone
time_ zone_leap_ second
time_ zone_ name
time_ zone_ tranition
time_ zone_ transition_ type user
23 rows in set( 0. 05 sec)
Database
information_ schema cd col
mysql
php
my
admin
test
db
6 rows in set ( 0. 00 sec)
Database
information_ schema db
2 rows in set ( 0. 00 sec)
60
An OUT using example
mysql> CREATE PROCEDURE sp_ out( OUT p VARCHAR( 10)) SET p=‘ 5th sem‘;
Query OK, o rows affected ( 0. 00 sec)
mysql> CALL sp_ out(@X);
Query OK, 0 rows affected( 0. 00 sec)
mMysql> select @X;
@X
5th sem
1 row in set ( 0. 00 sec)
( or)
mysql> SET @X=‘ 5th sem‘;
Query OK, 0 rows affected ( 0. 00 sec)
Mysql> select @X;
@X
5th sem
1 row in set ( 0. 00 sec)
Creating a Function
mysql> CREATE FUNCTION hello ( s CHAR( 20))
RETURNS CHAR( 50)
DETERMINISTIC
RETURN CONCAT( s);
Query OK, 0 rows affected ( 0. 00 sec)
In general, SQL statements can be embedded anywhere in a program that host language
statements are allowed.
The following example shows a simple embedded SQL program that retrieves an employee
name and salary from the database and prints them on a standard output device. The
statements that begin with the words EXEC SQL are embedded SQL statements. The
sequence of statements in this example illustrates a pattern common to most embedded SQL
programs.
begin program
exec sql include sqlca;
exec sql begin declare section;
name character_string(15);
salary float;
exec sql end declare section;
exec sql whenever sqlerror stop;
exec sql connect personnel;
exec sql select ename, sal
into :name, :salary
61
from employee
where eno = 23;
print name, salary;
exec sql disconnect;
end program
Next is an SQL declaration section. Host language variables must be declared to SQL prior
to their use in any embedded SQL statements. Host language variables are described in
detail in the next section.
The WHENEVER statement that follows uses information from the SQLCA to control program
execution under error or exception conditions. In general, an error handling mechanism must
precede all executable embedded SQL statements in a program. For details about error
handling, see Error Handling in the chapter “Working with Transactions and Handling Errors.”
Next is a series of SQL and host language statements. The first statement initiates access
to the personnel database. A CONNECT statement must precede any references to a
database.
Next is the familiar SELECT statement, containing a clause that begins with the keyword
INTO. The INTO clause associates values retrieved by the SELECT statement with host
language variables in the program. Following the INTO keyword are the two host language
variables previously declared to SQL: name and salary.
The last SQL statement in the program severs the connection of the program to thedatabase.
Consider a simple C program to illustrate embedded SQL. This program below accepts student
62
name from the user and queries DB for his student id.
#include <stdio.h>
#include <sqlca.h>
int main()
{
EXEC SQL INCLUDE SQLCA;
EXEC SQL BEGIN DECLARE SECTION;
BASED ON STUDENT.STD_ID SID; // host variable to store the value
returned by query
char *STD_NAME; // host variable to pass the value to the query
short ind_sid;// indicator variable
EXEC SQL END DECLARE SECTION;
//Error handling
EXEC WHENEVER NOT FOUND GOTO error_msg1;
EXEC WHENEVER SQLERROR GOTO error_msg2;
printf("Enter the Student name:");
scanf("%s", STD_Name);
// Executes the query
EXEC SQL SELECT STD_ID INTO : SID INDICATOR ind_sid FROM STUDENT
WHERE STD_NAME = : STD_NAME;
printf("STUDENT ID:%d", STD_ID); // prints the result from DB
exit(0);
// Error handling labels
error_msg1:
printf("Student Id %d is not found", STD_ID);
printf("ERROR:%ld", sqlca->sqlcode);
printf("ERROR State:%s", sqlca->sqlstate);
exit(0);
error_msg2:
printf("Error has occurred!");
printf("ERROR:%ld", sqlca->sqlcode);
printf("ERROR State:%s", sqlca->sqlstate);
exit(0);
}
Learning Outcome
After undergoing this laboratory module, the student should be able to c reate database
in MySQL and acc ess it from a c program.
Exercise
1. Practice the questions in Experiment No. 1 SQL queries in the MYSQLenvironment.
2. Practice the questions in Experiment No. 2 for creation of tables, modification of table
structure and inserting values into the tables in the MYSQL environment also.
3. Practice the questions in Experiment No 3 for practicing SQL set operations, joins and
nested queries in the MYSQL environment also.
63
Case Studies
Learning Objective
To develop Database application using DBMS design steps.
Learning Outcome
The student should be able to design a database for the giv en application by
applying design s teps .
Requirement Analysis:
This step includes obtaining the problem statement from user requirements like
- Seat Reservation.
- Cancel Reservation
- Update train information and report generation.
- View Reservation status and train Schedule.
64
Conceptual Database Design:
65
Logical Database Design:
66
Schema Refinement:
This step includes Normalization. By the process of Normalization, we get Normal forms
like 1NF, 2NF, 3NF, 4NF and BCNF.
Creation of Tables:
CREATE TABLE
Insertion of Data :
1. What is SQL?
Structured Query Language (SQL) being ANSI standard language updates database and
commands for accessing.
2. What is database?
A database is a logically coherent collection of data with some inherent meaning,
representing some aspect of real world and which is designed, built and populated with
data for a specific purpose.
3. What is DBMS?
It is a collection of programs that enables user to create and maintain a database. In
other words it is general-purpose software that provides the users with the processes of
defining, constructing and manipulating the database for various applications.
6. Advantages of DBMS?
• Redundancy is controlled.
• Unauthorized access is restricted.
• Providing multiple user interfaces.
• Enforcing integrity constraints.
• Providing backup and recovery.
68
8. Segregate database technology’s development.
The development of database technology is divided into:
• Structure or data model
• Navigational model
• SQL/ relational model
70
21. What is an attribute?
It is a particular property, which describes the entity.
71
30. What is VDL (View Definition Language)?
It specifies user views and their mappings to the conceptual schema.
72
37. Enlist the cursor types.
They are:
• Dynamic: it reflects changes while scrolling.
• Static: doesn’t reflect changes while scrolling and works on recording of snapshot.
• Keyset: data modification without reflection of new data is seen.
47. What restrictions can you apply when you are creating views?
Restrictions that are applied are:
• Only the current database can have views.
• You are not liable to change any computed value in any particular view.
• Integrity constants decide the functionality of INSERT and DELETE.
• Full-text index definitions cannot be applied.
• Temporary views cannot be created.
• Temporary tables cannot contain views.
• No association with DEFAULT definitions.
• Triggers such as INSTEAD OF is associated with views.
.
74
50. Enlist the advantages of normalizing database.
Advantages of normalizing database are:
• No duplicate entries
• Saves storage space
• Boasts the query performances
75
56. What is 2NF?
A relation schema R is in 2NF if it is in 1NF and every non-prime attribute A in R is fully
functionally dependent on primary key.
76