CS6312 DATABASE MANAGEMENT SYSTEMS LABORATORY L T … · 2018-05-08 · INTRODUCTION TO DBMS...

21
CS6312 DATABASE MANAGEMENT SYSTEMS LABORATORY L T P C 0 0 3 2 LIST OF EXPERIMENTS: 1. Creation of a database and writing SQL queries to retrieve information from the database. 2. Performing Insertion, Deletion, Modifying, Altering, Updating and Viewing records based on conditions. 3. Creation of Views, Synonyms, Sequence, Indexes, Save point. 4. Creating an Employee database to set various constraints. 5. Creating relationship between the databases. 6. Study of PL/SQL block. 7. Write a PL/SQL block to satisfy some conditions by accepting input from the user. 8. Write a PL/SQL block that handles all types of exceptions. 9. Creation of Procedures. 10. Creation of database triggers and functions 11. Mini project (Application Development using Oracle/ Mysql ) a) Inventory Control System. b) Material Requirement Processing. c) Hospital Management System. d) Railway Reservation System. e) Personal Information System. f) Web Based User Identification System. g) Timetable Management System. h) Hotel Management System

Transcript of CS6312 DATABASE MANAGEMENT SYSTEMS LABORATORY L T … · 2018-05-08 · INTRODUCTION TO DBMS...

CS6312 DATABASE MANAGEMENT SYSTEMS LABORATORY L T P C 0 0 3 2

LIST OF EXPERIMENTS:1. Creation of a database and writing SQL queries to retrieve information from the database.

2. Performing Insertion, Deletion, Modifying, Altering, Updating and Viewing records based on

conditions.

3. Creation of Views, Synonyms, Sequence, Indexes, Save point.

4. Creating an Employee database to set various constraints.

5. Creating relationship between the databases.

6. Study of PL/SQL block.

7. Write a PL/SQL block to satisfy some conditions by accepting input from the user.

8. Write a PL/SQL block that handles all types of exceptions.

9. Creation of Procedures.

10. Creation of database triggers and functions

11. Mini project (Application Development using Oracle/ Mysql )

a) Inventory Control System.

b) Material Requirement Processing.

c) Hospital Management System.

d) Railway Reservation System.

e) Personal Information System.

f) Web Based User Identification System.

g) Timetable Management System.

h) Hotel Management System

INTRODUCTION TO DBMS

OVERVIEW OF RDBMS:

RDBMS is the acronym for Relational Data Base Management System. The concept of

relational database is known since 1980‟s but the idea of Data Base Management System is

definitely old. The most famous RDBMS packages are Oracle, Sybase, and Informix.

What is DBMS?

A Data Base Management System is essentially a collection of interrelated data and a set

of programs to access this data. This collection of data is called the Database. The Primary

objective of a DBMS is to provide a convenient environment to retrieve and store database

information. Database systems support single user and multiuser environment. While on one

hand DBMS permits only one person to access the database at a given time, on the other

RDBMS allows many users simultaneous access to the database.

A Database System consists of two Parts namely, DBMS and Database Application.

DBMS is the program that organizes and maintains the information whereas the Database

Application is the program that lets us view, retrieve and update information stored in the

DBMS. DBMS has to protect against unintentional changes that could be caused by users and

applications. In case of multi user system, it must be capable of notifying any database change to

the other user.

DBMS offers following services:

Data Definition

Data maintenance

Data Manipulation

Data display

Data Integrity

INTRODUCTION TO ORACLE

Every business enterprise maintains large volumes of data for its operations. With more

and more people accessing this data for their work the need to maintain its integrity and

relevance increases. Normally, with the traditional methods of storing data and information in

files, the chance that the data loses its integrity and validity are very high.

Oracle 8 is an Object Relational Database Management System (ORDBMS). It offers

capabilities of both relational and object oriented data base systems. In general, objects can be

defined as reusable software codes which are location independent and perform a specific task on

any application environment with little or no change to the code.

Oracle products are based on a concept known as the client/Server Technology. This

concept involves segregating the processing of an application between two systems. One

