0% found this document useful (0 votes)
94 views69 pages

22cs4001 Dbms Lab Manual

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

22cs4001 Dbms Lab Manual

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

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

22CS4001 – DATABASE MANAGEMENT


LABORATORY

LAB MANUALS

II YEAR / IV SEMESTER – EVEN SEM


HINDUSTHAN COLLEGE OF ENGINEERING
DEPARTMENT OF CSE
VISION

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.

PROGRAM EDUCATIONAL OBJECTIVES


PEO1: To acquire knowledge in the latest technologies and innovations and an ability to identify, analyze,
and solve problems in Computer Engineering.

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.

PROGRAM SPECIFIC OBJECTIVES


PSO1: Ability to apply, design, and develop principles of software engineering, networking, and database
concepts for computer-based systems in solving engineering problems.

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

1 To understand data definitions and data manipulation commands.

2 To learn the use of nested and join queries

3 To understand views and constraints

4 To understand functions, procedures and procedural extensions of data bases

5 To understand design and implementation of typical database applications

COURSE OUTCOMES

S.NO DESCRIPTION

1 Use typical data definitions and manipulation commands

2 Design applications to test Nested and Join Queries

3 Implement simple applications that use Views

4 Critically analyze the use of Tables, Views, Functions and Procedures

5 Implement applications that require a Front-end Tool


COGNITIVE LEVEL ATTAINMENT

LAB COURSE COGNITIVE


EX. NO. EXP. NAME
SESSIONS OUTCOMES LEVEL

Data Definition Commands, Data


1 Manipulation Commands for inserting, 3 CO1 Applying
deleting, updating and retrieving Tables

Data Control and Transaction Control


2 statements 3 CO1 Creating

Database Querying – Simple queries,


3 Nested queries, Sub queries and Joins 3 CO2 Applying

Integrity Constraints
4 3 Analyzing

5 Views, Sequences, Synonyms 3 CO3 Applying

Database Programming: Implicit and


6 5 CO5 Remembering
Explicit Cursors

7 Procedures and Functions 5 CO5 Creating

8 Triggers 5 CO5 Understand

9 Exception Handling 5 CO1,CO5 Evaluating

Development of mini-projects with


CO1,CO2,CO3,
10 front end of your choice. 10 Creating
CO4,CO5
LIST OF EXPERIMENTS

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

LIST OF EQUIPMENT FOR A BATCH OF 30 STUDENTS


HARDWARE:
Standalone desktops 30 Nos. (or) Server supporting 30 terminals or more 42

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.

Also, they are using different dialects, such as:

 MS SQL Server using T-SQL,


 Oracle using PL/SQL,
 MS Access version of SQL is called JET SQL (native format) etc.

Why SQL?

 Allows users to access data in relational database management systems.


 Allows users to describe the data.
 Allows users to define the data in database and manipulate that data.
 Allows to embed within other languages using SQL modules, libraries & pre-compilers.
 Allows users to create and drop databases and tables.
 Allows users to create view, stored procedure, functions in a database.
 Allows users to set permissions on tables, procedures, and views

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

The commands used are:

 Create
 Select

1. DATA DEFINITION LANGUAGE (DDL): The Data Definition Language (DDL) is


used to create and destroy databases and database objects. These commands will primarily be
used by database administrators during the setup and removal phases of a database project.
Let's take a look at the structure and usage of four basic DDL commands:
1. CREATE 2. ALTER 3. DROP 4. RENAME

1. CREATE:
(a)CREATE TABLE: This is used to create a new relation (table)

Syntax: CREATE TABLE <relation_name/table_name >


(field_1 data_type(size),field_2 data_type(size), .. . );

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),..);

Example: SQL>ALTER TABLE std ADD (Address CHAR(10));

(b) ALTER TABLE...MODIFY...: This is used to change the width as well as data
type of fields of existing relations.

Syntax: ALTER TABLE relation_name MODIFY (field_1 newdata_type(Size), field_2


newdata_type(Size),... field_newdata_type(Size));

Example:SQL>ALTER TABLE student MODIFY(sname VARCHAR(10),class


VARCHAR(5));

c) ALTER TABLE..DROP .... This is used to remove any field of existing relations.

Syntax: ALTER TABLE relation_name DROP COLUMN (field_name);

Example:SQL>ALTER TABLE student DROP column (sname);

d) ALTER TABLE..RENAME...: This is used to change the name of fields in


existing relations.

Syntax: ALTER TABLE relation_name RENAME COLUMN (OLD field_name) to


(NEW field_name);

Example: SQL>ALTER TABLE student RENAME COLUMN sname to stu_name;


3. DROP TABLE: This is used to delete the structure of a relation. It permanently deletes
the records in the table.
Syntax: DROP TABLE relation_name;
Example: SQL>DROP TABLE std;

4. RENAME: It is used to modify the name of the existing database object.


Syntax: RENAME TABLE old_relation_name TO new_relation_name;
Example: SQL>RENAME TABLE std TO std1;

LAB PRACTICE ASSIGNMENT:

1. Create a table EMPLOYEE with following schema:

(Emp_no, E_name, E_address, E_ph_no, Dept_no, Dept_name,Job_id , Salary)


2. Add a new column; HIREDATE to the existing relation.
3. Change the datatype of JOB_ID from char to varchar2.
4. Change the name of column/field Emp_no to E_no.
5. Modify the column width of the job field of emp table
DATA MANIPULATION LANGUAGE (DML): The Data Manipulation
Language (DML) is used to retrieve, insert and modify database information.
These commands will be used by all database users during the routine
operation of the database. Let's take a brief look at the basic DML
commands:

1. INSERT 2. UPDATE 3. DELETE


