Dbms Practical File

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

DB MS L AB
(KCS-551)

Ambalika Institute of Management and Technology, Lucknow

Name of Student: Tushar Sonker


Roll No: 2003630100163 Branch: C.S.E Session:
KCS-551 Database Management Systems Lab

Objectives :

1. Installing oracle/ MYSQL


2. Creating Entity-Relationship Diagram using case tools.
3. Writing SQL statements Using ORACLE /MYSQL:
a)Writing basic SQL SELECT statements.
b) Restricting and sorting data.
c)Displaying data from multiple tables.
d)Aggregating data using group function.
e)Manipulating data.
e)Creating and managing tables.
4. Normalization
5. Creating cursor
6. Creating procedure and functions
7. Creating packages and triggers
8. Design and implementation of payroll processing system
9. Design and implementation of Library Information System
10. Design and implementation of Student Information System
11. Automatic Backup of Files and Recovery of Files
INDEX

SL NAME OF LAB EXPERIMENT DATE SIGN REMARK


1 Installing oracle/ MYSQL
2 Creating Entity-Relationship Diagram
using case tools.
3 Writing SQL statements Using ORACLE
/MYSQL:
3-A Writing basic SQL SELECT statements.
3-B Restricting and sorting data.
3-C Displaying data from multiple tables.
3-D Aggregating data using group function.
3-E Manipulating data.
3-F Creating and managing tables.
4 Normalization
5 Creating cursor
6 Creating procedure and functions
7 Creating packages and triggers
Appendices
I. Institute Vision
II. Institute Mission
III. CSE Department Vision
IV CSE Department Mission
V CSE Department PEOs
VI Program Outcomes (POs)

KCS-551: Database Management Systems Lab


PRACTICAL-1
Objective: Installing ORACLE/ MYSQL

I. Installing Oracle 10g database software :


1. Insert Oracle CD , the autorun window opens automatically. If you are installing from
network or hard disk, click setup.exe in the installation folder.
2. The Oracle Universal Installer (OUI) will run and display the Select Installation
MethodWindow.

3. Choose Basic Installation:


Select this option to quickly install Oracle Database 10g. This method requires minimal user
input. It installs the software and optionally creates a general-purpose database based on the
information you provide.
For basic installation, you specify the following:
Oracle Home Location — Enter the directory in which to install the Oracle Database 10g
software. You must specify a new Oracle home directory for each new installation of Oracle
Database 10g. Use the default value, which is :
c:\oracle\product\10.2.0\db_1

Installation Type — Select Enterprise Edition :


If you have limited space, select standard edition. Personal edition installs the same software
as the Enterprise Edition, but supports only a single-user development and deployment
environment.
Create Starter Database — Check this box to create a database during installation. Oracle
recommends that you create a starter database for first Create Starter Database — time
installations. Choose a Global Database Name, like cs157b, or just use the default value.
Type a password. Don’t lose this password, since you will need it to connect to the database
server.
Click next
4. The Product-Specific Prerequisite Checks window appears: Click next

5. A summary screen appears showing information such as your global settings, space
requirements and the new products to be installed. Click Install to start the installation..
6. The Install window appears showing installation progress.

7. At the end of the installation phase, the Configuration Assistants window appears. This
window lists the configuration assistants that are started automatically.
If you are creating a database, then the Database Configuration Assistant starts automatically
in a separate window.
At the end of database creation, you are prompted to unlock user accounts to make the
accounts accessible. The SYS and SYSTEM accounts are already unlocked. Click OK to
bypass password management.

PRACTICAL-2

Objective: Creating Entity-Relationship Diagram using CASE tools

An entity relationship diagram (ERD) shows the relationships of entity sets stored in a
database. An entity in this context is a component of data. In other words, ER diagrams
illustrate the logical structure of databases.
At first glance an entity relationship diagram looks very much like a flowchart. It is the
specialized symbols, and the meanings of those symbols, that make it unique.
An ER diagram is a means of visualizing how the information a system produces is
related. There are five main components of an ERD:

• Entities, which are represented by rectangles. An entity is an object or concept about

which you want to store information.


• A weak entity is an entity that must defined by a foreign key relationship with

anotherentity as it cannot be uniquely identified by its own attributes


alone.
• Actions, which are represented by diamond shapes, show how two entities share

information in the database. In some cases, entities can be


self linked. For example, employees can supervise other employees.

