DBms
DBms
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
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
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.
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".
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:
Syntax
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:
Example:
Describe persons;
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.
Example:
The following SQL adds an"Email"column to the"Persons"table:
ALTER TABLE Persons
ADDEmailvarchar(255);
ALTER TABLE
table_nameDROPCOLUMN
column_name;
Example:
The following SQL deletes the "Email" column from the "Persons" table:
ALTERTABLE Persons
DROPCOLUMN Email;
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
SELECT*FROM 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.
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.
DELETEFROM person;
EXP-05:Normalization
Normalization of Database:
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
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
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.
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