performs all activities related to the database (server) and the other performs activities that help

the user to interact with the application (client).

A Client or front-end database application also interacts with the database by requesting

and receiving information from the database server. It acts as an interface between the user and

the database. Further, it also checks for validation against the data entered by the user. The

commonly used front end tools of oracle are SQL * Plus V 8, Oracle forms 5.0 and Reports 3.0.

The database server or backend is used to manage the database tables optimally among

multiple clients who concurrently request the server for the sane data. It also enforces data

integrity across all client applications and controls database access and other security

requirements.

Tools of Oracle:

The tools provided by Oracle are so user friendly that a person with minimum skillls in

the field of computer can access them with ease. The main tools are

SQL * Plus

PL/SQL

Forms

Reports

SQL * Plus:

SQL * Plus is a Structured Query Language supported by Oracle. Through SQl* Plus we

can store, retrieve, edit, enter and run SQL commands and PL/SQL blocks. Using SQl * Plus we

can perform calculations, list column definitions for any table and can format query results in the

form of a report.

PL/SQL:

PL/SQL is an extension of SQL. PL./SQL statements can contain any number of SQL

statements integrated with flow of control statements. Thus PL/SQL combines the data

manipulating power of SQL with data processing power of procedural languages.

Forms:

This is a graphical tool used for generating and executing form-based applications. A

form basically comprises blocks and fields. Multiple tables can be accessed over a single form,

based on the application with the help of transaction commands. Oracle Forms Buildet is the

design component of Oracle forms. We can build, generate and run an Oracle forms application

from the builder.

Reports:

It is an application development tool of Oracle for developing, executing, displaying and

printing reports. We can create a wide variety of reports, which have various modes. Oracle

reports are powerful, yet easy to use. The reasons for choosing Oracle 8 as the RDBMS for

effectively managing the data are

Ability to retrieve data spread across multiple tables.

Oracle specific SQL *Plus functions used when required to query the database especially to

decide future course of action.

Provisions to maintain integrity of the database to avois data duplication and have constant

checks on the validity of data.

Ability to break the most frequently used object, the table into smaller units thereby reducing

the risk to loss of data.

With a number of clients accessing the database, Oracle allows explicit locking of data.

Concurrent access of data for manipulation can be prevented in this way.

Storing of information out-of-line with the table is also a major advantage. This allows

unstructured information to be stored in a different location with the pointers to the location

present in the table.

It supports OOPs concepts, making it a powerful object oriented database.

INTRODUCTION TO SQL

SQL was invented and developed by IBM in early 1970‟s. SQL stands for Structured

Query Language. IBM was able to demonstrate how to control relational database using SQL.

The SQL implemented by ORACLE CORPORATION is 100% compliant with the ANSI/ ISO

standard SQL data language. Oracle‟s database language is SQL, which is used for storing and

retrieving information in Oracle. A table is a Primary database object of SQL that is used to store

data. A table that holds data in the fo rm of rows and columns.

In order to communicate with the database, SQL supports the following categories of

commands: -

Data Definition Language - create, alter and drop commands.

Data Manipulation Language - insert, select, delete and update commands.

Transaction Control Language - commit, savepoint and rollback commands.

Data control Language - grant and revoke commands.

Data Definition Language: DDL is used to create an object (table), alter the structure of an

object and also to drop the object created. A table is a unit of storage that holds data in the form

of rows and columns. DDL is used for table definition.

Data Manipulation Language: DML commands are most frequently used SQL commands.

They are used to query and manipulate existing objects like tables.

Transaction Control Language: A transaction is a logical unit of work. All changes made to the

database can be referred to as a transaction. Transaction changes can be made permanent to a

database only if they are committed. A transaction begins with an executable SQL statement ends

explicitly with either rollback or commit commands and implicitly i.e., automatically, when a

DDL statement is used. The following are the benefits of SQL:

Non-procedural Language, because more than one record can be accessed rather than one

record at a time.

It is the common language for all relational databases. In other words it is portable and it

requires very few modifications so that it can work on other databases.