• Attributes, which are represented by ovals. A key attribute is the unique,


distinguishing characteristic of the entity. For example, an employee's social security
number might be the employee's key attribute.

A multivalued attribute can have more than one value. For

example, an employee entity can have multiple skill values. A


derived attribute is based on another attribute. For example, an employee's monthly

salary is based on the employee's annual salary.


• Connecting lines, solid lines that connect attributes to show the relationships of
entities in the diagram.
• Cardinality specifies how many instances of an entity relate to one instance of
another entity. Ordinality is also closely linked to cardinality. While cardinality specifies
the occurrences of a relationship, ordinality describes the relationship as either
mandatory or optional. In other words, cardinality specifies the maximum number of
relationships and ordinality specifies the absolute minimum number of relationships.
• There are many notation styles that express cardinality.
Information Engineering Style:

PRACTICAL-3
Objective: Writing SQL statements Using ORACLE /MYSQL

SQL is nonprocedural language for accessing a database. You run SQL statements commands
to perform various tasks, such as retrieving data from tables in Oracle Database XE. The SQL
language automatically handles how to navigate the database and perform the desired task. All
database operations are performed using SQL statements.

With SQL statements you can perform the following:

• Query, insert, and update data in tables


• Format, perform calculations on, store, and print from query results
• Examine table and object definitions

Oracle SQL statements are divided into several categories:


• Data Manipulation Language (DML) statements
These statements query, insert, update, and delete data in tables.
• Transaction Control statements
These statements commit or roll back the processing of transactions. A group of
changes that you make is referred to as a transaction.
• Data Definition Language (DDL) statements
These statements create, alter, and drop database objects.

Running SQL Statements:


You can enter and run SQL statements with the SQL Commands page, Script Editor page, or
SQL Command Line (SQL*Plus).
Using the SQL Commands and Script Editor pages are described in this section. The SQL
Commands page is a simpler interface and easier to use.
Both SQL Commands and Script Editor pages enable you to save your SQL statements as a
script file in a database repository for future use. You can run multiple SQL statements in the
Script Editor page. Script Editor also enables you to download the script to the local file
system, which can be run as a SQL script with SQL Command Line. For information about
running SQL statements or SQL scripts with SQL Command Line.

Running SQL Statements on the SQL Commands Page:

To enter and run SQL statements in the SQL Commands page:


1. Log in to the Database Home Page. See "Logging in to the Database Home Page".
To run the examples, log in as user HR with your password for the HR account.
2. On the Database Home Page, click the SQL icon to display the SQL page.
3. Click the SQL Commands icon to display the SQL Commands page.
4. On the SQL Commands page, enter the SQL statements. Note that SQL statements
are terminated with a semi colon (;) in the examples. The semi colon is required when
running the SQL statements in a SQL script or at the SQL Command Line prompt, but
it is optional on the SQL Commands page.
5. Select (highlight) the SQL statement that you want to run, then click Run to run the
statement and display the results.
6. If you want to save the SQL statements for future use, click the Save button.
7. In the Name field, enter a name for the saved SQL statements. You can also enter
an optional description. Click the Save button to save the SQL statement.
8. To access saved SQL statements, click the Saved SQL tab and select the name of
the saved SQL statement that you want to access.

PRACTICAL-3-A

Objective: Writing SQL DDL statements:

I. CREATE TABLE:
Specifies a new base relation by giving it a name, and specifying each of its attributes and their
data types

Syntax of CREATE Command:

CREATE TABLE <table name>( <Attribute A1><Data Type D1> [< Constarints>],
<Attribute A2><Data Type D2> [< Constarints>], ……….,
[<integrity-constraint1>, <integrity-constraint k> ] );

SQL Query:

II. DROP TABLE:


It is used to remove a relation (base table) and its definition. The relation can no
longer be used in queries, updates, or any other commands since its description no
longer exists
Syntax of DROP Command:

DROP TABLE <tablename>;

SQL

III. RENAMING TABLES

To rename the table,the syntax is:


Syntax:
RENAME oldtablename TO newtablename;
SQL Query :
IV. ALTER TABLE:
It is used to add an attribute to/from one of the base relations, drop constraint. The new
attribute will have NULLs in all the tuples of the relation right after the command is
executed; hence, the NOT NULL constraint is not allowed for such an attribute.

Syntax of ALTER Command:

A. Adding New Columns:

Syntax:
ALTER TABLE tablename
ADD(newcolumn datatype(size), newcolumnname datatype(size)....);

SQL Query:

B. Modifying Existing Columns:

Syntax:
ALTER TABLE tablename MODIFY (columnnamme newdatatype(newsize));

SQL Query:

C. Drop a Column:

Syntax:
ALTER TABLE tablename DROP columnname;

SQL Query:

Restrictions on the ALTER TABLE:

Using the ALTER TABLE clause the following tasks cannot be performed:
-Change the name of the table.
-Change the name of the column.
-Decrease the size of a column if table data exists.

V. Examining Object Created By A User:

To determine which tables the user has access to the syntax is :


Syntax:
SELECT*FROM TAB;

PRACTICAL-3-B

Objective: Restricting and sorting data:

❖ The essential capabilities of SELECT statement are Selection, Projection and Joining.
❖ Displaying specific columns from a table is known as a project operation.
❖ Displaying specific rows of output is known as a select operation. Specific rows can be
selected by adding a WHERE clause to a SELECT query. The WHERE clause appears
just after the FROM clause in SELECT query.
In the syntax,
• WHERE clause is the keyword
• [condition] contains column names, expressions, constants, literals and a
comparison operator.
• A SELECT clause can contain only one WHERE clause. However, multiple
filter conditions can be appended to WHERE clause using AND or OR operator.
• The columns, literals or expressions in a predicate clause must be of similar or
interconvertible data types.
• Column alias cannot be used in the WHERE clause.
• Character literals must be enclosed within single quotation marks and are case
sensitive.
• Date literals must be enclosed within single quotation marks and are format
sensitive. Default format is DD-MON-RR.

❖ Comparison Operators
Comparison operators are used in predicates to compare one term or operand with another
term. SQL offers comprehensive set of equality, inequality and miscellaneous operators.
Oracle has nine comparison operators to be used in equality or inequality conditions.

OperatorMeaning

= equal to

< less than

> greater than

>= greater than or equal to

<= less than or equal to

!=not equal to
<>not equal to

❖ Other Oracle operators are BETWEEN..AND, IN, LIKE, and IS NULL.

Logical Operations:

Logical operations that can be used in SQL sentence are:

❖ The AND Operator:

Example:

1. Retrieve the contents of the columns product_no, description, profit_percent, sell_price from
the table product_master where the values contained in the field profit_percent is between 10
and 20 both inclusive
SELECT product_no, description, profit_percent, sell_price
FROM product_master
WHERE profit_percent >=10 AND profitpercent <=20;

❖ The OR Operator:

The oracle engine will process all rows process all rows in a table and display the result only
when any of the conditions specified using the Or operator are satisfied

Example:

Retrieve client information like client_no, name, address1, address2, city and pincode for all
the clients where the field pincode has the value 400054 OR 400057;

SELECT client_no, name, address1, address2, city, pincode


FROM client_master
WHERE (pincode = 400054 OR pincode = 400057);

❖ THE NOT Operator:

The oracle will process all rows in a table and display the result only when none of conditions
specified using the Not operator are satisfied

Example

Retrieve specified client information for the clients who are Not in ‘Bombay’ OR ‘Delhi’
SELECT client_no, name, address1,address2, city, pincode
FROM client_master WHERE NOT (city = ‘Bombay’ or city =’Delhi’);

❖ Pattern Matching:

The use of the LIKE predicate


The Like predicate allows for a comparison of one string value with another string value,
which is not identical This is achieved by using wildcard characters. Two wildcard character
that are available are:
For character data types: The percent sign(%) matches any string
The Underscore (_) matches any single character

Example:

Retrieve all information about suppliers whose names begin with th letter ‘ja’ from
supplier_master
SELECT * FROM supplier_master
WHERE supplier_name LIKE ‘ja%’

❖ THE IN and NOT IN predicate:

The arithmetic operator (=) campares a single value to another single value In case a value
needs to be campared to a list of value then the IN predicate is used.One can check a single
value against multiple values by using tha predicate.

❖ The ORDER BY Clause:

The ORDER BY clause is used to sort the tuples in a query result based on the values of some
attribute(s)
Example:
Retrieve a list of employees and the projects each works in, ordered by the employee's
department, and within each department ordered alphabetically by employee last name.

SELECT DNAME, LNAME, FNAME, PNAME


