0% found this document useful (0 votes)
12 views

DBms

The document discusses a database management systems lab manual. It covers concepts like the entity relationship model, relational model, SQL, normalization, and database experiments including designing schemas, querying, triggers, and procedures.

Uploaded by

m10k4tmgw5
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

DBms

The document discusses a database management systems lab manual. It covers concepts like the entity relationship model, relational model, SQL, normalization, and database experiments including designing schemas, querying, triggers, and procedures.

Uploaded by

m10k4tmgw5
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

DATABASE MANAGEMENT SYSTEMS

LABMANUAL
Co-requisites: “Database Management Systems”

Course Objectives:
Introduce ER data model, database design and normalization Learn SQL basics for
data definition and data manipulation
Course Outcomes:
● Design database schema for a given application and apply normalization
● Acquire skills in using SQL commands for data definition and data manipulation.
● Develop solutions for database applications using procedures, cursors and triggers

List of Experiments: 1. Concept design with E-R Model


2. Relational Model
3. Practicing DDL commands
4. Practicing DML commands
5. NORMALIZATION
6. A. Querying (using ANY, ALL, UNION, INTERSECT, JOIN, Constraints etc.)
B. Nested, Correlated subqueries
7. Queries using Aggregate functions, GROUP BY, HAVING and Creation and
dropping of Views. 8. Triggers (Creation of insert trigger, delete trigger, update trigger)
8. Procedures
10. Usage of Cursors
EXP-1:Concept designwith E-RModel
 Entity relationship data model allows us to o describe the data involved in a real
worldenterprise in terms of objects and their relationships and is widely used to develop an
initialdatabase design.
 It isa graphicaluserrepresentationofthelogicalstructureofdatabase.
 Ithelpsyoutoidentifytheentitieswhichexistinasystemandtherelationshipsbetweenthoseentities.
 ERdiagramscanbeusedbydatabasedesignersasablueprintforimplementingdatainspecificsoftware
applications
 Thedatabasedesignergainsabetterunderstandingoftheinformationtobecontainedinthedatabase
withthehelpofERPdiagram
 ERDisallowedyoutocommunicatewiththelogicalstructureofthedatabasetousers

ComponentsoftheERDiagramEnt

ity:
An entity is a thing or object in the real world that is distinguishable from all other
objects.Anentitycan beplace,person,object,event oraconcept,whichstoresdatainthedatabase.
Examplesofentities:
 Person:Employee,Student,Patient
 Place:Store,Building
 Object:Machine,product,andCar
 Event:Sale,Registration,Renewal
 Concept:Account,Course

Entity set:
Anentitysetisasetofentitiesofthesametypethatsharethesameproperties.
Example:setofallpersons,companies,trees,holidays.
Attributes:
Entitiesarerepresentedbymeansoftheirproperties, calledattributes.Allattributeshavevalues.
Example:astudententitymayhavename, class,ageasattributes.
Thereexitsdomainrangevaluesthatcanbeassignedtoattributes.
Example: a student’s name cannot be a numeric value. It has to be alphabetic. A
student’sage cannotbenegative,etc.
Simple attribute – Simple attributes are atomic values, which cannot be divided further.
Forexample,a student’sphonenumberisanatomicvalue of10digits.
Composite attribute – Composite attributes are made of more than one simple attribute.
Forexample,a student’scomplete namemayhavefirst_name andlast_name.
Derivedattribute–
Derivedattributesaretheattributesthatdonotexistinthephysicaldatabase,buttheirvaluesarederivedfrom
otherattributespresentinthedatabase.Forexample,average_salary in a department should not be
saved directly in the database, instead it can bederived.Foranotherexample,age canbe
derivedfromdata_of_birth.
Single-valueattribute–Singlevalueattributescontainsinglevalue.Forexample–
social_Security_Number.
Multivalued attribute – Multivalued attributes may contain more than one values. For example,a
personcanhavemorethanone phonenumber,email_address,etc.

Key: Key is an attribute or collection of attributes that uniquely identifies an entity among
entityset.Forexample,theroll_number ofastudentmakeshim/heridentifiableamong students.
Therearemainlythreetypesofkeys:
SuperKey −Asetofattributes(oneormore) thatcollectivelyidentifiesanentityinanentityset.
Candidate Key − A minimal super key is called a candidate key. An entity set may have
morethanonecandidatekey.
Primary Key − A primary key is one of the candidate keys chosen by the database designer
touniquelyidentifytheentityset.

Relationship:
Relationship is nothing but an association among two or more entities. E.g., Tom works in
theChemistrydepartment.