1. INSERT INTO: This is used to add records into a relation. These
are three type ofINSERT INTO queries which are as
a) Inserting a single record
Syntax: INSERT INTO < relation/table name>
(field_1,field_2……field_n)VALUES (data_1,data_2,
............................... data_n);

Example: SQL>INSERT INTO


student(sno,sname,class,address)VALUES
(1,’Ravi’,’M.Tech’,’Palakol’);

b) Inserting a single record


Syntax: INSERT INTO < relation/table name>VALUES (data_1,data_2,
........................................................................................................................ data_
n);
Example: SQL>INSERT INTO student VALUES (1,’Ravi’,’M.Tech’,’Palakol’);

c) Inserting all records from another relation


Syntax: INSERT INTO relation_name_1 SELECT
Field_1,field_2,field_nFROM relation_name_2
WHERE field_x=data;

Example: SQL>INSERT INTO std SELECT sno,sname


FROM student WHERE name = ‘Ramu‘;

d) Inserting multiple records


Syntax: INSERT INTO relation_name field_1,field_2, .... field_n) VALUES
(&data_1,&data_2, ...... &data_n);

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

2. UPDATE-SET-WHERE: This is used to update the content of a record in a


relation.
Syntax: SQL>UPDATE relation name SET
Field_name1=data,field_name2=data, WHERE field_name=data;

Example: SQL>UPDATE student SET sname = ‘kumar’ WHERE sno=1;

3. DELETE-FROM: This is used to delete all the records of a relation but


it will retain thestructure of that relation.
a) DELETE-FROM: This is used to delete all the records of relation.
Syntax: SQL>DELETE FROM relation_name;
Example: SQL>DELETE FROM std;
b) DELETE -FROM-WHERE: This is used to delete a selected record from a
relation.
Syntax: SQL>DELETE FROM relation_name WHERE condition;
Example: SQL>DELETE FROM student WHERE sno = 2;

5. TRUNCATE: This command will remove the data permanently. But


structure will not beremoved.

Difference between Truncate & Delete:-


 By using truncate command data will be removed permanently & will
not get back where as by using delete command data will be removed
temporally & get back by using roll back command.
13
 By using delete command data will be removed based on the
condition where as by using truncate command there is no condition.
 Truncate is a DDL command & delete is a DML command.

Syntax: TRUNCATE TABLE <Table name>


Example TRUNCATE TABLE student;

 To Retrieve data from one or more tables.

1. SELECT FROM: To display all


fields for all records. Syntax :
SELECT * FROM relation_name;
Example : SQL> select * from dept;
DEPTNO DNAME LOC
-------- ----------- ----------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

2. SELECT FROM: To display a set of fields for all


records of relation. Syntax: SELECT a set of
fields FROM relation_name; Example: SQL> select
deptno, dname from dept;
DEPTNO DNAME

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

LAB PRACTICE ASSIGNMENT:

Create a table EMPLOYEE with following schema:


(Emp_no, E_name, E_address, E_ph_no, Dept_no, Dept_name,Job_id , Salary)

Write SQL queries for following question:


1. Insert aleast 5 rows in the table.
2. Display all the information of EMP table.
3. Display the record of each employee who works in department D10.
4. Update the city of Emp_no-12 with current city as Nagpur.
5. Display the details of Employee who works in department MECH.
6. Delete the email_id of employee James.
7. Display the complete record of employees working in SALES Department.

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:

Function Name Return Value

ABS (x) Absolute value of the number 'x'

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'

TRUNC (x, y) Truncates value of number 'x' up to 'y' decimal places

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.

Few of the character or text functions are as given below:

Function Name Return Value


LOWER (string_value) All the letters in 'string_value' is converted to lowercase.
UPPER (string_value) All the letters in 'string_value' is converted to uppercase.
All the letters in 'string_value' is converted to mixed
INITCAP (string_value)
case.
All occurrences of 'trim_text' is removed from the left of
LTRIM (string_value, trim_text)
'string_value'.

All occurrences of 'trim_text' is removed from the right


RTRIM (string_value, trim_text)
of 'string_value' .

All occurrences of 'trim_text' from the left and right of


TRIM (trim_text FROM
'string_value' , 'trim_text' can also be only one character
string_value)
long .

Returns 'n' number of characters from 'string_value'


SUBSTR (string_value, m, n)
starting from the 'm' position.

LENGTH (string_value) Number of characters in 'string_value' in returned.

LPAD (string_value, n, Returns 'string_value' left-padded with 'pad_value' . The


pad_value) length of the whole string will be of 'n' characters.

RPAD (string_value, n, Returns 'string_value' right-padded with 'pad_value' .


pad_value) The length of the whole string will be of 'n' characters.

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.

Few date functions are as given below.

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:

Function Name Return Value

Converts Numeric and Date values to a character string value. It cannot


TO_CHAR (x [,y])
be used for calculations since it is a string value.

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.

SQL GROUP Functions

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.

SQL DISTINCT(): This function is used to select the distinct rows.


SQL MAX(): This function is used to get the maximum value from a column.
SQL MIN(): This function is used to get the minimum value from a column.
SQL AVG(): This function is used to get the average value of a numeric column.
SQL SUM(): This function is used to get the sum of a numeric column

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

SQL> create table college(id number(3),name varchar2(7),dept varchar2(3));


SQL> insert into college values(3,'b','cse');

SAVE POINT

SQL> savepoint p1;

COMMIT

SQL> commit;
SQL> delete from college where id=3;
SQL> savepoint p2;
SQL> select *from college;

ROLLBACK

SQL> roll back p1;


Rollback complete.
SQL> select *from college;
ID NAME DEP
---------- ------- ---
3 b cse

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

Procedure and Query

DCL (Data Control Language)

