22cs4001 Dbms Lab Manual
22cs4001 Dbms Lab Manual
LAB MANUALS
To provide an excellence for individuals to develop technologically superior, socially conscious and
nationally responsible citizens.
MISSION
M1: To develop competent Computer Science and Engineering professionals with knowledge in current
technology.
M2: To mould them to attain excellent leadership qualities there by making them excel in their careers.
M3: To inspire and nurture students to come out with innovation and creativity solutions meeting the societal
needs.
PEO2: To be capable of modeling, designing, implementing, and verifying a computing system to meet
specified requirements for the benefit of society.
PEO3: To possess critical thinking, communication skills, teamwork, leadership skills, and ethical behaviour
necessary to function productively and professionally.
PSO2: Ability to understand, design, and code engineering problems using programming skills.
PROGRAM OUTCOMES
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and an
engineering specialization to the solution of complex engineering problems
2. Problem analysis: Identify, formulate, research literature, and analyze complex engineering Problems
reaching substantiated conclusions using first principles of mathematics, natural sciences, and engineering
sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and design system
components or processes that meet the specified needs with appropriate consideration for the public
health and safety, and the cultural, societal, and environmental considerations
4. Conduct investigations of complex problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering
and IT tools including prediction and modeling to complex engineering activities with an understanding
of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the Professional
engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in diverse
teams, and in multidisciplinary settings
10. Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports and
design documentation, make effective presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one’s own work, as a member and leader in a team, to manage
projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in independent
and life-long learning in the broadest context of technological change.
COURSE OBJECTIVES
S.NO DESCRIPTION
COURSE OUTCOMES
S.NO DESCRIPTION
Integrity Constraints
4 3 Analyzing
1. Data Definition Commands, Data Manipulation Commands for inserting, deleting, updating and
retrieving
2. Data Control and Transaction Control statements
3. Database Querying – Simple queries, Nested queries, Sub queries and Joins
4. Integrity Constraints
5. Views, Sequences, Synonyms
6. Database Programming: Implicit and Explicit Cursors
7. Procedures and Functions
8. Triggers
9. Exception Handling
10. Development of mini-projects with front end of your choice.
TOTAL: 45 PERIODS
REFERENCE: spoken-tutorial.org
SOFTWARE:
Front end: VB/VC ++/JAVA or Equivalent
Back end: Oracle / SQL / MySQL/ PostGress / DB2 or Equivalent
INTRODUCTION TO SQL
WHAT IS SQL?
SQL is Structured Query Language, which is a computer language for storing, manipulating and retrieving
data stored in relational database.
SQL is the standard language for Relation Database System. All relational database management systems like
MySQL, MS Access, Oracle, Sybase, Informix, postgres and SQL Server use SQL as standard database
language.
Why SQL?
History of SQL
1970 -- Dr. E. F. "Ted" of IBM is known as the father of relational databases. He described a
relational model for databases.
1974 -- Structured Query Language appeared.
1978 -- IBM worked to develop Codd's ideas and released a product named System/R.
1986 -- IBM developed the first prototype of relational database and standardized by ANSI. The first
relational database was released by Relational Software and its later becoming Oracle.
INTRODUCTION TO SQL COMMANDS
SQL commands are instructions used to communicate with the database to perform specific task that
work with data. SQL commands can be used not only for searching the database but also to perform various
other functions like, for example, you can create tables, add data to tables, or modify data, drop the table, set
permissions for users. SQL commands are grouped into four major categories depending on their
functionality:
Data Definition Language (DDL) - These SQL commands are used for creating, modifying, and
dropping the structure of database objects. The commands are CREATE, ALTER, DROP, RENAME,
and TRUNCATE.
Data Manipulation Language (DML) - These SQL commands are used for storing, retrieving,
modifying, and deleting data. These commands are SELECT, INSERT, UPDATE, and DELETE.
Transaction Control Language (TCL) - These SQL commands are used for managing changes
affecting the data. These commands are COMMIT, ROLLBACK, and SAVEPOINT.
Data Control Language (DCL) - These SQL commands are used for providing security to data
EX.NO : 01 Data Definition Commands, Data Manipulation Commands for
DATE : inserting, deleting, updating and retrieving tables
AIM
To study the database creation, Data definition commands, Data manipulation commands for inserting,
deleting ,updating and retrieving tables and Transaction Control statements from the database.
DESCRIPTION
It is used to communicate with database. It is used to:
Create an object
Select an object
Create
Select
1. CREATE:
(a)CREATE TABLE: This is used to create a new relation (table)
Example:
SQL> CREATE TABLE Student (sno NUMBER (3), sname CHAR (10), class CHAR (5));
2. ALTER:
(a) ALTER TABLE ...ADD...: This is used to add some extra fields into existing
relation.
Syntax: ALTER TABLE relation_name ADD (new field_1 data_type(size), new field_2
data_type(size),..);
(b) ALTER TABLE...MODIFY...: This is used to change the width as well as data
type of fields of existing relations.
c) ALTER TABLE..DROP .... This is used to remove any field of existing relations.
12
Example: SQL>INSERT INTO student (sno, sname,
class,address) VALUES
(&sno,’&sname’,’&class’,’&address’);
Enter value
for sno: 101
Enter value
for name:
Ravi Enter
value for
class:
M.TechEnter
value for
name:
Palakol
10 ACCOUNTING
20 RESEARCH
30 SALES
3. SELECT - FROM -WHERE: This query is used to display a selected
set of fields for aselected set of records of a relation.Syntax: SELECT a
set of fields FROM relation_name WHERE condition;
14
Example: SQL> select * FROM dept
WHERE deptno<=20;DEPTNO DNAME LOC
------ ----------- ------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
1) Numeric Functions:
Numeric functions are used to perform operations on numbers. They accept numeric values
as input and return numeric values as output. Few of the Numeric functions are:
CEIL (x) Integer value that is Greater than or equal to the number 'x'
FLOOR (x) Integer value that is Less than or equal to the number 'x'
ROUND (x, y) Rounded off value of the number 'x' up to the number 'y' decimal places
15
2) Character or Text Functions:
Character or text functions are used to manipulate text strings. They accept strings or
characters as input and can return both character and number values as output.
For Example, we can use the above UPPER() text function with the column value as follows.
3) Date Functions:
These are functions that take values that are of datatype DATE as input and return values of
datatypes DATE, except for the MONTHS_BETWEEN function, which returns a number as
output.
16
Function Name Return Value
ADD_MONTHS (date, n) Returns a date value after adding 'n' months to the date 'x'.
MONTHS_BETWEEN (x1,
Returns the number of months between dates x1 and x2.
x2)
Returns the date 'x' rounded off to the nearest century, year,
ROUND (x, date_format) month, date, hour, minute, or second as specified by the
'date_format'.
Returns the date 'x' lesser than or equal to the nearest
TRUNC (x, date_format) century, year, month, date, hour, minute, or second as
specified by the 'date_format'.
Returns the next date of the 'week_day' on or after the date
NEXT_DAY (x, week_day)
'x' occurs.
It is used to determine the number of days remaining in a
LAST_DAY (x)
month from the date 'x' specified.
SYSDATE Returns the systems current date and time.
Returns the date and time in zone2 if date 'x' represents the
NEW_TIME (x, zone1, zone2)
time in zone1.
4) Conversion Functions:
These are functions that help us to convert a value in one form to another form. For Ex: a null
value into an actual value, or a value from one datatype to another datatype like NVL,
TO_CHAR, TO_NUMBER, TO_DATE. Few of the conversion functions available in oracle
are:
TO_DATE (x [, Converts a valid Numeric and Character values to a Date value. Date is
date_format]) formatted to the format specified by 'date_format'.
NVL (x, y) If 'x' is NULL, replace it with 'y'. 'x' and 'y' must be of the same datatype.
DECODE (a, b, c, Checks the value of 'a', if a = b, then returns 'c'. If a = d, then returns 'e'.
d, e, default_value) Else, returns default_value.
Group functions are built-in SQL functions that operate on groups of rows and return
one value for the entire group. These functions are: COUNT, MAX, MIN, AVG, SUM,
DISTINCT
17
SQL COUNT (): This function returns the number of rows in the table that satisfies
the condition specified in the WHERE condition. If the WHERE condition is not specified,
then the query returns the total number of rows in the table.
TRANSACTION CONTROL LANGUAGE (TCL) - These SQL commands are used for
managing changes affecting the data. These commands are COMMIT, ROLLBACK, and
SAVEPOINT.
SYNTAX
SAVEPOINT variable;
EXAMPLE
SAVE POINT
COMMIT
SQL> commit;
SQL> delete from college where id=3;
SQL> savepoint p2;
SQL> select *from college;
ROLLBACK
Result
Thus The Above Procedure was successfully created and Executed
18
EX.NO : 02
DATE : Data Control and Transaction Control statements
Aim
To learn and Implement the Data Control Transaction Control Commands
DCL includes commands such as GRANT and REVOKE which mainly deal with the rights,
permissions, and other controls of the database system.
Syntax:
GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;
REVOKE: This command withdraws the user’s access privileges given by using the
GRANT command.
Syntax:
Query
/* Revoking privileges */
REVOKE ALTER TABLE FROM user1;
REVOKE SELECT ON employees FROM user2;
19
Transactional Control Commands
The COMMIT command is the transactional command used to save changes invoked by a
transaction. It saves all the transactions occurred on the database since the last COMMIT or
ROLLBACK.
COMMIT
QUERY
Firstly, let us create a table names CUSTOMERS using the following query −
20
ID NAME AGE ADDRESS SALARY
Following query would delete those records from the table which have AGE as 25 and then
COMMIT the changes in the database.
Verification
The two rows from the table would be deleted and if you verify the contents of the
CUSTOMERS table using the SELECT statement as −
The ROLLBACK command is the transactional command used to undo transactions that have
not already been saved to the database. This command can only undo transactions since the
last COMMIT or ROLLBACK.
21
ROLLBACK;
Example
Following query would delete those records from the table where the AGE value is 25 and
then ROLLBACK the changes in the database.
Verification
The delete operation would not impact the table and the SELECT statement would produce
the following result.
22
A SAVEPOINT is a logical rollback point in a transaction.
Usually, when you execute the ROLLBACK command, it undoes the changes until the last
COMMIT. But, if you create save points you can partially roll the transaction back to these
points. You can create multiple save points between two commits.
SAVEPOINT savepoint_name;
Then, to roll back to the SAVEPOINT created, you can use the following syntax −
ROLLBACK TO savepoint_name;
Example
Following is an example where you plan to delete the three different records from the
CUSTOMERS table. You want to create a SAVEPOINT before each delete, so that you can
ROLLBACK to any SAVEPOINT at any time to return the appropriate data to its original
state.
SAVEPOINT SP1;
Query OK, 0 rows affected (0.00 sec)
SAVEPOINT SP2;
Query OK, 0 rows affected (0.00 sec)
23
DELETE FROM CUSTOMERS WHERE ID=2;
Query OK, 0 rows affected (0.00 sec)
SAVEPOINT SP3;
Query OK, 0 rows affected (0.00 sec)
Now that the three deletions have taken place, let us assume that you have changed your
mind and decided to ROLLBACK to the SAVEPOINT that you identified as SP2. Because
SP2 was created after the first deletion, the last two deletions are undone −
ROLLBACK TO SP2;
Verification
If you display the CUSTOMERS table, you can notice that only the first deletion took place
since you rolled back to SP2.
Once a SAVEPOINT has been released, you can no longer use the ROLLBACK command to
undo transactions performed since the last SAVEPOINT.
Result
Thus The Above Procedure was successfully created and Executed
24
EX.NO : 03
DATE : Database Querying –Simple Queries,
Sub Queries and Joins
AIM:
To study and Implement the Database Querying –Simple Queries, Sub Queries and
Joins.
Sample Queries
Table1: Student1
Table2: Student2
25
INSERT INTO Student1 SELECT * FROM Student2;
Output:
To delete students from Student2 table whose rollno is same as that in Student1 table and
having location as Chennai.
DELETE FROM Student2 WHERE ROLL_NO IN ( SELECT ROLL_NO FROM Student1
WHERE LOCATION = ’chennai’);
Output:
Output:
In SQL a Subquery can be simply defined as a query within another query. In other words we
can say that a Subquery is a query that is embedded in WHERE clause of another SQL query.
26
Important rules for Subqueries:
You can place the Subquery in a number of SQL clauses: WHERE clause, HAVING
clause, FROM clause.
Subqueries can be used with SELECT, UPDATE, INSERT, DELETE statements
along with expression operator. It could be equality operator or comparison operator
such as =, >, =, <= and Like operator.
A subquery is a query within another query. The outer query is called as main query
and inner query is called as subquery.
The subquery generally executes first, and its output is used to complete the query
condition for the main or outer query.
Subquery must be enclosed in parentheses.
Subqueries are on the right side of the comparison operator.
ORDER BY command cannot be used in a Subquery. GROUPBY command can be
used to perform same function as ORDER BY command.
Use single-row operators with singlerow Subqueries. Use multiple-row operators with
multiple-row Subqueries.
Syntax:
There is not any general syntax for Subqueries. However, Subqueries are seen to be used
most frequently with SELECT statement as shown below:
SELECT column_name
FROM table_name
WHERE column_name expression operator
( SELECT COLUMN_NAME from TABLE_NAME WHERE ... );
Sample Table:
DATABASE
STUDENT
Types of Joins
1. Simple Join
2. Self Join
3. Outer Join
27
Simple Join
It is the most common type of join. It retrieves the rows from 2 tables having a common
column and is further classified into
a) Equi-join
b) Non Equi-join
It specifies the relationship between columns belonging to different tables by making use of
relational operators other than’=’.
Table Aliases
Table aliases are used to make multiple table queries shorted and more readable. We give an
alias name to the table in the ‘from’ clause and use it instead of the name throughout the
query.
Self join
Joining of a table to itself is known as self-join. It joins one row in a table to another. It can
compare each row of the table to itself and also with other rows of the same table.
Outer Join
It extends the result of a simple join. An outer join returns all the rows returned by simple
join as well as those rows from one table that do not match any row from the table. The
symbol(+) reprsents outer join.
1) SIMPLE JOIN
create table1 with rollno, name, create table2 with rollno, marks
a) Equi-Join
b) Non Equi-Join
28
SQL> SELECT * FROM table1,table2
2 WHERE table1.rollno>=table2.rollno;
2) SELF JOIN
3) INNER JOIN
4) NATURAL JOIN
5) CROSS JOIN
6) OUTER JOIN
Result
Thus The Above Procedure was successfully created and Executed
29
EX.NO : 04 Integrity Constraints
DATE :
Aim
To study and Implement the Integrity Constraints
INTEGRITY CONSTRAINTS
Description: Constraints are used to limit the type of data that can go into a table. Such
constraints can be specified when the table is first created via the CREATE TABLE
statement, or after the table is already created via the ALTER TABLE statement.
Constraints are grouped into 3 categories
1. Domain Integrity constraints
Constraints imposed on column. Types of constraints comes under this is
a) Not Null Constraint: Ensures that a column cannot have NULL value.
b) Default Constraint: Provides a default value for a column when none is
specified.
c) Check Constraint: Makes sure that all values in a column satisfy certain
criteria.
2. Entity integrity constraints
Constraints imposed on each row. Types of constraints comes under this is
d) Unique Constraint: Ensures that all values in a column are different.
e) Primary key Constraint: Used to uniquely identify a row in the table.
Syntax:
Create table <tablename>(col1 datatype [constraint constname] not null, col2 datatype, ….)
30
Note: Modify Clause of alter statement is used to set the Not Null constraint and the table
must be empty.
Syntax:
alter table <table name> modify <column name > [constraint constname] not null
b) DEFAULT CONSTRAINT
Description: DEFAULT constraint provides a default value to a column when the INSERT
INTO statement does not provide a specific value.
Create table <table name> (col1 datatype default value, col2 datatype,….)
c) CHECK CONSTRAINT
Description: constraint validates incoming columns at row insertion time.
During table creation
Syntax:
create table <table name> (col1 datatype [constraint constname ] check {condition}, col2
datatype,…)
Syntax:
a) UNIQUE CONSTRAINT
Description: The UNIQUE constraint ensures that all values in a column are distinct. Null
value is accepted.
31
Syntax:
create table <tablename>(col1 datatype [constraint cname] unique, col2 datatype,………);
Description
A primary key is used to uniquely identify each row in a table. It can either be part of
the actual record itself, or it can be an artificial field (one that has nothing to do with the
actual record). A primary key can consist of one or more fields on a table. When multiple
fields are used as a primary key, they are called a composite key.
None of the fields that are part of the primary key can contain a null value. A table
can have only one primary key. Primary keys can be specified either when the table is created
(using CREATE TABLE) or by changing the existing table structure (using ALTER
TABLE).
Syntax:
alter table <tablename >add [constraint cname] primary key (column1, column2, …);
A foreign key is a field (or fields) that points to the primary key of another table. The
purpose of the foreign key is to ensure referential integrity of the data. In other words, only
values that are supposed to appear in the database are permitted.
For example, say we have two tables, a CUSTOMER table that includes all customer
data, and an ORDERS table that includes all customer orders. The constraint here is that all
orders must be associated with a customer that is already in the CUSTOMER table. In this
case, we will place a foreign key on the ORDERS table and have it relate to the primary key
of the CUSTOMER table. This way, we can ensure that all orders in the ORDERS table are
related to a customer in the CUSTOMER table. In other words, the ORDERS table cannot
contain information on a customer that is not in the CUSTOMER table.
In the above example, the C_SID column in the ORDERS table is a foreign key pointing to
the CID column in the CUSTOMER table.
Syntax 1:
create table <tablename> (col1 datatype [constraint cname] primary key, col2 datatype, …,
col_i [constraint fk_cname references <parenttablename>(col1)
Syntax 2:
create table<tablename>(col1 datatype ,col2 datatype ,... col_i [constraint fk_column]
foreign key (column1, column2, ...) references <parenttablename> (column1, column2, ...));
Problem 4.1: Create a table called EMP with the following structure.
Name Type
EMPNO NUMBER(6)
ENAME VARCHAR2(20)
JOB VARCHAR2(10)
MGR NUMBER(4)
DEPTNO NUMBER(3)
SAL NUMBER(7,2)
Allow NULL for all columns except ename and job.
Problem 4.2: Add a column commission to the emp table Commission numeric null allowed.
Problem 4.3: Modify the column width of the job field of emp table.
Name Type
-----------------------------------------------------------------
DEPTNO NUMBER(2)
DNAME VARCHAR2(10)
LOC VARCHAR2(10)
33
Deptno as the primarykey
Problem 4.5: Add constraints to the emp table that empno as the primary key and deptno
as the foreign key.
Problem 4.6: Add constraints to the emp table to check the empno value while entering
(i.e) empno > 100.
Problem 4.7: Salary value by default is 5000, otherwise as entered values
Problem 4.8: Add columns Dob to the emp table.
Problem 4.9: Add and drop a column DOJ to the emp table.
Problem 4.10: Insert few rows and truncate those from the emp1 table and also drop
it.(pseudo table)
Result
Thus The Above Procedure was successfully created and Executed
34
EX.NO : 05 Creation of Views, Synonyms, Sequence
DATE :
AIM:
To Study and implement the Creation of Views, Synonyms, Sequence, Indexes and Save
point.
Views:
A view is the tailored presentation of data contained in one or more table and can also
be said as restricted view to the datas in the tables. A view is a “virtual table” or a “stored
query” which takes the output of a query and treats it as a table. The table upon which a view
is created is called as base table.
A view is a logical table based on a table or another view. A view contains no data of
its own but is like a window through which data from tables can be viewed or changed. The
tables on which a view is based are called base tables. The view is stored as a SELECT
statement in the data dictionary
Advantages of a view:
Syntax:
Create [or replace ] view <view name> [column alis names] as <query> [with <options>
conditions];
Types of view:
Problem 3.1: The organization wants to display only the details of the employees those who
are managers.( horizontal portioning)
Problem 3.2: The organization wants to display only the details like
empno,empname,deptno,deptname of the employees.(vertical portioning)
Problem 3.3: The organization wants to display only the details like empno, empname,
deptno, deptname of the all the employees except the HOD and CEO. (full portioning)
Type of index
Simple index
A simple index on column.
>create index sid on emp(empno);
Composite index
An index created on more than one column of table.
>create index cid on emp(empno,ename);
Unique index
An index with unique constraint it will not allow duplicate values.
>create unique index uid on dept(dname)
B-tree index
B tree index are normally used OLTP Environment.(Dynamic)
Descending index
This is created on columns which are displayed in sorted order.
>create index dixd on emp(ename asc, sal desc);
SEQUENCE
o Sequence is a DB object that can generate unique sequential value (serial Number).
o Its automatic creates sequence.
o Sequence value is often used for PRIMARY KEY’s & UNIQUE KEY’s.
o When sequence is created, we can define its initial value and the increment between its
value..
o The maximum value generated by the sequence is 38 digits.
o To generate starting value sequence NEXTVAL should be used.
36
>create sequence (seq_name)
[Increment by n
Start with n
Max value n/NOMAXVALUE
Min value n/NOMINVALUE
Cycle/Nocycle
Cache/Nocache
Order/No order];
Increment by
Specify the interval between the sequence numbers.
Value can be positive or negative but can’t be zero.
If the value is POSITIVE it is INCREMENT SEQUENCE.
If the value is NEGATIVE it is DECREMENT SEQUENCE.
Default increment is 1.
Start with n
Specify the starting value of sequence.
Default value is 1.
Min value
Specify the min value of sequence.
No min value
Specify a minimum value of 1 for ascending sequence.
-1026 for descending sequence.
Max value
Specify the max value of sequence.
No max value
Specify the maximum value of 1027 for ascending sequence.
-1 for descending sequence.
Cycle
Specify the sequence will continue to generate value after reaching either maximum or
minimum value.
No cycle
Specify sequence can’t generate value after reaching max or min value.
Default is NO CYCLE.
Cache
Cache is a buffer.
It specifies the No. of integer to keep in memory.
Default cache is 20.
Minimum cache is 2.
Order
This guarantees that sequence Numbers are generated in the order of request.
No order
This does not guarantee that sequence Numbers are generated in the order of request.
37
Alter is available in sequence.
The START WITH OPTION can’t be changed using ALTER SEQUENCE.
To change START WITH OPTION, drop the SEQUENCE and then recreate the sequence.
A synonym is an alternative name for objects such as tables, views, sequences, stored
procedures, and other database objects.
We can avoid the entry of SCHEMA.
DML operation performed on synonym will affect the table.
The main functionality of synonym is to access the database objects between different schemas
without using the schema names.
Types of Synonyms
The PL/SQL programming language was developed by Oracle Corporation in the late 1980s
as procedural extension language for SQL and the Oracle relational database. Following are
notable facts about PL/SQL:
Features of PL/SQL
Advantages of PL/SQL
38
SQL is the standard database language and PL/SQL is strongly integrated with SQL.
PL/SQL supports both static and dynamic SQL. Static SQL supports DML operations
and transaction control from PL/SQL block. Dynamic SQL is SQL allows embedding
DDL statements in PL/SQL blocks.
PL/SQL allows sending an entire block of statements to the database at one time. This
reduces network traffic and provides high performance for the applications.
PL/SQL provides high security level.
Basic Syntax
PL/SQL is a block-structured language, meaning that PL/SQL programs are divided and
written in logical blocks of code. Each block consists of three sub-parts:
Declarations
This section starts with the keyword DECLARE. It is an optional section and defines all
variables, cursors, subprograms, and other elements to be used in the program.
Executable Commands
This section is enclosed between the keywords BEGIN and END and it is a mandatory
section. It consists of the executable PL/SQL statements of the program. It should have at
least one executable line of code, which may be just a NULL command to indicate that
nothing should be executed.
Exception Handling
This section starts with the keyword EXCEPTION. This section is again optional and
contains exception(s) that handle errors in the program.
Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested within
other PL/SQL blocks using BEGIN and END. Here is the basic structure of a PL/SQL block:
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;
Data Types
PL/SQL - Operators
Arithmetic operators
Relational operators
Comparison operators
Logical operators
String operators
Result
Thus The Above Procedure was successfully created and Executed
40
EX.NO : 06 Database Programming Implicit and Explicit
DATE :
cursors
AIM:
To study the database Programming PL/SQL using implicit and explicit cursors.
a. Implicit Cursors
Program
DECLARE
total_rows number(2);
BEGIN
UPDATE customers SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
/
Output
6 customers selected
PL/SQL procedure successfully completed.
b. Explicit Cursors
Program
DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END; /
Output
1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP
Result
Thus The Above Procedure was successfully created and Executed
42
EX.NO : 07 Procedures and Functions
DATE :
AIM:
To Study the creation of procedures and functions.
Description
A procedure is a block that can take parameters (sometimes referred to as arguments) and be
invoked.
Procedures promote reusability and maintainability. Once validated, they can be used in
number of applications. If the definition changes, only the procedure are affected, this greatly
simplifies maintenance.
· Break down a complex problem into a set of manageable well defined logical
modules and implement the modules with blocks.
Function:
- Returns a value
- FUNCTION name RETURN data-type IS
Program 5.1:
Write a procedure to add an amount of Rs.1000 for the employees whose salaries is greater
than 5000 and who belongs to the deptno passed as an argument .
Program 5.2:
Write a PL/SQL block to update the salary of the employee with a 10% increase whose
empno is to be passed as an argument for the procedure.
Program 5.3:
Write a function to find the salary of the employee who is working in the deptno 20(to be
passed as an argument).
43
FUNCTION
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.
1) 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.
2) The execution and exception section both should return a value which is of the datatype
defined in the header section.
For example, let’s create a frunction called ''employer_details_func' similar to the one created
in stored proc
In the example we are retrieving the ‘first_name’ of employee with empID 100 to variable
‘emp_name’.
The return type of the function is VARCHAR which is declared in line no 2.
The function returns the 'emp_name' which is of type VARCHAR as the return value in line
no 9.
44
employee_name := employer_details_func;
dbms_output.put_line(employer_details_func);
This line displays the value returned by the function.
Result
Thus The Above Procedure was successfully created and Executed
45
EX.NO : 08 Triggers
DATE :
AIM
To study and implement the concept of triggers
DEFINITION
TYPES OF TRIGGERS
46
SYNTAX
Program 6.2: Write a Trigger to carry out the following action: on deleting a deptno from
dept table , all the records with that deptno has to be deleted from the emp table
Program 6.3: Write a Trigger to carry out the following action: on deleting any records from
the emp table ,the same values must be inserted into the log table.
Result
Thus The Above Procedure was successfully created and Executed
47
EX.NO : 09 Exception Handling
DATE :
AIM:
To Study the PL/SQL block that handles all types of exceptions.
System-defined exceptions
User-defined exceptions
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
........
WHEN others THEN
exception3-handling-statements
END;
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. Following is the simple syntax of raising an exception:
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
48
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.
DECLARE
my-exception EXCEPTION;
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:
Oracle
Exception SQLCODE Description
Error
It is raised when a null object is
ACCESS_INTO_NULL 06530 -6530
automatically assigned a value.
It is raised when none of the choices in the
CASE_NOT_FOUND 06592 -6592 WHEN clauses of a CASE statement is
selected, and there is no ELSE clause.
It is raised when a program attempts to
apply collection methods other than
EXISTS to an uninitialized nested table or
COLLECTION_IS_NULL 06531 -6531
varray, or the program attempts to assign
values to the elements of an uninitialized
nested table or varray.
It is raised when duplicate values are
DUP_VAL_ON_INDEX 00001 -1 attempted to be stored in a column with
unique index.
It is raised when attempts are made to
make a cursor operation that is not
INVALID_CURSOR 01001 -1001
allowed, such as closing an unopened
cursor.
It is raised when the conversion of a
character string into a number fails because
INVALID_NUMBER 01722 -1722
the string does not represent a valid
number.
It is raised when s program attempts to log
LOGIN_DENIED 01017 -1017 on to the database with an invalid
username or password.
It is raised when a SELECT INTO
NO_DATA_FOUND 01403 +100
statement returns no rows.
49
It is raised when a database call is issued
NOT_LOGGED_ON 01012 -1012
without being connected to the database.
It is raised when PL/SQL has an internal
PROGRAM_ERROR 06501 -6501
problem.
Result
Thus The Above Procedure was successfully created and Executed
50
EX.NO : 10 Mini project (application development using
DATE : oracle)
The stock inventory control system is the systematic recording of all the transactions that take
place during the purchase of goods. Previously, all these details were entered manually. So it
was difficult to refer to all the transaction information later. In order to overcome these
difficulties a computerized form to record the transactions is necessary. Thus the stock
inventory control system is designed and implemented. The stock inventory control system
will interface with the purchasing, customer order entry, ordering for goods, purchasing
register, customer details, pay money, damage, exchange, invoice, sales register and database.
51
SQL> create table sales1(cid1 varchar(10)references custable1(cid),cname1 varchar(15),ino1
number(10),iname1 varchar(20),quantity1 number(5),price1 number(10,2));
Table created.
Step 2: Goto control panel , administrative tools , data asource(ODBC) and create a new
ODBC driver for oracle by selecting Microsoft ODBC for oracle.
Step 3: Create a visual basic project, design the form and type the following code
Module 1:
Global con As New ADODB.Connection
Global rs1 As New ADODB.Recordset
Global rs2 As New ADODB.Recordset
Global rs3 As New ADODB.Recordset
52
Private Sub Label3_Click()
End
End Sub
53
Private Sub Command1_Click() ‘Clear
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text4.Text = ""
End Sub
54
rs2(0) = Text1.Text
rs2(1) = Text2.Text
rs2(2) = Text3.Text
rs2(3) = Text4.Text
rs2.Save
MsgBox "Record Saved successfully..."
End Sub
56
Private Sub Combo1_Click() ‘fetch cname from custable1
rs1.MoveFirst
Do While Not rs1.EOF
If Trim(Combo1.Text) = Trim(rs1(0)) Then Exit Do
rs1.MoveNext
Loop
Text2.Text = rs1(1) ‘cusname
End Sub
End If
End Sub
End Sub
TRAIN TABLE:
SQL> create table train(tno number(6) primary key,tname varchar2(20),source
varchar2(15),destination
varchar2(15),departure varchar2(10),reach varchar2(10));
COACH TABLE:
SQL> create table coach(tno number(6) references train(tno),fcoach varchar2(4),fseat
number(3),favai
l number(3),ffare number(4),scoach varchar2(4),sseat number(3),savail number(3),sfare
number(4));
RESERVE TABLE:
SQL> create table reserve(pname varchar2(30),pnr number(10) primary key,tno number(6)
references train(tno),age number(3),gender varchar2(6),jdate date,class varchar2(25),source
varchar2(25),destination varchar2(25),coach varchar2(5),seat number(3),fare number(4));
MODULE1:
Public con As New ADODB.Connection
Public rs1 As New ADODB.Recordset
Public rs2 As New ADODB.Recordset
Public rs3 As New ADODB.Recordset
Sub Main()
con.Open "manoj", "mc037", "manoj"
rs1.Open "train", con, 1, 3
rs2.Open "coach", con, 1, 3
rs3.Open "reserve", con, 1, 3
Form1.Show
End Sub
59
FORM1:
60
FORM2:
61
Private Sub Form_Load()
rs1.MoveFirst
rs2.MoveFirst
'' rs3.MoveFirst
Combo1.AddItem "MADURAI"
Combo2.AddItem "CHENNAI"
End Sub
FORM3:
MsgBox rs3(1)
Me.Text4.Text = rs3(1)
rs3(6) = Option4.Caption
rs3(9) = rs2(5)
rs3(10) = rs2(6) - rs2(7)
rs3(11) = rs2(8)
''rs2.Update
Exit Do
End If
End If
rs2.MoveNext
Loop Until rs2.EOF
rs3.Update
rs2.Update
'' pnr = rs3(3)
End Sub
FORM 4:
DATAENVIRONMENT1:
DATAENVIRONMENT1->PROPERTIES->MICROSOFT OLE DB FOR ODBC DRIVER-
>NEXT
Select DSN name, UserName, Password, Test Connection.
DATAENVIRONMENT1->ADDCOMMAND.
COMMAND1->PROPERTIES->SQL statement, type
“select * from reserve where pnr=?”
->Apply
In Parameters tab,
Select DataType as “adInteger”,
Host DataType as “Integer”.
->Apply->OK.
DATAREPORT1:
Drag the command1 from dataenvironment1 and drop it in “detail” section of datareport1.
Set DataSource property as DataEnvironment1,
Set DataMember Property as Command1.
Result
Thus The above Mini project was successfully created and Executed
65
Case Study using real life database Application
Try to identify the different entities , normalize the data , draw the ER Diagram , design the
Data base by using back end tool and build an application in front end.
VIVA QUESTIONS
1. What is database?
A database is a collection of information that is organized so that it can be easily
accessed, managed and updated.
2. 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.
3. What is RDBMS ?
Relational Database Management system (RDBMS) is a database management
system (DBMS) that is based on the relational model. Data from relational database
can be accessed or reassembled in many different ways without having to reorganize
the database tables. Data from relational database can be accessed using an API ,
Structured Query Language (SQL).
66
7. Explain the difference between DELETE , TRUNCATE and DROP commands?
Once delete operation is performed, Commit and Rollback can be performed to
retrieve data.
Once the truncate statement is executed, Commit and Rollback statement cannot be
performed. Where condition can be used along with delete statement but it can't be
used with truncate statement.
Drop command is used to drop the table or keys like primary,foreign from a table.
8. What is a Database system?
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.
13. What is the difference between primary key and unique constraints?
Behavior: Primary Key is used to identify a row (record) in a table, whereas Unique-
key is to prevent duplicate values in a column (with the exception of a null entry).
Indexing: By default SQL-engine creates Clustered Index on primary-key if not
exists and Non-Clustered Index onUnique-key.
16. What are the differences between DDL, DML and DCL in SQL?.
DDL stands for Data Definition Language. SQL queries like CREATE, ALTER,
DROP and RENAME come under this.
DML stands for Data Manipulation Language. SQL queries like SELECT, INSERT
and UPDATE come under this.
DCL stands for Data Control Language. SQL queries like GRANT and REVOKE
come under this.
68
A sequence is a set of integers 1, 2, 3, ... that are generated in order on demand.
Sequences are frequently used in databases because many applications require each
row in a table to contain a unique value, and sequences provide an easy way to
generate them.
Every record has a key field, which helps it to be recognized uniquely. Indexing is a
data structure technique to efficiently retrieve records from the database files based on
some attributes on which the indexing has been done.
A synonym is an alias or alternate name for a table, view, sequence, or other schema
object. They are used mainly to make it easy for users to access database objects
owned by other users.
----------------------------------------------------------------------
69