RelationshipSet:Asetofrelationshipsofsimilartypeiscalledarelationshipset.Likeentities,arelationshi
p toocanhave attributes.These attributesare called descriptive attributes.
Degree of Relationship: The number of participating entities in a relationship defines the
degreeoftherelationship.
MappingCardinalities
Cardinality defines the number of entities in one entity set, which can be associated with
thenumberofentitiesofothersetviarelationshipset.
TypesofCardinalities
One-to-one:OneentityfromentitysetAcanbeassociated withatmost
oneentityofentitysetBandviceversa.

One-to-
many:OneentityfromentitysetAcanbeassociatedwithmorethanoneentitiesofentitysetBhoweveranent
ityfromentitysetB,canbe associatedwithatmostoneentity

Many to One: More than one entities from entity set A can be associated with at most one entityof
entity set B, however an entity from entity set B can be associated with more than one
entityfromentitysetA.

Many to Many: One entity from A can be associated with more than one entity from B and
viceversa.
ER-DiagramSymbols/Notations

Entity

Weak Entity

Relationship

Link attributes to entity sets and


entitysetstorelationship

MultivaluedAttribute

Derived Attribute

WeakRelationships

KeyAttributes

Totalparticipationofanentityset

One-to-oneassociation

One-to-manyassociation

Many-to-Manyassociation

Partiallyoptionalassociation
FullyOptionalassociation
ERDiagramforStudentdatabase
EXP-02:Relational Model

The relational model represents the database as a collection of relations.A relation is nothing but a
table of values. Every row in the table represents a collection of related data values. These rows in the table
denote a real-world entity or relationship.
Relational Model Concepts
 Attribute: Each column in a Table. Attributes are the properties which define a
relation.e.g.,Student_Rollno, NAME,etc.
 Tables: In the Relational model the, relations are saved in the table format. It is stored along with its
entities. A table has two properties rows and columns. Rows represent records and columns represent
attributes.
 Tuple:It is nothing but a single row of a table,which contains a single record.
 Relation Schema:A relation schema represents the name of the relation with its attributes.
 Degree:The total number of attributes which in the relation is called the degree of the relation.
 Cardinality :Total number of rows present in the Table.
 Column:The column represents the set of values for a specific attribute.
 Relation instance: Relation instance is a finite set of tuples in the RDBMS system. Relation instances
never have duplicate tuples.
 Relation key:Every row has one,two or multiple attributes,which is called relation key.
 Attribute domain :Every attribute has some pre-defined value and scope which is known as attribute
domain
Operations in Relational Model
Four basic update operations performed on relational database model are
Insert, update, delete and select.
 Insert is used to insert data into the relation
 Delete is used to delete tuples from the table.
 Modify allows you to change the values of some attributes in existing tuples.
 Select allows you to choose a specific range of data.

Insert Operation
The insert operation gives values of the attribute for a new tuple which should be inserted into a relation.

Update Operation
You can see that in the below-given relation table CustomerName='Apple' is updated from Inactive to Active.
Delete Operation
To specify deletion,a condition on the attributes of the relation selects the tuple to be deleted.

In the above-given example, CustomerName="Apple"is deleted from the table.


The Delete operation could violate referential integrity if the tuple which is deleted is referenced by foreign keys from
other tuples in the same database.
Select Operation

In the above-given example, CustomerName="Amazon"is selected

Advantages of using Relational model


 Simplicity: A relational data model is simpler than the hierarchical and network model.
 Structural Independence:The relational database is only concerned with data and not with a structure.
This can improve the performance of the model.
 Easy to use: The relational model is easy as tables consisting of rows and columns is quite natural and
simple to understand
 Query capability: It makes possible for a high-level query language like SQL to avoid complex
database navigation.
 Data independence: The structure of a database can be changed without having to change any
application.
 Scalable: Regarding a number of records, or rows, and the number of fields, a database should be
enlarged to enhance its usability.
Disadvantages of using Relational model
 Few relational databases have limits on field lengths which can't be exceeded.
 Relational databases can sometimes become complex as the amount of data grows,and the relations
between pieces of data become more complicated.
 Complex relational database systems may lead to isolated databases where the information cannot be
shared from one system to another.
Relational Integrity constraints
Relational Integrity constraints is referred to conditions which must be present for a valid relation. These
integrity constraints are derived from the rules in the mini-world that the database represents.
There are many types of integrity constraints. Constraints on the Relational database management system
is mostly divided into three main categories are:
 Domain constraints
 Key constraints
 Referential integrity constraints
Domain Constraints
Domain constraints can be violated if an attribute value is not appearing in the corresponding domain or it
is not of theappropriatedata type.
Domain constraints specify that within each tuple, and the value of each attribute must be unique. This is
specified as data types which include standard data types integers, real numbers, characters, Booleans
,variable length strings, etc.
Example:
Create DOMAIN Customer
NameCHECK (value not NULL)
The example shown demonstrates creating a domain constraint such that CustomerName is not NULL