DCL includes commands such as GRANT and REVOKE which mainly deal with the rights,
permissions, and other controls of the database system.

List of DCL commands:

GRANT: This command gives users access privileges to the database.

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:

REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;

Query

/* Granting system privileges */


GRANT CREATE TABLE, ALTER TABLE TO user1;

/* Granting object privileges */


GRANT SELECT, UPDATE ON employees TO user2;

/* Revoking privileges */
REVOKE ALTER TABLE FROM user1;
REVOKE SELECT ON employees FROM user2;

19
Transactional Control Commands

 COMMIT − to save the changes.


 ROLLBACK − to roll back the changes.
 SAVEPOINT − creates points within the groups of transactions in which to
ROLLBACK.

The COMMIT Command

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.

The syntax for the COMMIT command is as follows.

COMMIT

QUERY

Firstly, let us create a table names CUSTOMERS using the following query −

CREATE TABLE CUSTOMERS (


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);

We are inserting some records into the above-created table −

INSERT INTO CUSTOMERS VALUES


(1, 'Ramesh', 32, 'Ahmedabad', 2000.00),
(2, 'Khilan', 25, 'Delhi', 1500.00),
(3, 'Kaushik', 23, 'Kota', 2000.00),
(4, 'Chaitali', 25, 'Mumbai', 6500.00),
(5, 'Hardik', 27, 'Bhopal', 8500.00),
(6, 'Komal', 22, 'Hyderabad', 4500.00),
(7, 'Muffy', 24, 'Indore', 10000.00);

The table will be created as follows –

20
ID NAME AGE ADDRESS SALARY

1 Ramesh 32 Ahmedabad 2000.00

2 Khilan 25 Delhi 1500.00

3 Kaushik 23 Kota 2000.00

4 Chaitali 25 Mumbai 6500.00

5 Hardik 27 Bhopal 8500.00

6 Komal 22 Hyderabad 4500.00

7 Muffy 24 Indore 10000.00

Following query would delete those records from the table which have AGE as 25 and then
COMMIT the changes in the database.

DELETE FROM CUSTOMERS WHERE AGE = 25;


COMMIT;

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 −

SELECT * FROM CUSTOMERS;

The table will be displayed as follows −

ID NAME AGE ADDRESS SALARY

1 Ramesh 32 Ahmedabad 2000.00

3 Kaushik 23 Kota 2000.00

5 Hardik 27 Bhopal 8500.00

6 Komal 22 Hyderabad 4500.00

7 Muffy 24 Indore 10000.00

The ROLLBACK Command

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.

The syntax for a ROLLBACK command is as follows −

21
ROLLBACK;

Example

Consider the CUSTOMERS table having the following records −

ID NAME AGE ADDRESS SALARY

1 Ramesh 32 Ahmedabad 2000.00

2 Khilan 25 Delhi 1500.00

3 Kaushik 23 Kota 2000.00

4 Chaitali 25 Mumbai 6500.00

5 Hardik 27 Bhopal 8500.00

6 Komal 22 Hyderabad 4500.00

7 Muffy 24 Indore 10000.00

Following query would delete those records from the table where the AGE value is 25 and
then ROLLBACK the changes in the database.

DELETE FROM CUSTOMERS WHERE AGE = 25;


ROLLBACK;

Verification

The delete operation would not impact the table and the SELECT statement would produce
the following result.

ID NAME AGE ADDRESS SALARY

1 Ramesh 32 Ahmedabad 2000.00

2 Khilan 25 Delhi 1500.00

3 Kaushik 23 Kota 2000.00

4 Chaitali 25 Mumbai 6500.00

5 Hardik 27 Bhopal 8500.00

6 Komal 22 Hyderabad 4500.00

7 Muffy 24 Indore 10000.00

The SAVEPOINT Command

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.

The syntax to create a SAVEPOINT among the transactions is as shown below.

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.

Consider the CUSTOMERS table having the following records.

ID NAME AGE ADDRESS SALARY

1 Ramesh 32 Ahmedabad 2000.00

2 Khilan 25 Delhi 1500.00

3 Kaushik 23 Kota 2000.00

4 Chaitali 25 Mumbai 6500.00

5 Hardik 27 Bhopal 8500.00

6 Komal 22 Hyderabad 4500.00

7 Muffy 24 Indore 10000.00

The following code block contains the series of operations.

SAVEPOINT SP1;
Query OK, 0 rows affected (0.00 sec)

DELETE FROM CUSTOMERS WHERE ID=1;


Query OK, 1 row affected (0.01 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)

DELETE FROM CUSTOMERS WHERE ID=3;