Very simple commands for Querying, inserting, deleting and modifying data and objects.

SQL Vs SQL *Plus:

SQL is a standard language common to all relational databases. SQL is a database

language used for storing and retrieving data from the database. Most relational Database

Management Systems provide extensions to SQL to make it easier for application developers.

SQL *Plus is an Oracle specific Program which accepts SQL commands and PL/SQL

blocks and executes them. SQL *Plus enables manipulation of SQL commands and PL/SQL

blocks. It also performs many additional tasks as well. Through SQL *Plus we can

enter, edit, store, retrieve and run SQL commands and PL/SQL blocks.

format, perform calculations, store and print query results in the form of reports.

list column definitions for any table.

Access and copy data between SQL databases.

Send messages to and accept responses from an end user.

Ex.No:1. CREATION OF A DATABASE AND WRITING SQL QUERIES TORETRIEVE INFORMATION FROM THE DATABASE.

AIM:

To create, alter, truncate and drop a table using DDL commands.

DDL COMMANDS:

OVERVIEW:CREATE - to create objects in the databaseALTER - alters the structure of the objects in the databaseDROP - delete objects from the databaseTRUNCATE - remove all records from a table, including all spaces allocated for the records are removedCOMMENT - add comments to the data dictionaryGRANT - gives user's access privileges to databaseREVOKE - withdraw access privileges given with the GRANT command

SQL - CREATE TABLE

Syntax: CREATE TABLE tablename (column_name data_ type constraints, …)

Example:

INPUT::

SQL> CREATE TABLE DEPARTMENT (DEPTID VARCHAR (5) CONSTRAINT PKEYPRIMARY KEY, DEPTNAME VARCHAR (15), DOS DATE CONSTRAINT NOTNULL);OUTPUT: Table created.

SQL> CREATE TABLE EMPLOYE (EMPID VARCHAR (5) CONSTRAINT PKEYPRIMARY KEY, EMPNAME VARCHAR (15), JOB CHAR (10) CONSTRAINT UNIQ1UNIQUE, MGRID VARCHAR (5) CONSTRAINT FKEY1 REFERENCES EMP (EMPID),HIREDATE DATE, DEPTID VARCHAR (5) CONSTRAINT FKEY2 REFERENCES DEPT(DEPTID), SALARY NUMBER (7, 2));OUTPUT: Table created.

SQL - DESC TABLE

SQL>desc Employe;

Name Null? Type--------------------------------- -------- ----------------------------EMPID NOT NULL VARCHAR2(5)EMPNAME VARCHAR2(20)JOB NOT NULL CHAR(10)MGRID NOT NULL VARCHAR2(5)HIREDATE DATEDEPTID VARCHAR2(5)SALARY NUMBER(7,2)

SQL - ALTER TABLE

INPUT::

SQL>ALTER TABLE EMPLOYE ADD CONSTRAINT NTNLL NOT NULL (SALARY);

OUTPUT: Table Altered.

Similarly, ALTER TABLE EMPLOYE DROP CONSTRAINT UNIQ1;

SQL - DROP TABLE

– Deletes table structure – Cannot be recovered – Use with caution

INPUT::

SQL> DROP TABLE EMP; //Here EMP is table name

OUTPUT: Table Dropped.

SQL - TRUNCATE TABLE

TRUNCATE TRUNCATE TABLE <TABLE NAME>;

PRELAB QUESTIONS:

1. What is a database?

A database is a logically coherent collection of data with some inherent meaning, representing

some aspect of real world and which is designed, built and populated with data for a specific

purpose.

2. What is the role of data dictionary in DBMS architecture?

A data dictionary contains a list of all files in the database, the number of records in each file,

and the names and types of each field. Data dictionaries do not contain any actual data from the

database, only book keeping information for managing it.

3. What is a data model?

Data Models are fundamental entities to introduce abstraction in DBMS. Data models define

how data is connected to each other and how it will be processed and stored inside the system.

4. Compare instance and schema of a database.