Key constraints
An attribute that can uniquely identify a tuple in a relation is called the key of the table. The value of the
attribute for different tuples in the relation has to be unique.
Example:
In the given table, CustomerID is a key attribute of Customer Table. It is most likely to have a single key
for one customer, CustomerID =1 is only for the CustomerName = "Google".

CustomerID CustomerName Status


1 Google Active
2 Amazon Active
3 Apple Inactive

Referential integrity constraints


Referential integrity constraints is base on the concept of Foreign Keys. A foreign key is an important
attribute of a relation which should be referred to in other relationships. Referential integrity constraint
state happens where relation refers to a key attribute of a differentor same relation. However, that key element
must exist in the table.
Example:

In the above example, we have 2 relations, Customer and Billing.

Tuple for CustomerID= 1 is referenced twice in the relation Billing. So we know CustomerName= Google
has billing amount $300
EXP-03:DDL commands
Data Definition Language (DDL) or Schema Definition Language, statements are used to define the database
structure or schema. These statements handle the design and storage of database objects.

CREATE:

CREATE DATABASE:

The CREATE DATABASE statement is used to create a new SQL database.

Syntax

CREATEDATABASE database name;


Example
The following SQL statement creates a database called "testDB":

CREATEDATABASE testDB;

CREATE TABLE:
The CREATETABLE statement is used to create a new table in a database.
Syntax
CREATE TABLE table_name
(column1datatype,
column2datatype,
column3datatype,
....
);

 The column parameters specify the names of the columns of the table.
 The datatype parameter specifies the type of data the column can hold (e.g. varchar, integer, date,
etc.).

Example
The following example creates a table called "Persons" that contains five columns: PersonID,
LastName, FirstName, Address, and City:

CREATE TABLE Persons


(PersonID int,
LastName
varchar(255),FirstName
varchar(255),Address
varchar(255),Cityvarcha
r(255)
);
DESC Statement (Describe Table):
SQL DESC statement use for describe the list of column definitions for specified table. You can
use either DESC or DESCRIBE statement.
Syntax:
Describe table_name

Example:
Describe persons;

Field Type Null Key Default Extra

PersonID int YES NULL

LastName varchar(255) YES NULL

FirstName varchar(255) YES NULL

Address varchar(255) YES NULL

City varchar(25) YES NULL

Field indicates the column name, Type is the data type for the column, NULL indicates whether
the column can contain NULL values, Key indicates whether the column is indexed, and Default
specifies the column's default value.Extra displays special information about columns:

ALTER TABLE:
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table. The
ALTERTABLE statement is also used to add and drop various constraints on an existing table.

ALTER TABLE-ADD Column


To add a column in a table.
Syntax:
ALTERTABLE table_name
ADD column_name datatype;

Example:
The following SQL adds an"Email"column to the"Persons"table:
ALTER TABLE Persons
ADDEmailvarchar(255);

Add MultipleColumnin table:


ALTERTABLE table_name
ADD ( column_name1
datatype[(size)],column_name2dat
atype[(size)],
...
);
ALTER TABLE-DROP COLUMN
It is used to delete a column in a table
Syntax:

ALTER TABLE
table_nameDROPCOLUMN
column_name;
Example:
The following SQL deletes the "Email" column from the "Persons" table:
ALTERTABLE Persons
DROPCOLUMN Email;

MODIFY EXISTING COLUMN IN TABLE


To change the datatype of a column in a table
Syntax:
ALTERTABLE table_name
MODIFYCOLUMN column_name datatype;

RENAME THE EXISTING COLUMN IN A TABLE


Syntax:
ALTERtable table_name change old_column_name new_column_name datatype;
Example:
ALTER table persons change city district varchar(50);
RENAME:
RENAME command is used to set a new name for any existing table.
Syntax(Rename Table):
RENAMETABLE old_table_name to new_table_name
Example:
RENAMETABLE persons to students_info;

The above query will rename the table student to students_info.

TRUNCATE:
It is used to delete all the rows from the table and free the space containing the table.
Syntax:
TRUNCATETABLE table_name;

Example:
TRUNCATETABLE Persons;

DROPTABLE/DATABASE
The DROP TABLE / DATABASE statement is used to drop an existing table in a database or a
database.
Syntax
DROPTABLE table_name;

Example
The following SQL statement drops the existing table "Person":
DROPTABLE Person;
EXP-4:DML Commands
 The SQL commands that deals with the manipulation of data present in the database belong
to DML or Data Manipulation Language and this includes most of the SQL statements.
 DML is responsible for all forms data modification in a database.

INSERT:
The insert statement is used to add new row to a table.
Syntax
INSERTINTOTABLE_NAME
(col1,col2, col3,......colN)
VALUES(value1,value2, value3, ....... valueN);
Or
INSERTINTOTABLE_NAME
VALUES(value1,value2, value3,....... valueN);
Example
Insert the values into the following table (person).
Sure, here is the content in a proper tabular format:
Field Type Null Key Default Extra