Query OK, 1 row affected (0.01 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.

ID NAME AGE ADDRESS SALARY

2 Khilan 25 Delhi 1500.00

3 Kaushik 23 Kota 2000.00

4 Chaitali 25 Mumbai 6500.00

5 Hardik 27 Bhopal 8500.00

6 Komal 22 Hyderabad 4500.00

7 Muffy 24 Indore 10000.00

The RELEASE SAVEPOINT Command

The RELEASE SAVEPOINT command is used to remove an existing SAVEPOINT.

The syntax for a RELEASE SAVEPOINT command is as follows.


RELEASE SAVEPOINT SAVEPOINT_NAME;

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

To display NAME, LOCATION, PHONE_NUMBER of the students from DATABASE


table whose section is A

Select NAME, LOCATION, PHONE_NUMBER from DATABASE WHERE ROLL_NO


IN
(SELECT ROLL_NO from STUDENT where SECTION=’A’);

Explanation : First subquery executes “ SELECT ROLL_NO from STUDENT where


SECTION=’A’ ” returns ROLL_NO from STUDENT table whose SECTION is ‘A’.Then
outer-query executes it and return the NAME, LOCATION, PHONE_NUMBER from the
DATABASE table of the student whose ROLL_NO is returned from inner subquery.
Output:

NAME ROLL_NO LOCATION PHONE_NUMBER


Ravi 104 Salem 8989898989
Raj 102 Coimbatore 8877665544

Insert Query Example:

Table1: Student1

NAME ROLL_NO LOCATION PHONE_NUMBER


Ram 101 chennai 9988773344
Raju 102 coimbatore 9090909090
Ravi 103 salem 8989898989

Table2: Student2

NAME ROLL_NO LOCATION PHONE_NUMBER


Raj 111 chennai 8787878787
Sai 112 mumbai 6565656565
Sri 113 coimbatore 7878787878

To insert Student2 into Student1 table:

25
INSERT INTO Student1 SELECT * FROM Student2;

Output:

NAME ROLL_NO LOCATION PHONE_NUMBER


Ram 101 chennai 9988773344
Raju 102 coimbatore 9090909090
Ravi 103 salem 8989898989
Raj 111 chennai 8787878787
Sai 112 mumbai 6565656565
Sri 113 coimbatore 7878787878

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:

1 row delete successfully.

Display Student2 table:

NAME ROLL_NO LOCATION PHONE_NUMBER


Sai 112 mumbai 6565656565
Sri 113 coimbatore 7878787878
To update name of the students to geeks in Student2 table whose location is same as
Raju,Ravi in Student1 table

UPDATE Student2 SET NAME=’geeks’ WHERE LOCATION IN ( SELECT LOCATION


FROM Student1 WHERE NAME IN (‘Raju’,’Ravi’));

Output:

1 row updated successfully.

 Display Student2 table:

NAME ROLL_NO LOCATION PHONE_NUMBER


Sai 112 mumbai 6565656565
geeks 113 coimbatore 7878787878

SQL | SUB Queries

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

NAME ROLL_NO LOCATION PHONE_NUMBER


Ram 101 Chennai 9988775566
Raj 102 Coimbatore 8877665544
Sasi 103 Madurai 7766553344
Ravi 104 Salem 8989898989
Sumathi 105 Kanchipuram 8989856868

STUDENT

NAME ROLL_NO SECTION


Ravi 104 A
Sumathi 105 B
Raj 102 A

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

A join, which is based on equalities, is called equi-join.

It can be used as follows:

o To insert records in the target table.


o To create tables and insert records in this table.
o To update records in the target table.
o To create views.

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

SQL> SELECT * FROM table1,table2


2 WHERE table1.rollno=table2.rollno;

b) Non Equi-Join
28
SQL> SELECT * FROM table1,table2
2 WHERE table1.rollno>=table2.rollno;

2) SELF JOIN

SQL> SELECT * FROM table1 a,table1 b WHERE a.rollno=b.rollno;

3) INNER JOIN

SQL> SELECT * FROM table1 INNER JOIN table2 USING (rollno);

4) NATURAL JOIN

SQL> SELECT * FROM table1 NATURAL JOIN table2;

5) CROSS JOIN

SQL> SELECT * FROM table1 CROSS JOIN table2;

6) OUTER JOIN

a) Left Outer Join

SQL> SELECT * FROM table1,table2 WHERE table1.rollno(+)=table2.rollno;

b) Right Outer Join

SQL> SELECT * FROM table1,table2 WHERE table1.rollno=table2.rollno(+);

c) Full Outer Join

SQL> SELECT * FROM table1 FULL JOIN table2 ON table1.rollno=table2.rollno;

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

Procedure and Example

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.

3. Referential integrity Constraint: Used to ensure referential integrity of the data.

DOMAIN INTEGRITY CONSTRAINTS/COLUMN-LEVEL CONSTRAINTS

a) NOT NULL CONSTRAINT


Description : This constraint is used to specify that a column may never contain a NULL
value. This is enforced at SQL insert and update time.

Syntax:
Create table <tablename>(col1 datatype [constraint constname] not null, col2 datatype, ….)

Using Alter Statement

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.

Using Create Statement


Syntax:

Create table <table name> (col1 datatype default value, col2 datatype,….)

Using Alter statement


SQL> alter table emp1 modify age default 25;

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,…)

Using Alter statement

Syntax:

alter table <tablename> add [constraint constname] check (colname <condtions>);

ENTITY INTEGRITY CONSTRAINTS /TABLE –LEVEL CONSTRAINTS

a) UNIQUE CONSTRAINT

Description: The UNIQUE constraint ensures that all values in a column are distinct. Null
value is accepted.

During Creation Of Table

31
Syntax:
create table <tablename>(col1 datatype [constraint cname] unique, col2 datatype,………);

Using Alter Statement


Syntax:
alter table <tablename> add [constraint cname] unique(colname);

b) PRIMARY KEY=(unique key + not null)

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

During Creation Of Table


Syntax 1: create table <table name> (col1 datatype [constraint cname ] primary key, col2
datatype, ….);

Syntax 2: create table <table name>(column1 datatype ,column2 datatype ,..[constraint


cname] primary key (column1, column2, ….));
Using Alter Statement

Syntax:

alter table <tablename >add [constraint cname] primary key (column1, column2, …);

REFERENTIAL INTEGRITY CONSTRAINT


Description:

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.

The structure of these two tables will be as follows:


32
Table CUSTOMER Table ORDERS

column name characteristic


column name characteristic
OID Primary Key
CID Primary Key
ODate
lname
C_ID Foreign Key
fname
Amount

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.

During Creation Of The 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.

Problem 4.4: Create dept table with the following structure.

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:

a. Additional level of table security.


b. Hides data complexity.
c. Simplifies the usage by combinig multiple tables into a single table.
d. Provides datas in different perspective.

Syntax:

Create [or replace ] view <view name> [column alis names] as <query> [with <options>
conditions];

Types of view:

1. Horizontal view: enforced by where cause


2. Vertical View: enforced by selecting the required columns

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)

Problem 3.4: Display all the views generated.


Problem 3.5: Execute the DML commands on the view created.
Problem 3.6: Drop a view.
35
INDEX

 Default index is B-Tree index.


 Index is a db objects, provide a fast access path to column that are indexed.
 It contains an entry for each value that appears in the Index columns.
 Indexes are stored separately from actual data.
 Index are independent of the table, it indexes both physically and logically.
 Index do not have activated & deactivated.
 We can use up to 16 COLUMNS as index.

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)

Bit map index


Bitmap indexes are normally used to index low cardinality columns in a warehouse
environment.(statics)
>create bit map index bmid on emp(deptno);

B-tree index
B tree index are normally used OLTP Environment.(Dynamic)

Function based index


This function is created on the arithmetic expression on columns of table.
>Create index fid on emp(sal+comm.);
Reverse index
This is created on columns containing data in sequential order.
>create index rid on emp(empno) reverse;

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.

>ALTER sequence (seq_name)


[Increment by n
Max value n
Min value n
Cycle
Cache];
SYNONYM

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

Private synonyms- it is created by user.


Public synonyms-
Which can be accessed by all USERS in the DB?
Synonym created by user with CREATE PUBLIC SYNONYM privileges.
>create synonym (syn_name) for scott.

STUDY OF PL/SQL BLOCK.

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:

 PL/SQL is a completely portable, high-performance transaction-processing language.


 PL/SQL provides a built-in interpreted and OS independent programming
environment.

Features of PL/SQL

PL/SQL has the following features:

 PL/SQL is tightly integrated with SQL.


 It offers extensive error checking.
 It offers numerous data types.
 It offers a variety of programming structures.
 It supports structured programming through functions and procedures.

Advantages of PL/SQL

PL/SQL has the following advantages:

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

Data Type Description


CHAR Fixed-length character string with maximum size of 32,767 bytes
VARCHAR2 Variable-length character string with maximum size of 32,767 bytes
RAW Variable-length binary or byte string with maximum size of 32,767
bytes, not interpreted by PL/SQL
NCHAR Fixed-length national character string with maximum size of 32,767
bytes
NVARCHAR2 Variable-length national character string with maximum size of
32,767 bytes
LONG Variable-length character string with maximum size of 32,760 bytes

Variable Declaration in PL/SQL

variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value]


39
Declaring a Constant

PI CONSTANT NUMBER := 3.141592654;

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

Select * from customers;


ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00

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.

Select * from customers;

ID NAME AGE ADDRESS SALARY


1 Ramesh 32 Ahmedabad 2500.00
2 Khilan 25 Delhi 2000.00
3 kaushik 23 Kota 2500.00
4 Chaitali 25 Mumbai 7000.00
5 Hardik 27 Bhopal 9000.00
41
6 Komal 22 MP 5000.00

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

PL/SQL procedure successfully completed.

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.

Modularized program development:

· Group logically related statements within blocks.


· Nest sub-blocks inside larger blocks to build powerful programs.

· Break down a complex problem into a set of manageable well defined logical
modules and implement the modules with blocks.

Procedure and function blocks:


Procedure:
- No return.
- PROCEDURE name IS

Function:
- Returns a value
- FUNCTION name RETURN data-type IS

Syntax for procedure:


Create [or Replace] PROCEDURE procedur_name
(parameter1 [model1] datatype1,
(parameter2 [model2] datatype2, …)
IS|AS PL/SQL Block;

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

What is a Function in PL/SQL?

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.

General Syntax to create a function is

CREATE [OR REPLACE] FUNCTION function_name [parameters]


RETURN return_datatype;
IS
Declaration_section
BEGIN
Execution_section
Return return_variable;
EXCEPTION
exception section
Return return_variable;
END;

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

CREATE OR REPLACE FUNCTION employer_details_func


RETURN VARCHAR(20);
IS
emp_name VARCHAR(20);
BEGIN
SELECT first_name INTO emp_name
FROM emp_tbl WHERE empID = '100';
RETURN emp_name;
END;
/

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.

How to execute a PL/SQL Function?

A function can be executed in the following ways.

1) Since a function returns a value we can assign it to a variable.

44
employee_name := employer_details_func;

If ‘employee_name’ is of datatype varchar we can store the name of the employee by


assigning the return type of the function to it.

2) As a part of a SELECT statement

SELECT employer_details_func FROM dual;

3) In a PL/SQL Statements like,

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

A trigger is a statement that is executed automatically by the system as a side effect of a


modification to the database.

It can either be:


1. Application trigger: Fires whenever an event occurs with a particular application.
2. Database Trigger: Fires whenever a data event (such as DML) occurs on a schema
or database.

The parts of a trigger are,


 Trigger statement: Specifies the DML statements and fires the trigger body. It also
specifies the table to which the trigger is associated.
 Trigger body or trigger action: It is a PL/SQL block that is executed when the
triggering statement is used.
 Trigger restriction: Restrictions on the trigger can be achieved

The different uses of triggers are as follows,

 To generate data automatically


 To enforce complex integrity constraints
 To customize complex securing authorizations
 To maintain the replicate table
 To audit data modifications

TYPES OF TRIGGERS

The various types of triggers are as follows,

 Before: It fires the trigger before executing the trigger statement.


 After: It fires the trigger after executing the trigger statement.
 For each row: It specifies that the trigger fires once per row.
 For each statement: This is the default trigger that is invoked. It specifies that the
trigger fires once per statement.

VARIABLES USED IN TRIGGERS


 :new
 :old