In DBMS, Schema is the overall Design of the Database. Instance is the information stored in the

Database at a particular moment.

5. Highlight the intention of ER-model in designing a database.

The whole purpose of ER modeling is to create an accurate reflection of the real world in a

database. It gives us an intermediate step from which it is easy to define a database.

6. What is weak entity set? Is it recommended to have a weak entity set in a relation?

An entity set is a set of entities of the same type that share the same properties. An entity set that

does not possess sufficient attributes to form a primary key is called a weak entity set. One that

does have a primary key is called a strong entity set.

RESULT:Thus the table was successfully created, altered, truncated, and dropped.

Ex.No:2. PERFORMING INSERTION, DELETION, MODIFYING, ALTERING,UPDATING AND VIEWING RECORDS BASED ON CONDITIONS.

AIM:To insert, select, update, modify and delete records in a table using DML commands.

DML COMMANDS:

COMMANDS OVERVIEW:

SELECT - retrieve data from the a databaseINSERT - insert data into a tableUPDATE - updates existing data within a tableDELETE - deletes all records from a table, the space for the records remain

SQL – SELECT FROM

Selecting all records from a table

SELECT * FROM EMPLOYE

Listing the selected records which satisfies the given condition from a table

SELECT * FROM EMPLOYE WHERE DEPTID=’DPT01’

SQL - INSERT INTO

Syntax: INSERT INTO tablename VALUES (value list)

Single-row insert

INSERT INTO DEPARTMENT VALUES (‘DPT02’,’TESTING’,’10-JAN-2012’)

Inserting one row, with values to the column in the given order

INSERT INTO DEPARTMENT (DEPTNAME, DEPTID) VALUES (‘DESIGN’, ‘DPT02’);

Inserting one or more rows with values from other tables.

INSERT INTO DEPARTMENT (DEPTID, DEPTNAME)

SELECT EMPID, EMPNAME FROM EMP WHERE MGRID=EMPID;

OTHER EXAMPLES:

INPUT::

SQL>INSERT INTO EMPLOYE VALUES (‘Emp121’,’Gayle’,’Testing’,’Emp01’,’01-Feb-2013’, ’Dpt01’, 32000);

OUTPUT: 1 row created.

INPUT::

SQL>INSERT INTO DEPARTMENT VALUES(‘&deptid,’&deptname’);

Enter value for deptid: Dpt01

Enter value for deptname: Development

OUTPUT:

old 1: Insert into department values(‘&deptid,’&deptname’)