ID int NO NULL

NAME varchar(20) YES NULL

AGE int YES NULL

ADDRESS varchar(20) YES NULL

SALARY int YES NULL

INSERT into person values


(1,”ram”,32,”Chennai”,2000),(2,”sam”,28,”Hyd”,2500),(3,”Henry”,30,”Bangalore”,5000),(
4,”Adam”,29,”Pune”,6500),(5,”Alice”,25,”Delhi”,8500);
SELECT:
SELECT statement is used to fetch the data from a database table which returns this data in the
form of a result table. These result tables are called result-sets.
Syntax
SELECTcolumn1,column2,columnNFROM table_name;
Example

SELECT*FROM person

To fetch all the fields of the table,

To fetch selected fields (ID, NAME) of the table,

SELECT ID, NAMEFROM person

UPDATE
UPDATE Query is used to modify the existing records in a table. The WHERE clause with the
UPDATE query to update the selected rows, otherwise all the rows would be affected.

Syntax
UPDATEtable_name
SET column1=value1, column2=value2....... ,columnN=valueN
WHERE[condition];
Example
UpdatetheADDRESSforacustomerwhoseIDnumberis5inthetable.

UPDATE person SET ADDRESS=“LONDON”WHEREID=5;

Now, the PERSON table would have the following records,


To modify all the ADDRESS and the SALARY column values in the CUSTOMERS table, not
need to use the WHERE clause as the UPDATE query would be enough as shown in the
following code block.
UPDATE person SETADDRESS=“LONDON”,SALARY=5000;

Now, the PERSON table would have the following records,

DELETE
DELETE Query is used to delete the existing records from a table.
You can use the WHERE clause with a DELETE query to delete the selected rows, otherwise all
the records would be deleted.
Syntax

DELETE FROM
table_nameWHERE[conditio
n];
Example
The following code has a query, which will DELETE a customer ,whose ID is 5.

DELETE FROM person


WHERE ID=5;
Now, the person table would have the following records.
To DELETE all the records from the CUSTOMERS table, no need to use the WHERE
clause and the DELETE query would be as follows–

DELETEFROM person;
EXP-05: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.
 Ensuring data dependencies make sense i.e data is logically stored.

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.

Course Content Course Content


Programming Java,C++ Programming Java
Web HTML.Php,ASP Programming C++
Web HTML
Web Php
Web ASP

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.

Studi lastname Idprof Prof Grade


d
1 John 3 Nick 5
2 Helan 2 Smith 4
3 Henry 1 Martin 6

studid lastname Idprof Prof studid Idprof Grade


1 John 1 Martin 1 3 5
2 Helan 2 Smith 2 2 4
3 Henry 3 Nick 3 1 6

ThirdNormalForm(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.
Bookid Genreid Genretype Price
1 1 Science 30
2 2 maths 35
3 1 Science 25
4 3 Physics 20
5 2 maths 30

Bookid Genreid Price Genreid Genretype


1 1 30 1 Science
2 2 35 2 maths
3 1 25 3 Physics
4 3 20
5 2 30

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 over lapping
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. 
std course teacher
Helan DBMS Mark
Sam DBMS Williams
Ram COA Smith
Vicky COA Smith
Alice DBMS Mark

std course course teacher


Helan DBMS DBMS Mark
Sam DBMS DBMS Williams
Ram COA COA Smith
Vicky COA
Alice DBMS

FourthNormalForm(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.
s_id course hobby
1 Science Cricket
1 Maths Hockey
2 C# Cricket
2 Php Hockey

s_id course s_id hobby


1 Science 1 Cricket
1 Maths 1 Hockey
2 C# 2 Cricket
2 Php 2 Hockey

Fifth Normal Form/Projected Normal Form (5NF): A relation R is in 5NF if and only if every join dependency
in R is implied by the candidate keys of R. A relation decomposed into two relations must have loss-less join
Property, which ensures that no spurious or extra tuples are generated, when relations are reunited through a
natural join.

Properties – A relation R is in 5NF if and only if it satisfies the following conditions:

1. R should be already in 4NF.


2. It cannot be further non-loss decomposed (join dependency).

Agent Company Product


Smith C1 Book
Smith C1 Pencil
Smith C2 Laptop
Sam C1 Laptop

R1 R2
Agent Company Agent Product
Smith C1 Smith Book
Smith C2 Smith Pencil
Sam C1 Smith Laptop
Sam Laptop

R1⋈R2
Agent Company Product
Smith C1 Book
Smith C1 Pencil
Smith C1 Laptop
Smith C2 Book
Smith C2 Pencil
Smith C2 Laptop
Sam C1 Laptop

You might also like