These two variables retain the new and old values of the column updated in the database. The
values in these variables can be used in the database triggers for data manipulation

46
SYNTAX

create or replace trigger triggername [before/after]


{DML statements}
on [tablename] [for each row/statement]
begin
-------------------------
-------------------------
exception
end;

USER DEFINED ERROR MESSAGE


 The package “raise_application_error” is used to issue the user defined error
messages
 Syntax: raise_application_error(error number,‘error message‘);
 The error number can lie between -20000 and -20999.
 The error message should be a character string.

Example: CREATE [OR REPLACE] TRIGGER


secure_emp Before insert on emp
BEGIN
IF(to_char(sysdate,’dy’) IN (‘SAT’,’SUN’)) OR
To_char(sysdate,’HH24’) NOT BETWEEN ‘08’
AND ‘18’) THEN
RAISE_APPLICATION_ERROR(-20500,
‘you may only insert into EMP during normal
hours.’); END IF;
END;
Program 6.1: Write a TRIGGER to ensure that DEPT TABLE does not
contain duplicate of null values in DEPTNO column

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.

An error condition during a program execution is called an exception in PL/SQL. PL/SQL


supports programmers to catch such conditions using EXCEPTION block in the program
and an appropriate action is taken against the error condition. There are two types of
exceptions:

 System-defined exceptions
 User-defined exceptions

Syntax for Exception Handling

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.

The syntax for declaring an exception is:

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)

Inventory control system


Aim
To create an application using visual basic and oracle for inventory control system.
Problem Statement

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.

Step 1: Create the following table in oracle


SQL> create table custable1(cid varchar(10)primary key,cname varchar(15),caddr
varchar(30),cphno number(10),cemail varchar(20));
Table created.

SQL> desc custable1;

Name Null? Type


-------------------------------------- -------- --------------------
CID NOT NULL VARCHAR2(10)
CNAME VARCHAR2(15)
CADDR VARCHAR2(30)
CPHNO NUMBER(10)
CEMAIL VARCHAR2(20)

SQL> create table stock1(ino varchar(10)primary key,iname varchar(20),quantity


number(5),price number(10));
Table created.

SQL> desc stock1;


Name Null? Type
------------------------------ ------ -------- ------------------------
INO NOT NULL VARCHAR2(10)
INAME VARCHAR2(20)
QUANTITY NUMBER(5)
PRICE NUMBER(10)

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.

SQL> desc sales1;


Name Null? Type
----------------------------------------- -------- ----------------------------
CID1 VARCHAR2(10)
CNAME1 VARCHAR2(15)
INO1 NUMBER(10)
INAME1 VARCHAR2(20)
QUANTITY1 NUMBER(5)
PRICE1 NUMBER(10,2)

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

Public Sub Main()


con.Open "Inventory", "system", "manager"
rs1.Open "custable1", con, 1, 3
rs2.Open "stock1", con, 1, 3
rs3.Open "sales1", con, 1, 3
Form1.Show
End Sub

Main Form (Form1)

Private Sub Label2_Click()


Form2.Show
End Sub

52
Private Sub Label3_Click()
End
End Sub

Private Sub Label4_Click()


Form3.Show
End Sub

Private Sub Label5_Click()


Form4.Show
End Sub

Customer Details (Form2)

Private Sub Command1_Click() ‘Clear


Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text4.Text = ""
Text5.Text = ""
End Sub
Private Sub Command2_Click() ‘Save
rs1.AddNew
rs1(0) = Text1.Text
rs1(1) = Text2.Text
rs1(2) = Text3.Text
rs1(3) = Text4.Text
rs1(4) = Text5.Text
rs1.Save
MsgBox "Record Saved successfully..."
End Sub

Private Sub Command3_Click() ‘Main menu


Form1.Show
End Sub

Private Sub Command4_Click() ‘Exit


End
End Sub

Stock Details (Form3)

53
Private Sub Command1_Click() ‘Clear
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text4.Text = ""
End Sub

Private Sub Command10_Click() ‘Search


inp = InputBox("Enter INO to Search Record..")
Set tmp3 = con.Execute("select * from stock1 where ino='" & inp & "'")

If tmp3.EOF = False And tmp3.BOF = False Then


Text1.Text = tmp3(0)
Text2.Text = tmp3(1)
Text3.Text = tmp3(2)
Text4.Text = tmp3(3)
Else
MsgBox "Record not Found.."
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text4.Text = ""
End If
End Sub

Private Sub Command11_Click() ‘delete


con.Execute ("delete From stock1 where ino='" & Text1.Text & "'")
MsgBox "Record deleted.."
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text4.Text = ""
End Sub

Private Sub Command2_Click() ‘Save


rs2.AddNew

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

Private Sub Command3_Click() ‘Main menu


Form1.Show
End Sub

Private Sub Command4_Click() ‘Exit


End
End Sub

Private Sub Command5_Click() ‘Modify


rs2(0) = Text1.Text
rs2(1) = Text2.Text
rs2(2) = Text3.Text
rs2(3) = Text4.Text
rs2.Update
MsgBox "Record updated successfully..."
End Sub

Private Sub Command6_Click() ‘Move First


rs2.MoveFirst
view
End Sub

Private Sub Command7_Click() ‘Move Last


rs2.MoveLast
view
End Sub

Private Sub Command8_Click() ‘Move Previous


If rs2.BOF Then
rs2.MoveFirst
End If
rs2.MovePrevious
view
End Sub

Private Sub Command9_Click() ‘Move Last


If rs2.EOF Then
rs2.MoveLast
End If
rs2.MoveNext
view
End Sub

Public Sub view() ‘View function