new 1: Insert into department values(‘Dpt01’,' Development’)

1 row created.

SQL - UPDATE

Syntax: UPDATE tablename SET COLUMN_NAME =value [ WHERE CONDITION]

INPUT::

SQL> UPDATE DEPT SET DOS=’01-JAN-2010’ WHERE DEPTID=’DPT01’;

1 row updated.

SQL - DELETE

Syntax: DELETE FROM tablename WHERE condition

INPUT::

SQL> DELETE FROM DEPARTMENT;

OUTPUT: 1 row deleted.

PRELAB QUESTIONS:

1. In which system table the structure of all tables will be stored.

USER_TABLES

2. In which relation the constraints of all tables will be stored.

USER_CONSTRAINTS

3. What is the role of DML compiler in the database architecture?

It translates DML statements in a query language into low-level instruction (Relational Algebra)

that the query evaluation engine can understand.

4. What is the objective of specifying primary key in a relation?

A table typically has a column or combination of columns that contain values that uniquely

identify each row in the table. This column, or columns, is called the primary key (PK) of the

table and enforces the entity integrity of the table. Because primary key constraints guarantee

unique data, they are frequently defined on an identity column.

When you specify a primary key constraint for a table, the Database Engine enforces data

uniqueness by automatically creating a unique index for the primary key columns. This index

also permits fast access to data when the primary key is used in queries

RESULT:

Thus the table was successfully inserted, updated, select, and deleted.

Ex.No:3. CREATION OF VIEWS, SYNONYMS, SEQUENCE, INDEXES, SAVE POINT.

AIM:

To create save point, commit and rollback while using a transaction.

VIEWS

In SQL, a view is a virtual table based on the result-set of an SQL statement. A view

contains rows and columns, just like a real table. The fields in a view are fields from one or more

real tables in the database.

A view is an object that gives the user the logical view of data from the underlying table.

Any relation that is not part of the logical model but is made visible to the user as a virtual

relation is called a view. They are generally used to avoid duplication of data. Views are created

for the following reasons,

Data simplicity

To provide data security

Structural simplicity (because view contains only limited number of rows and

columns)

TYPES OF VIEWS

Updatable views – Allow data manipulation

Read only views – Do not allow data manipulation

SQL create view

CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE

condition

SQL updating a view

Update view name set field name=value where condition

SQL create or replace view

CREATE OR REPLACE VIEW view_name AS SELECT column_name(s) FROM table_name

WHERE condition.

SQL drop view

DROP VIEW view-name;

INDEXES

Indexes are special lookup tables that the database search engine can use to speed up data

retrieval. An index is a pointer to data in a table. An index in a database is very similar to an

index in the back of a book. An index helps speed up SELECT queries and WHERE clauses, but

it slows down data input, with UPDATE and INSERT statements. Indexes can be created or

dropped with no effect on the data. Index in sql is created on existing tables to retrieve the rows

quickly. When there are thousands of records in a table, retrieving information will take a long

time. When an index is created, it first sorts the data and then it assigns a ROWID for each row.

An index can be created in a table to find data more quickly and efficiently.

The users cannot see the indexes, they are just used to speed up searches/queries

Syntax to create Index

CREATE INDEX index_name ON table_name (column_name1,column_name2...);

Syntax to create SQL unique index

CREATE UNIQUE INDEX index_name ON table_name (column_name1, column_name2...);

index_name is the name of the INDEX.

table_name is the name of the table to which the indexed column belongs.

column_name1, column_name2.. is the list of columns which make up the INDEX.

The Drop Index Command

An index can be dropped using SQL DROP command. Care should be taken when dropping an

index because performance may be slowed or improved.

DROP INDEX index_name;

Examples:

SQL> create table persons (first name varchar (20), last name varchar(10));

Table created;

SQL> create index plndex on persons (last name); Index created.

SQL> select * from persons; No rows selected.

SQL> drop plndex on persons;

Drop index plndex on persons

* ERROR at line1:

ORA_00950: Invalid DROP option

SEQUENCE

A sequence is a user-defined schema bound object that generates a sequence of numeric

values according to the specification with which the sequence was created. The sequence of

numeric values is generated in an ascending or descending order at a defined interval and can be

configured to restart (cycle) when exhausted. Sequences, unlike identity columns, are not

associated with specific tables. Applications refer to a sequence object to retrieve its next value.

The relationship between sequences and tables is controlled by the application. User applications

can reference a sequence object and coordinate the values across multiple rows and tables.

SYNTAX

CREATE SEQUENCE sequence_name

MINVALUE value

MAXVALUE value

START WITH value

INCREMENT BY value

CACHE value;

Drop Sequence: Syntax: DROP SEQUENCE sequence_name

Examples:

SQL> create table supplier2 (supplierid number (10), supplier name varchar (20));

Table created.

SQL>insert into supplier2 values (10,‟ganesh‟);

1 row created.

SQL> select * from supplier2;

SUPPLIER ID SUPPLIERNAME

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

10 ganesh

SQL> create sequence supplier2_seq2

2 MINVALUE 1

3 STARTWITH 1

4 INCREMENT BY 1

5 CACHE 20

Sequence created.

SQL> insert into supplier2 (supplier id, supplier name) values

(supplier2_seq.NEXTVAL,‟Kraftfoods‟);

1 row created.

SQL> select*from supplier2;

SUPPLIERID SUPPLIERNAME

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

10 ganesh

1 Kraftfoods

SQL> insert into supplier2 (supplier id, supplier name) values

(supplier2_seq.NEXTVAL,‟parle‟); 1 row created.

SQL> select*from supplier2;

SUPPLIERID SUPPLIERNAME

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

10 ganesh

1 Kraftfoods

2 Parley

SQL> select*from supplier2_seq2*;

Error at line1:

ORA-00942: table or view does not exist;

TRANSACTION CONTROL LANGUAGE

COMMANDS OVERVIEW

COMMIT - save work done & it is visible to other users.

SAVEPOINT - identify a point in a transaction to which you can later roll back

ROLLBACK - restore database to original since the last COMMIT

SET TRANSACTION - Change transaction options like what rollback segment to use

SAVEPOINT

Syntax: savepoint username;

INPUT::

SQL> savepoint emp;

Output:

savepoint created;

COMMIT

Syntax: commit;

INPUT::

SQL> commit;

Output:

Commit complete.

ROLLBACK

Syntax:

rollback to savepoint_text_identifier;

INPUT::

SQL> rollback to emp;

Output:

Rollback complete.

SYNONYMS

Synonym is an alternative name for a table, view, sequence, operator, procedure, stored

function, package, materialized view, Java class schema object, user-defined object type, or

another synonym. A synonym places a dependency on its target object and becomes invalid if the

target object is changed or dropped.

CREATE SYNONYM offices FOR

hr.locations;

PRELAB QUESTIONS:

1. What is mean by transaction?

A transaction is a logical unit that is independently executed for data retrieval or updates. In

relational databases, database transactions must be atomic, consistent, isolated and durable

summarized as the ACID acronym.

2. When the updated records will be visible to other users?

The changes (Insertion, deletion or updation) performed by the user will be highlighted to other

user only after performing commit operation.

3. Can the deleted records be recovered using rollback command?

It can be recovered if commit operation was not performed.

4. What is savepoint in Oracle?

The SAVEPOINT statement names and marks the current point in the processing of a

transaction. With the ROLLBACK TO statement, savepoints undo parts of a transaction instead

of the whole transaction.

5. What is the role of buffer manager in DBMS architecture?

A DBMS must manage a huge amount of data, and in the course of processing the required space

for the blocks of data will often be greater than the memory space available. For this there is the

need to manage a memory in which to load and unload the blocks. The buffer manager is

responsible primarily for managing the operations inherent saving and loading of the blocks.

RESULT:

Thus the table was successfully saved, committed and rollback.

Ex.No:4. CREATING AN EMPLOYEE DATABASE TO SET VARIOUSCONSTRAINTS

AIM

To create an Employee database with various constraints.

DESCRIPTION:

SQL CONSTRAINTS

Constraints are the rules enforced on data columns on table. These 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 database.

Constraints could be column level or table level. Column level constraints are applied only to

one column, whereas table level constraints are applied to the whole table.

Following are commonly used constraints available in SQL.

NOT NULL Constraint: Ensures that a column cannot have NULL value.

UNIQUE Constraint: Ensures that all values in a column are different.

PRIMARY Key: Uniquely identified each rows/records in a database table.

FOREIGN Key: Uniquely identified a rows/records in any another database table.

CHECK Constraint: The CHECK constraint ensures that all values in a column satisfy

certain conditions.

SAMPLE OUTPUT:

SQL> CREATE TABLE EMPLOYEE (EMP_NO NUMBER (6) NOT NULL, NAME

VARCHAR2 (10), BRANCH VARCHAR2 (6));

Table created.

SQL> DESC EMPLOYEE;

Name Null? Type

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

EMP_NO NOT NULL NUMBER (6)

NAME VARCHAR2 (10)

BRANCH VARCHAR2 (6)

SQL> INSERT INTO EMPLOYEE VALUES (&EMP_NO,'&NAME','&BRANCH');

Enter value for emp_no: 501

Enter value for name: ABHILASH

Enter value for branch: CHENNAI

old 1: INSERT INTO EMPLOYEE VALUES(&EMP_NO,'&NAME','&BRANCH')

new 1: INSERT INTO EMPLOYEE VALUES(501,'ABHILASH', „CHENNAI‟)

1 row created.