FROM DEPARTMENT, EMPLOYEE, WORKS_ON, PROJECT
WHERE DNUMBER=DNO AND SSN=ESSN AND PNO=PNUMBER
ORDER BY DNAME, LNAME;

The default order is in ascending order of values. We can specify the keyword DESC if we
want a descending order; the keyword ASC can be used to explicitly specify ascending order,
even though it is the default.
Ex: ORDER BY DNAME DESC, LNAME ASC, FNAME ASC

PRACTICAL-3-C

Objective: Displaying data from multiple tables.:

The related tables of a database are linked through the use of foreign and primary keys. The
ability to join tables will enable you to add more meaning to the result table that is produced.
For 'n' number tables to be joined in a query, minimum (n-1) join conditions are necessary.
Based on the join conditions, Oracle combines the matching pair of rows and displays the one
which satisfies the join condition.

Joins are classified as below

• Natural join (also known as an equijoin or a simple join) - Creates a join by


using a commonly named and defined column.

• Non-equality join - Joins tables when there are no equivalent rows in the tables
to be joined-for example, to match values in one column of a table with a range of
values in another table.

• Self-join - Joins a table to itself.

• Outer join - Includes records of a table in output when there's no matching


record in the other table.

• Cartesian join (also known as a Cartesian product or cross join) - Replicates


each row from the first table with every row from the second table.Creates a join
between tables by displaying every possible record combination.

• Natural Join
The NATURAL keyword can simplify the syntax of an equijoin.A NATURAL JOIN is
possible whenever two (or more) tables have columns with the same name,and the columns
are join compatible, i.e., the columns have a shared domain of values.

• Self Join
A SELF-JOIN operation produces a result table when the relationship of interest exists
among rows that are stored within a single table. In other words, when a table is joined to
itself, the join is known as Self Join.
• Non Equijoins
A non-equality join is used when the related columns can't be joined with an equal sign-
meaning there are no equivalent rows in the tables to be joined.A non-equality join enables
you to store a range's minimum value in one column of a record and the maximum value in
another column.

• Outer Joins
An Outer Join is used to identify situations where rows in one table do not match rows in a
second table, even though the two tables are related.

There are three types of outer joins: the LEFT, RIGHT, and FULL OUTER JOIN.

• Right Outer Join


A RIGHT OUTER JOIN adds back all the rows that are dropped from the second (right)
table in the join condition, and output columns from the first (left) table are set to NULL.

• Left Outer Join

A LEFT OUTER JOIN adds back all the rows that are dropped from the first (left) table in
the join condition, and output columns from the second (right) table are set to NULL. The
query demonstrated above can be used to demonstrate left outer join, by exchanging the
position of (+) sign.

• Full Outer Join