55
If rs2.BOF Or rs2.EOF Then
MsgBox "EOF or BOF file..."
Else
Text1.Text = rs2(0)
Text2.Text = rs2(1)
Text3.Text = rs2(2)
Text4.Text = rs2(3)
End If
End Sub

Sales Details (Form4)

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

Private Sub Combo2_Click() ‘fetch product name from stock table


rs2.MoveFirst
Do While Not rs2.EOF
If Trim(Combo2.Text) = Trim(rs2(0)) Then Exit Do
rs2.MoveNext
Loop
Text4.Text = rs2(1) ‘product name
End Sub

Private Sub Command1_Click() ‘clear


Combo1.Text = ""
Text2.Text = ""
Combo2.Text = ""
Text4.Text = ""
Text5.Text = ""
Text6.Text = ""
End Sub

Private Sub Command2_Click() ‘save


rs3.AddNew
rs3(0) = Combo1.Text
rs3(1) = Text2.Text
rs3(2) = Combo2.Text
rs3(3) = Text4.Text
rs3(4) = Text5.Text
rs3(5) = Text6.Text
rs3.Save
MsgBox "Record Saved successfully..."

rs2.MoveFirst ‘reduce quantity from stock table after purchase


Do While Not rs2.EOF
If Combo2.Text = rs2(0) Then
rs2(2) = rs2(2) - Val(Text5.Text)
rs2.Update
Exit Do
End If
rs2.MoveNext
Loop
End Sub

Private Sub Command3_Click()


Form1.Show
57
End Sub

Private Sub Command4_Click()


End
End Sub

Private Sub Command5_Click() ‘delete


con.Execute ("delete From sales1 where cid1='" & Combo1.Text & "'")
MsgBox "Record deleted.."
Combo1.Text = ""
Text2.Text = ""
Combo2.Text = ""
Text4.Text = ""
Text5.Text = ""
Text6.Text = ""
End Sub

Private Sub Command6_Click() ‘search


inp = InputBox("Enter CID to Search Record..")
Set tmp3 = con.Execute("select * from sales1 where cid1='" & inp & "'")

If tmp3.EOF = False And tmp3.BOF = False Then


Combo1.Text = tmp3(0)
Text2.Text = tmp3(1)
Combo2.Text = tmp3(2)
Text4.Text = tmp3(3)
Text5.Text = tmp3(4)
Text6.Text = tmp3(5)
Else
MsgBox "Record not Found.."
Combo1.Text = ""
Text2.Text = ""
Combo2.Text = ""
Text4.Text = ""
Text5.Text = ""
Text6.Text = ""

End If
End Sub

Private Sub Form_Load()


'fetch cid from custable1 then move to combo1
rs1.MoveFirst
While Not rs1.EOF
Combo1.AddItem rs1(0)
rs1.MoveNext
Wend
'fetch ino from stock1 then move to combo2
rs2.MoveFirst
While Not rs2.EOF
Combo2.AddItem rs2(0)
58
rs2.MoveNext
Wend
End Sub

Private Sub Text6_Click()


Text6.Text = Text5.Text * rs2(3)

End Sub

Railway Reservation System

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:

Private Sub Command1_Click()


Form2.Show
Me.Hide
Form3.Hide
Form4.Hide
End Sub

Private Sub Command2_Click()


Form3.Show
Me.Hide
Form2.Hide
Form4.Hide
End Sub

Private Sub Command3_Click()


Form4.Show
Me.Hide
Form3.Hide
Form2.Hide
End Sub

Private Sub Command4_Click()


End
End Sub

Private Sub Form_Load()


MsgBox "server connected"
End Sub

60
FORM2:

Private Sub Combo1_Click()


Combo2.SetFocus
End Sub

Private Sub Combo2_Click()


rs1.MoveFirst
Do
If rs1(2) = "MADURAI" Then
Me.List1.AddItem rs1(0)
End If
rs1.MoveNext
Loop Until rs1.EOF
End Sub

Private Sub Command2_Click()


Combo1.Text = ""
Combo2.Text = ""
List1.Clear
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text4.Text = ""
Text5.Text = ""
Text6.Text = ""
Text7.Text = ""
End Sub

Private Sub Command3_Click()


Form1.Show
Me.Hide
Form3.Hide
Form4.Hide
End Sub

61
Private Sub Form_Load()
rs1.MoveFirst
rs2.MoveFirst
'' rs3.MoveFirst
Combo1.AddItem "MADURAI"
Combo2.AddItem "CHENNAI"
End Sub

Private Sub List1_Click()


rs1.MoveFirst
Do
If rs1(0) = List1.Text Then Exit Do
rs1.MoveNext
Loop While Not rs1.EOF
Text1.Text = rs1(1)
Text2.Text = rs1(4)
Text3.Text = rs1(5)
Set t = con.Execute("select * from coach where tno=" & Val(List1.Text))
Text4.Text = CInt(t(3))
Text5.Text = CInt(t(7))
Text6.Text = CInt(t(4))
Text7.Text = CInt(t(8))
End Sub

FORM3:

Private Sub Command1_Click()


rs3.AddNew
rs3(0) = Me.Text1.Text
rs3(2) = Val(Me.Combo1.Text)
rs3(3) = Val(Me.Text2.Text)
If Option1.Value = True Then
rs3(4) = Option1.Caption
Else
rs3(4) = Option2.Caption
62
End If
rs3(5) = Format(CDate(Text3.Text), "dd-mm-yyyy")
rs1.MoveFirst
Do
If rs1(0) = Val(Me.Combo1.Text) Then Exit Do
rs1.MoveNext
Loop Until rs1.EOF
rs3(7) = rs1(2)
rs3(8) = rs1(3)
rs2.MoveFirst
Do
If Option3.Value = True Then
If CInt(rs2(0)) = Val(Me.Combo1.Text) And CInt(rs2(3)) > 0 Then
rs2(3) = rs2(3) - 1
rs3(1) = Int((100 * Rnd) + 1)
MsgBox rs3(1)
Me.Text4.Text = rs3(1)
rs3(6) = Option3.Caption
rs3(9) = rs2(1)
rs3(10) = rs2(2) - rs2(3)
rs3(11) = rs2(4)
''rs2.Update
Exit Do
End If
ElseIf Option4.Value = True Then
If CInt(rs2(0)) = Val(Me.Combo1.Text) And CInt(rs2(7)) > 0 Then
rs2(7) = rs2(7) - 1
rs3(1) = Int((100 * Rnd) + 1)

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

Private Sub Command2_Click()


Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Combo1.Clear
End Sub
63
Private Sub Command3_Click()
Form1.Show
Me.Hide
Form3.Hide
Form4.Hide
End Sub

Private Sub Command4_Click()


DataEnvironment1.Command1 Val(Text4.Text)
DataReport1.Show
End Sub

Private Sub Form_Load()


Text4.Visible= False
rs1.MoveFirst
While Not rs1.EOF
Combo1.AddItem rs1(0)
rs1.MoveNext
Wend
End Sub

FORM 4:

Private Sub Command1_Click()


rs3.MoveFirst
Do
If rs3(1) = Val(Text1.Text) Then Exit Do
rs3.MoveNext
Loop Until rs3.EOF
rs2.MoveFirst
Do
If rs2(0) = rs3(2) And rs2(1) = rs3(9) Then
rs2(3) = rs2(3) + 1
Exit Do
ElseIf rs2(0) = rs3(2) And rs2(5) = rs3(9) Then
64
rs2(7) = rs2(7) + 1
Exit Do
End If
rs2.MoveNext
Loop Until rs2.EOF
rs2.Update
rs3.Delete
End Sub

Private Sub Command2_Click()


Text1.Text = ""
End Sub

Private Sub Command3_Click()


Form1.Show
Me.Hide
Form3.Hide
Form4.Hide
End Sub

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.

Design an application for the following:


1. Material Requirement Processing
2. Hospital Management System
3. Personal Information System
4. Web Based User Identification System
5. Timetable Management System
6. Hotel Management System
7. Online course registration system
8. Library Management System
9. Online ticket reservation system

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

4. What is a field in a database ?


A field is an area within a record reserved for a specific piece of data.
Examples: Employee Name, Employee ID, etc.

5. What is a Record in a database ?


A record is the collection of values / fields of a specific entity: i.e. an Employee,
Salary etc.

6. What is a Table in a database ?


A table is a collection of records of a specific type. For example, employee table,
salary table etc.

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.

9. What are the advantages of DBMS?


 Redundancy is controlled.
 Unauthorized access is restricted.
 Providing multiple user interfaces.
 Enforcing integrity constraints.
 Providing backup and recovery.

10. What is an attribute?


It is the name of the column. An attribute gives the characteristics of the entity. For
example, A customer of bank may be described by : name, address, customer ID
number.

11. What is a Relation Schema and a Relation?


A set of attributes is called a relation schema (or relation scheme). A relation
schema is also known as table schema (or table scheme). ... It is the logical definition
of a table.

12. What are super, primary, candidate and foreign keys?


A superkey is a set of attributes of a relation schema upon which all attributes of the
schema are functionally dependent. No two rows can have the same value of super
key attributes.
A Candidate key is minimal superkey, i.e., no proper subset of Candidate key
attributes can be a superkey.
A Primary Key is one of the candidate keys. One of the candidate keys is selected as
most important and becomes the primary key. There cannot be more that one primary
keys in a table.
Foreign key is a field (or collection of fields) in one table that uniquely identifies a
row of another table.

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.

14. What is database normalization?


It is a process of analyzing the given relation schemas based on their Functional
Dependencies (FDs) and primary key to achieve the properties
(1).Minimizing redundancy, (2). Minimizing insertion, deletion and update anomalies.
67
15. What is SQL?
SQL (pronounced "ess-que-el") stands for Structured Query Language. SQL is used to
communicate with a database.

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.

17. What is a view in SQL? How to create one?


A view is a virtual table based on the result-set of an SQL statement. We can create
using create view syntax.
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition

18. What is a Trigger?


A Trigger is a code that associated with insert, update or delete operations. The code
is executed automatically whenever the associated query is executed on a table.
Triggers can be useful to maintain integrity in database.

19. What is a stored procedure?


A stored procedure is like a function that contains a set of operations compiled
together. It contains a set of operations that are commonly used in an application to do
some common database tasks.

20. What is the difference between Trigger and Stored Procedure?


Unlike Stored Procedures, Triggers cannot be called directly. They can only be
associated with queries.

21. Define Aggregate functions.


In database management an aggregate function is a function where the values of
multiple rows are grouped together as input on certain criteria to form a single value
of more significant meaning or measurement such as a set, a bag or a list.

22. Define Join and enlist its types.


A JOIN is a means for combining columns from one (self-table) or more tables by
using values common to each. ANSI-standard SQL specifies five types of JOIN :
INNER , LEFT OUTER , RIGHT OUTER , FULL OUTER and CROSS .

23. Explain ODBC .


Open Database Connectivity (ODBC) provides a standard software interface for
accessing database management systems (DBMS).Any application can use ODBC
to query data from a database, regardless of the platform it is on or DBMS it uses.

24. What is sequence, index and synonym.

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.

25. What are the constraints?


Constraints are used to limit the type of data that can go into a table. This ensures the
accuracy and reliability of the data in the table. If there is any violation between
the constraint and the data action, the action is aborted. Constraints can be column
level or table level.

----------------------------------------------------------------------

69

You might also like