The FULL OUTER JOIN adds back all the rows that are dropped from both the tables.
Below query shows lists the employees and their departments. Note that employee 'MAN' has
not been assigned any department till now (it's NULL) and department 30 is not assigned to
any employee.

• Cartesian product or Cross join


For two entities A and B, A * B is known as Cartesian product. A Cartesian product consists
of all possible combinations of the rows from each of the tables.

PRACTICAL-3-E

Objective: Manipulating data:

❖ SELECT OPERATION:
The SELECT in SQL is used to select rows from table.

SELECT columnname1, columnname2,…. FROM tablename;

❖ INSERT OPERATION:

The INSERT in SQL is used to insert rows into table.

INSERT INTO tablename (columnname1, columnname2,…. ) VALUES


(expr1,expr2,…);

❖ DELETE OPERATIONS:

The verb DELETE in SQL is used to remove rows from table. To remove
All the rows from a table

• Removal of All Rows:

Syntax:
DELETE FROM tablename;

• Removal of a specified Rows:

Syntax:
DELETE FROM tablename WHERE search condition;

❖ UPDATING THE CONTENTS OF A TABLE:

The update command is used to change or modify data values in a table. To update
All the rows from a table

• UPDATING of ALL Rows:

Syntax:
UPDATE tablename
SET columnname =expression, columnname = expression;

• UPDATING records conditionally:


Syntax:
UPDATE tablename
SET columnname = expression, columnname = expression...
WHERE columnname = expression;

PRACTICAL-3-F

Objective: Creating and managing tables:

Tables are the basic units of data storage in Oracle Database Express Edition. Tables hold
all user-accessible data. Each tablecontains rows that represent individual data records.
CREATE TABLE Persons
(
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

PRACTICAL-4

Objective: Normalization:

Normalization of Database:

Database Normalization is a technique of organizing the data in the database. Normalization is


a systematic approach of decomposing tables to eliminate data redundancy(repetition) and
undesirable characteristics like Insertion, Update and Deletion anomalies. It is a multi-step
process that puts data into tabular form, removing duplicated data from the relation tables.
Normalization is used for mainly two purposes,

• Eliminating redundant (useless) data.


Normalization Rule:
Normalization rules are divided into the following normal forms:

1. First Normal Form


2. Second Normal Form
3. Third Normal Form
4. BCNF
5. Fourth Normal Form
6. Fifth Normal Form

• First Normal Form (1NF):


For a table to be in the First Normal Form, it should follow the following 4 rules:

1. It should only have single(atomic) valued attributes/columns.


2. Values stored in a column should be of the same domain
3. All the columns in a table should have unique names.
4. And the order in which data is stored, does not matter.

• Second Normal Form (2NF):


For a table to be in the Second Normal Form,

1. It should be in the First Normal form.


2. And, it should not have Partial Dependency.

• Third Normal Form (3NF):


A table is said to be in the Third Normal Form when,

1. It is in the Second Normal form.


2. And, it doesn't have Transitive Dependency.

• Boyce and Codd Normal Form (BCNF):


Boyce and Codd Normal Form is a higher version of the Third Normal form. This form
deals with certain type of anomaly that is not handled by 3NF. A 3NF table which does not
have multiple overlapping candidate keys is said to be in BCNF. For a table to be in BCNF,
following conditions must be satisfied:

• R must be in 3rd Normal Form


• and, for each functional dependency ( X → Y ), X should be a super Key.

• Fourth Normal Form (4NF):


A table is said to be in the Fourth Normal Form when,

1. It is in the Boyce-Codd Normal Form.


2. And, it doesn't have Multi-Valued Dependency.
PRACTICAL-5

Objective: Creating cursor:

A Cursor is a pointer to this context area. Oracle creates context area for processing an SQL
statement which contains all information about the statement.PL/SQL allows the programmer
to control the context area through the cursor. Acursor holds the rows returned by the SQL
statement.
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;
/

PRACTICAL-6

Objective: Creating procedure and functions:

The SQL CREATE FUNCTION statement is used tocreate stored functions that are stored
in an Oracledatabase. A procedure or function is similar to a miniature program. It has an
optional declarative part, an executable part, and an optional exception-handling part.
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
dbms_output.put_line('Hello World!');
END;
/

PRACTICAL-7

Objective: Creating packages and triggers:

• Creating triggers:
Triggers provide a way of executing PL/SQL code on the occurrence of specific database
events. For example, it can be used to maintain an audit log by setting triggers to fire when
insert or update operations are carried out on a table. The insert and update triggers add an
entry to an audit table whenever the table is altered.

CREATE OR REPLACE PACKAGE TRIGGER_PACKAGE AS


PROCEDURE MY_TRIGGER_PROC;
END TRIGGER_PACKAGE;

CREATE OR REPLACE PACKAGE BODY TRIGGER_PACKAGE AS


PROCEDURE MY_TRIGGER_PROC IS
BEGIN
DBMS_OUTPUT.PUT_LINE('TRIGGER_PACKAGE.MY_TRIGGER_PROC invoked');
END MY_TRIGGER_PROC;
END trigger_package;

CREATE OR REPLACE TRIGGER MY_TABLE_AIUD


AFTER INSERT UPDATE DELETE ON MY_TABLE
FOR EACH ROW
BEGIN
TRIGGER_PACKAGE.MY_TRIGGER_PROC;
END MY_TABLE_AIUD;

• Creating packages:

Packages are PL/SQL constructs that enable the grouping of related PL/SQL objects, such as
procedures, variables, cursors, functions, constants, and type declarations.

A package can have two parts: a specification and a body. The specification defines a list of
all objects that are publicly available to the users of the package

CREATE OR REPLACE PACKAGE c_package AS


-- Adds a customer
PROCEDURE addCustomer(c_id customers.id%type,
c_name customers.Name%type,
c_age customers.age%type,
c_addr customers.address%type,
c_sal customers.salary%type);
PROCEDURE delCustomer(c_id customers.id%TYPE);
--Lists all customers
PROCEDURE listCustomer;

END c_package;
/
Output Package created.

You might also like