0% found this document useful (0 votes)
41 views53 pages

DDM Lab Manual 22-23

Uploaded by

Pon Murugan
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)
41 views53 pages

DDM Lab Manual 22-23

Uploaded by

Pon Murugan
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/ 53

DEPARTMENT OF

ARTIFICIAL INTELLIGENCE AND DATA SCIENCE

DATABASE DESIGN AND MANAGEMENT

LAB MANUAL
 Vision

To emerge as a Premier Institute for developing industry ready engineers with


competency, initiative and character to meet the challenges in global environment.

 Mission

 To impart state-of-the-art engineering and professional education through strong


theoretical basics and hands on training to students in their choice of field.

 To serve our students by teaching them leadership, entrepreneurship, teamwork,


values, quality, ethics and respect for others.

 To provide opportunities for long-term interaction with academia and industry.

 To create new knowledge through innovation and research.


DEPARTMENT OF
ARTIFICIAL INTELLIGENCE AND DATA SCIENCE

 VISION
To produce the leaders in the field of Artificial Intelligence and Data Science ,
evolving as a Centre of Excellence for Learning and Research.

 MISSION

Artificial Intelligence and Data Science Department is committed,

o To develop globally competent engineers capable of providing secure


and Out-of-the Box computing and cutting-edge technology solutions.

o To provide state-of-art laboratories and quality learning environment.

o To educate students with ethical values and to serve society with


innovative, intelligent products and service.
DEPARTMENT OF

ARTIFICIAL INTELLIGENCE AND DATA SCIENCE

I. PROGRAM EDUCATIONAL OBJECTIVES (PEOs)

Graduates can
1. Utilize their proficiencies in the fundamental knowledge of basic sciences, mathematics,
Artificial Intelligence, data science and statistics to build systems that require management
and analysis of large volumes of data.
2. Advance their technical skills to pursue pioneering research in the field of AI and Data
Science and create disruptive and sustainable solutions for the welfare of ecosystems.
3. Think logically, pursue lifelong learning and collaborate with an ethical attitude in a
multidisciplinary team.
4. Design and model AI based solutions to critical problem domains in the real world.
5. Exhibit innovative thoughts and creative ideas for effective contribution towards economy
building.

II. PROGRAM OUTCOMES (POs)

PO# Graduate Attribute

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, review 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. 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.

III PROGRAM SPECIFIC OUTCOME


(PSOs) Graduates should be able to:

1. Evolve AI based efficient domain specific processes for effective decision making in several domains
such as business and governance domains.
2. arrive at actionable Foresight, Insight, hindsight from data for solving business and engineering
problems
3. create, select and apply the theoretical knowledge of AI and Data Analytics along with practical
industrial tools and techniques to manage and solve wicked societal problems
4. Develop data analytics and data visualization skills, skills pertaining to knowledge acquisition,
knowledge representation and knowledge engineering, and hence be capableof coordinating complex
projects.
5. Able to carry out fundamental research to cater the critical needs of the society through cutting edge
technologies of AI.
AD3381 DATABASE DESIGN AND MANAGEMENT LABORATORY L T P C
0 0 3 1.5

COURSE OBJECTIVES:
 To understand the database development life cycle
 To learn database design using conceptual modeling, Normalization
 To implement database using Data definition, Querying using SQL manipulation and SQL
programming
 To implement database applications using IDE/RAD tools
 To learn querying Object-relational databases

SUGGESTIVE EXPERIMENTS
1. Database Development Life cycle:
Problem definition and Requirement analysis
Scope and Constraints
2. Database design using Conceptual modeling (ER-EER) – top-down approach Mapping
conceptual to relational database and validate using Normalization
3. Implement the database using SQL Data definition with constraints, Views
4. Query the database using SQL Manipulation
5. Querying/Managing the database using SQL Programming
- Stored Procedures/Functions
- Constraints and security using Triggers
6. Database design using Normalization – bottom-up approach
7. Develop database applications using IDE/RAD tools (Eg., NetBeans,VisualStudio)
8. Database design using EER-to-ODB mapping / UML class diagrams
9. Object features of SQL-UDTs and sub-types, Tables using UDTs, Inheritance, Method definition
10. Querying the Object-relational database using Objet Query language

COURSE OUTCOMES
After the completion of this course, students will be able to:
CO1:Understand the database development life cycle
CO2:Design relational database using conceptual-to-relational mapping, Normalization
CO3:Apply SQL for creation, manipulation and retrieval of data
CO4:Develop a database applications for real-time problems
CO5:Design and query object-relational databases

HARDWARE:
 Standalone Desktops

SOFTWARE:
 PostgreSQL
EXP NO: 01 DATABASE DEVELOPMENT LIFE CYCLE

Traditional Lifecycle Models

This section discusses the traditional lifecycle models and shows that, at least one of the properties required for
database system development (scope restriction, progressive enhancement, incremental planning and pre-defined
structure), is missing from each of these lifecycles. For this reason, these life cycle models are not completely
suitable for developing database systems. In the remaining of this section we briefly describe some of the most
popular software models and point out their deficiencies for developing DBMSs.

Waterfall model:

This is the most common of all software models The phases in the waterfall cycle are: project planning, requirements
definition, design, development, testing, and installation and acceptance (See Figure 1). Each of these phases
receives an input and produces an output (that serves as the input for next phase) in the form of deliverables.

The waterfall model accommodates the scope restriction and the pre-defined structure properties of the lifecycle. The
requirements definition phase deals with scope restriction based on the discussions with the end user. The pre-
defined structure establishes a set of standard guidelines to carry out the activities required of each phase as well as
the documentation that needs to be produced. The waterfall model has a documentation driven approach which, from
the user‟s point of view, is considered one of its main weaknesses.
The system specifications, which are finalized early in the lifecycle, may be written in a non-familiar style or in a
formal language that may be difficult for the end user to understand [Schach, 2008].
Generally, the end user agrees to these specifications without having a clear understanding of what the final product
will be like. This leads to misunderstood or missing requirements in the software requirements specifications (SRS)
Prototype model:

In this life cycle model, the developers create a prototype of the application based on a limited version of the user
requirements The prototype consists mainly of a “hallow graphics” which shows some basic and simple functionality.
However, this may create a problem because the user may view the prototype as it were the final product overlooking
some of the requirements specified in the SRS which may not be met fully by this “final product

This lifecycle model does support the progressive enhancement property. However, since the user is only shown a
prototype there may be features that the user would like to incorporate but which may too costly or time consuming to
incorporate later in the project In the prototype model, the requirements are finalized early in lifecycle as shown in
Figure 2. The iterations are focused on design, prototyping, customer evaluation and review phases. This model lacks
the incremental planning property as there is no planning after the initial planning phase

Spiral model:

This model is a combination of the prototyping and waterfall model starting with the requirements and a development
plan, the system prototypes and the risks involved in their developments are analyzed through an iterative process.
During each iteration alternative prototypes are considered based up on the documented constraints and risks of the
previous iteration the spiral model supports the scope restriction property of a lifecycle. The requirements are
designed in a hierarchical pattern; any additional requirements are built on the first set of requirements
implemented. In this model, the problem to be solved is well defined from the start. In consequence, the scope of the
project is also restricted.
The progressive enhancement property is not accommodated in this lifecycle model because, even though, the
system is evolving with each phase, no new features can be added to the SRS due to the fact that the requirements
have been finalized in an earlier phase.

Rapid application development model (RAD):

The basic approach of this model is to let the user try the application before it is finally delivered. The users provide
feedback based upon their hands-on experience with the system.

The foremost problem with this model is that it is very easy to get caught in an unending and uncontrollable cycle of
enhancements. This will lead to violations of the progressive enhancement and scope restriction property.

As the name of this model implies a prototype is created and installed as soon as possible at the user‟s site for their
review. This model lacks the predefined structure because, in general, the rapid prototype phase is completed
withoutstrictly adhering to the guideline documents and the processes already defined to complete this phase
Database Development Lifecycle:

As we have shown in the previous paragraphs, each of the traditional lifecycle models is missing at least one of the four
properties required for database system development. In this section the authors propose new lifecycle model that is
adapted from the traditional lifecycles and which is enhanced for database system development This new model
satisfies properties such as scope restriction, progressive enhancement, incremental planning and pre-defined
structure.

The next phase of this model, the requirement definition and organizational data collection phase, should have as its
ultimate goal to provide a complete set of requirements, from the user point of view, for the database system under
consideration.

This phase, by its very nature, requires a high degree of interaction with people at all levels of the organization, from
top management to the entry level clerical workers.

After the previous phase has been completed it is necessary to analyze the data to consider issues of extreme
importance such as feasibility, cost, scope and boundaries, performance issues, security issues, portability
requirements, maintenance and the design model of the expected system. This analysis of the requirements
and organizational data helps to identify potential problems and constraints that could arise during
development phases.
The application design documents from the application design phase serve as an input to this phase. The database is
then integrated with the application(s) in the next phase i.e. the integration and testing phase. The integrated system
is tested in this phase.

RESULT
A complete and correct database system is difficult to create if the SDLC does not take into account the intrinsic
characteristics of the system to be developed and the SDLC itself does not accommodate properties like scope
restriction, progressive enhancement, incremental planning and pre-defined structure.
EXP NO: 02 DESIGN AN ER DIAGRAM

AIM:
Analyze the problem and come with the entities in it. Identify what Data has to be persisted in the databases.

ALGORTHIM:
Step 1: Identify the Problem.
Step 2: Draw the E-R model Diagram separately based on problem
Step 3: Separate the Entity Diagram
Step 4: Check the attributes for each Entity.
Step 5: After Identifying the Entity draw the Concept design with E-R model
Step 6: Then based on Concept designdraw the Concept design with E-R diagram
Step 7: Stop.
The following are the entities:

Concept Design with E-R Diagram:


RESULT:
Thus the program to design a database using ER diagram has been done successfully
EXP NO: 03 IMPLEMENT THE DATABASE USINGSQL DATA
DEFINITION WITH CONSTRAINTS

AIM:
To Implement the Database using Sql Data
Definition With Constraints

QUERY:

creating a table

CREATE TABLE Student1(

ID int NOT NULL,

Name varchar(25) NOT NULL,

Age int

);

-- inserting some values

INSERT INTO Student1 VALUES (1, 'Aakash', 21);

INSERT INTO Student1 VALUES (2, null, null);

Output:

As you can see in the output, the query returned an error saying that Student1.Name cannot accept
null values. Now let’s provide a value to the Name column of the second INSERT INTO command
and see whether it runs the command successfully.

-- creating a table

CREATE TABLE Student1(


ID int NOT NULL,

Name varchar(25) NOT NULL,

Age int

);

-- inserting some values

INSERT INTO Student1 VALUES (1, 'Aakash', 21);

INSERT INTO Student1 VALUES (2, 'George', null);

Output:

As you can see, even the field for the age column was left null, the query executed successfully as you
provided values for NOT NULL columns. Now, fetch values from this table using the SQL
SELECT command.

-- fetching values

SELECT * FROM Student1;

Output:

 UNIQUE Constraint in SQL

As the name gives out, the UNIQUE constraint prohibits any duplicate values in a column. If a
column has a UNIQUE constraint, it will not allow any similar row entry for that field. You can
declare more than one column as UNIQUE in a table. In the example below, you will take the same
Student1 table and add an Email_Id column and keep it unique. You will also have to insert a
duplicate value in the Email_Id column and see the output.

CREATE TABLE Student1(

ID int NOT NULL,

Name varchar(25) NOT NULL,

Age int,

Email_Id NVARCHAR(50) UNIQUE

);

INSERT INTO Student1 VALUES (1, 'Aakash', 21, 'ak@12');

INSERT INTO Student1 VALUES (2, 'George', null, 'go@45');

SELECT * FROM Student1;

-- trying to insert duplicate values

INSERT INTO Student1 VALUES (3, 'Rahul', 21, 'go@45');

Output:

 PRIMARY KEY Constraint in SQL

The PRIMARY KEY constraint is a combination of both NOT NULL and UNIQUE constraints. This
means that when you define a column with PRIMARY KEY, it will not accept any null or duplicate
values. You will create the Student2 table in the code below and determine the ID column with the
PRIMARY KEY constraint. You will then try to insert the same and null values in different rows and
look at the output.

CREATE TABLE Student2(

Name varchar(25) NOT NULL,


ID int PRIMARY KEY,

Age int,

Email_Id NVARCHAR(50) UNIQUE

);

INSERT INTO Student2 VALUES ('Aakash', 1, 21, 'ak@12');

INSERT INTO Student2 VALUES ('George', 2, NULL, 'go@45');

INSERT INTO Student2 VALUES ('Rahul', 1, 21, 'rh@67');

INSERT INTO Student2 VALUES (NULL, 3, 23, 'mr@89');

SELECT * FROM Student2;

Output:

RESULT:
Thus the Implementation of the Database Using SQL Data
Definition With Constraints has been done successfully.
EX NO.04 IMPLEMENTATION OF SQL COMMANDS - DDL

AIM:
To implement the SQL commands for DDL.

DDL Commands:
a.Create a Database named student_db
Query:

CREATE DATABASE student_db

b. Create a table named student_info with following attributes student register number student name student year
student mail id student mobile number
Query:
CREATE TABLE student_info
(

student_register_number int(3),
student_name varchar(30),
student_year int(4),
student_mail_id varchar(20),
student_mobile_number int(10));
SELECT*FROMstudent_info
c. Add the column course id course name grade
Query:
ALTER TABLE student_info
ADD COLUMN course_id int(10),
ADD COLUMN course_name varchar(20),
ADD COLUMN grade varchar(10);

d. remove the below column student year


Query:
ALTER TABLE student_info
DROP COLUMN student_year;

e. rename the table as student_detail


Query:
ALTER TABLE student_info
RENAME TO student_detail;
SELECT * FROM student_detail
f.
f. rename student name attribute as student Lastname
Query:
ALTER TABLE student_detail
RENAME COLUMN student_name TO student_Lastname;

g. Delete the table

Query:

DROP TABLE student_detail;


i. Delete the
database
Query:
DROP DATABASE student_db;

Result:
Thus, the DDL commands has been implemented successfully.
EXP NO. 5a. PROCEDURES/FUNCTIONS

AIM:
To demonstrate the implementation of PL/SQL stored procedures.

1. Get a number from user and identify if it‟s a even number or odd number Hint:- use simple if-else Loop and
MOD function
Query:
DELIMITER &&
CREATE PROCEDURE odd_even(IN x int)
BEGIN
If (x MOD 2 = 0)Then
Select "Given Number is Even" as output;
else
Select "Given Number is Odd" as output;
End If;
End &&
set @x=125;
call odd_even(@x);

2. Get the basic salary from a user, calculate and display the HRA, DA and total salary (as per the conditions below)
of an employee using Procedures
Query:
DELIMITER &&

Query:
DELIMITER &&
CREATE PROCEDURE salary(in bSalary int,out HRA int,out DA int,out TotalSalary int) BEGIN
if(bSalary>=15000) then
set HRA = (12/100) * bSalary;
set DA = (8/100) * bSalary;

Set TotalSalary = HRA + DA + bSalary; elseif(bSalary<15000 and bSalary>=12000) then


set HRA = (10/100) * bSalary;
set DA = (6/100) * bSalary;
set TotalSalary = HRA + DA + bSalary; elseif(bSalary<12000 and bSalary>=9000) then set HRA = (7/100) *
bSalary;
set DA = (4/100) * bSalary;
set TotalSalary = HRA + DA + bSalary;
else
set HRA = (5/100) * bSalary;
set DA = 200;
set TotalSalary = HRA + DA+bSalary;
END IF;
END &&
call salary(13500,@a,@b,@c);
select @a As HRA, @b As DA, @c AsTotal_Salary;
3. Get a number from user and find Factorial of the given number Hint: use a loop
Query:
DELIMITER &&
create procedure print_table (in num int)
begin
declare i,j int;
set i=1,j=1;
simple_loop: LOOP
set i=i+1;
set j=i*j;
IF i=num THEN
select j;
LEAVE simple_loop;
END IF;

END LOOP simple_loop;


END &&
set @num=5;
call print_table(@num);set @num=5;
call print_table(@num);

4. Get an input string from a user, write a Procedure to check if the string is a palindrome.
Hint : use REVERSE function and compare the strings using STRCMP function
Query:
DELIMITER &&
CREATE PROCEDURE Palindrome(in sname varchar(30))
BEGIN
DECLARE rev varchar(30);
set rev = Reverse(sname);
If (STRCMP(sname,rev)=0) then
select "It is a Palindrome" as Output;
else
select "It is not Palindrome" as Output;
end if;
end &&
set @sname = "vishnupriya";
call Palindrome(@sname);
5. Print the output (1,2,3,4,5,6,7,8,9,10). Use a simple loop function and CONCAT function to do this.
Query:
DELIMITER //
CREATE procedure print_numbers()
begin
declare i int;
declare result varchar(50);
set i=2;
set result=1;
loop_label: LOOP

SET result = CONCAT(result,',',i);


set i=i+1;
if i>10 then
LEAVE loop_label;
END IF;
ITERATE loop_label;
END LOOP;
select result;
END //
call print_numbers();

6. Create a table for the below schema


Sample1(sl.no)
Using procedure insert values from 1-99 in the table
Query:
CREATE TABLE Sample1(s_no int);
DELIMITER //
CREATE procedure insert_values()
begin
Declare i int;
set i=1;
loop_label: LOOP
insert into sample1(s_no) values (i);
set i=i+1;
if i>99 then
LEAVE loop_label;
END IF;
ITERATE loop_label;
END LOOP;
END //
call insert_values();
select * from Sample1;

Result:
Thus, the queries to implement PL/SQL stored procedures has been executed successfully.
EXP NO. 5b CONSTRAINTS AND SECURITY USING TRIGGERS

AIM:
To demonstrate the implementation of PL/SQL Triggers and Cursors.

TRIGGERS:
1. Write a trigger to ensure that no employee of age less than 25 can be inserted in the emp_details table.
2. Query:
Create table emp_details(emp_id int,emp_name varchar(30),age int,residence varchar(30));
DELIMITER :
Create Trigger checkAge before insert on emp_details for eachrow Begin
if new.age<=25 then SIGNAL SQLSTATE '45000'
set message_text = 'Age must not be less than 25';End if;
End // DELIMITER ;
INSERT INTO emp_details values(103,'Anu',24,'Salem');

3. Create a trigger which will work before deletion in employee table and create a duplicate copy of the record in
another table employee_backup.
Query:
Create Table Employee_Backup(emp_id int,emp_name varchar(30),age int,residence varchar(30));
DELIMITER &&
CREATE TRIGGER Back_up Before delete on emp_details foreach row
Begin
Insert into Employee_Backup Values(old.emp_id,old.emp_name,old.age,old.residence );
END &&
DELIMITER ;
Delete from emp_details where age=30;
Select * from Employee_Backup;

4. Write a trigger to count number of new tuples inserted using each insert statement. Query:
DELIMITER &&
CREATE TRIGGER Count_tupples after insert on emp_details for each rowBegin
Declare count int; set count=0; set count = count+1;END &&
DELIMITER ;
INSERT INTO emp_details Values(106,'Vinny',29,'Bangalore'),(107,'Vp',26,'Mumbai');

5. Suppose that the Middlesex Transport Authority (MTA) has a rule stating that a bus driver‟s salary cannotbe
changed by more than 20% of the original salary. Create a trigger „salary_change_monitoring‟ to enforce this
constraint. The trigger fires whenever there is an update to the Busdriver table and outputs a suitable error message
when the rule is violated.
Query:
create table BusDriver(Driver_name varchar(30),salary int); Insert into BusDriver
Values('Ramu',30000),('Somu',35000);
DELIMITER &&
create trigger salary_change_monitoring before update on BusDriver for each rowBegin
Declare a varchar(100);
Set a = "Large amount of change in salary is not accepted"; ifnew.salary>old.salary + (old.salary*20/100) then
Signal SqlState '45000'Set message_text = a; End if;
End &&
Update BusDriver set salary = 50000 where salary = 35000;

6. Suppose you enter a product in the purchase table, and if the product quantity is greater than 10 in the stocktable
raise a warning “we have enough stock with us”.
Query:
Create table stock(SName varchar(30),SQuantity int); Insert into stock values('Pen',15),('Carrom',5),('Bat',8); Create
table purchase(Pname varchar(30),PQuantity int);DELIMITER &&
Create trigger quantity_check before insert on purchase for each rowBEGIN
declare a int;
Set a = (select SQuantity from stock where Sname = new.PQuantity); if a >=10 thenSignal sqlstate '45000'
Set message_text = 'We have Enough Stock with us';End if;
End && DELIMITER :
Insert into purchase values('Bat',8);

7. Suppose, we are adding a tupple to the „Donors‟ table that is some person has donated blood. So, we candesign a
trigger that will automatically add the value of donated blood to the „Blood_record‟ table.
Query:
Create table Donars(Donar_name varchar(50),blood_group varchar(10)); Insert into Donars
values('Viveka','O'),('Ammu','A');
Create table Blood_Record(blood_group varchar(10));
DELIMITER &&
create trigger Donars_Record after Insert on Donars for each rowBegin
Insert into Blood_Record values(new.blood_group); End &&
DELIMITER ;
INSERT INTO Donars values('Akil','B');Select * from Blood_Record;
CURSOR:
1. Create a student academic table with following fields:
▪ Register number
▪ Mark 1
▪ Mark 2
▪ Total
▪ Result
Construct a procedure with a cursor which prints the result as “pass” when Mark 1 and Mark 2 is greater than 50and
“fail” when either of them are less than 50
Query:
Create table stud_at(reg_no int,mark_1 int,mark_2 int,total int,result varchar(50)); insert into stud_at values
(101,95,95,190,""),(102,40,40,80,"");
delimiter //
create procedure stud_result ()begin declare n int;
declare R varchar(1000) default "";declare is_done int default 0; declare res varchar(50);
declare m1 int; declare m2 int;
declare cur_result cursor for select reg_no,mark_1,mark_2 from stud_at; declare continue handler for not found set
is_done =1;
open cur_result; getResult: loop fetch next from cur_result into n,m1,m2; if m1 > 50 and m2 > 50 then
set res ="Pass";
else set res = "fail"; end if; if is_done = 1 thenleave getResult;
end if;

set R =concat ( "Result of ",n," is ",res ,' ',R);end loop getResult;


close cur_result; select R as result;
end // delimiter ; call stud_result();
2. Write a program in PL/SQL to create a cursor displays the name and salary of each employee in the
EMPLOYEES table whose salary is less than that specified by a passed- in parameter value.
Query:
Create table Employees ( id int,e_name varchar(20),e_salary int); insert into Employees
values(101,'Ramu',20000),(102,'Lachu',10000); select * from
Employees;

delimiter // create procedure Emp_detail(in salary int) begin declare n varchar(50); declare s int; declare R
varchar(1000) default "";
declare is_done int default 0;

declare emp cursor for select e_name,e_salary from Employees; declare continue handler for not found set is_done
=1;
open emp; getResult: loop fetch next from emp into n,s;
if s < salary then set R =concat ( "salary of ",n, " is ",s ,' '); end if;if is_done = 1 then leave getResult; end if; end
loop getResult; close emp; select R as result;end // delimiter ; call Emp_detail(20000);
Result:

Thus, the queries to demonstrate the implementation of Triggers and Cursors has been executed successfully.
EXP NO.6. NORMALIZATION

AIM:

Normalization is the analysis of functional dependencies between


attributes/dataitemsofuserviews.Itreducesacomplexuserviewtoasetofsmallandstablesubgroups
ofthefieldsandrelations.This process helps to design a logical data model known as conceptual datamodel.

Therearedifferentnormalforms
1. FirstNormalForm(1NF)
2. SecondNormalForm(2NF)
3. ThirdNormalForm(3NF)

FIRSTNORMALFORM (1NF)
1NF states that the domain of an attribute must include only atomic values and thatvalue of any attribute in a
tuple must be a single value from the domain of that attribute.Hence 1NF disallows multivalued attributes,
composite attributes. It disallows “relationswithinrelations”.

SECONDNORMALFORM(2NF)
Arelationissaidtobein2NFifitisalreadyin1NFandithasnopartialdependency.2NFisbasedontheconcept
offullfunctionaldependency.
Afunctionaldependency(FD)x→yisfullyfunctionaldependencyis(x-
(A))→ydoesnotholddependencyanymoreifA→x.
Afunctionaldependencyx→yispartialdependencyifAcanberemovedwhichdoes not affect
thedependencyie, (x-(A))→yholds.
A relation is in 2NF if it is in 1NF and every non-primary key attribute
Isfullyandfunctionallydependentonprimarykey.
Arelationisin1NFwill beinthe2NFifoneofthefollowingconditionsissatisfied:

1. The primarykeyconsist ofonlyone attribute.


2. Non-keyattributeexistinrelationie , alltheattributesintherelationarecomponentsoftheprimarykey.
Every non-key attribute is functionally dependent on full set of primarykeyattributes.

THIRD NORMAL FORM(3NF)


Arelationissaidtobein3NFifitisalreadyin2NFandithasnotransitivedependency.
A FD x→y in a relation schema R is a transitive dependency if there is a set ofattributes zthat is neither a
candidate key nor a subset of any key of the relation and bothx→z andz→yhold.

CREATE TABLE Projects(


[ID] INT PRIMARY KEY IDENTITY,
[Name] VARCHAR(100),
[Value] DECIMAL(5,2),
StartDate DATE,
EndDate DATE
)
GO
CREATE TABLE Employees(
[ID] INT PRIMARY KEY IDENTITY,
[FirstName] VARCHAR(50),
[LastName] VARCHAR(50),
[HourlyWage] DECIMAL(5,2),
[HireDate] DATE
)
GO
CREATE TABLE ProjectEmployees(
[ID] INT PRIMARY KEY IDENTITY,
[ProjectID] INT,
[EmployeeID] INT,
[Hours] DECIMAL(5,2),
CONSTRAINT FK_ProjectEmployees_Projects FOREIGN KEY ([ProjectID]) REFERENCES [Projects] ([ID]),
CONSTRAINT FK_ProjectEmployees_Employees FOREIGN KEY ([EmployeeID]) REFERENCES [Employees]
([ID])
)
GO
CREATE TABLE JobOrders(
[ID] INT PRIMARY KEY IDENTITY,
[EmployeeID] INT,
[ProjectID] INT,
[Description] TEXT,
[OrderDateTime] DATETIME,
[Quantity] INT,
[Price] DECIMAL(5,2),
CONSTRAINT FK_JobOrders_Projects FOREIGN KEY ([ProjectID]) REFERENCES [Projects] ([ID]),
CONSTRAINT FK_JobOrders_Employees FOREIGN KEY ([EmployeeID]) REFERENCES [Employees] ([ID])
)
GO

CREATE TABLE Customers (


[Name] VARCHAR(100),
[Industry] VARCHAR(100),
[Project1_ID] INT,
[Project1_Feedback] TEXT,
[Project2_ID] INT,
[Project2_Feedback] TEXT,
[ContactPersonID] INT,
[ContactPersonAndRole] VARCHAR(255),
[PhoneNumber] VARCHAR(12),
[Address] VARCHAR(255),
[City] VARCHAR(255),
[Zip] VARCHAR(5)
)
GO

First Normal Form

As we have already discussed above, the first normal form relates to the duplication of data and also over-grouping
of data in the columns.

The Customers table in the diagram violates all the three rules of the first normal form.

1. We do not see any Primary Key in the table.


2. The data is not found in its most reduced form. For example, the column ContactPersonAndRole can be
divided further into two individual columns - ContactPerson and ContactPersonRole.
3. Also, we can see there are two repeating groups of columns in this table - (Project1_ID, Project1_FeedBack)
and (Project2_ID, Project2_Feedback). We need to get these removed from this table.

The diagram below shows dummy data stored in the Customers table.
Fig 2 - Customers Table Data

Let us now get our hands dirty and start modifying the table, so that it satisfies the first normal form.

The first thing that we need to do is to add a primary key to this table. For this, we can add a new column ID with
datatype as INT and also assign it as an Identity column. The script is given below.

ALTER TABLE [Customers]


ADD [ID] INT IDENTITY PRIMARY KEY
GO

When you execute this script, a new column gets added at the end of all the columns. This is the primary key of the
table and now it satisfies the first rule of the First Normal Form.

Secondly, we need to split the column ContactPersonAndRole into two individual columns. This can be done in two
steps as follows:

1. Rename the original column from ContactPersonAndRole to ContactPerson.


2. Add a new column for ContactPersonRole.

The script below, when executed, will rename the original column and add a new column to store
the ContactRole information.

sp_rename 'Customers.[ContactPersonAndRole]', 'ContactPerson', 'COLUMN'


GO
ALTER TABLE [Customers]
ADD [ContactPersonRole] VARCHAR(20)
GO
Finally, in order to satisfy the third rule of the First Normal Form, we need to move the
columns Project1_ID, Project1_Feedback, Project2_ID, and Project2_Feedback into a new table. This can be done
by creating a new table ProjectFeedbacks and link it back with the Customers and the Projects table.

When the script below is executed, it will remove the above-mentioned columns from the Customers table and
create a new table ProjectFeedbacks with Foreign Key references to the Customers and Projects table.

ALTER TABLE [Customers]


DROP COLUMN Project1_ID
ALTER TABLE [Customers]
DROP COLUMN Project1_Feedback
ALTER TABLE [Customers]
DROP COLUMN Project2_ID
ALTER TABLE [Customers]
DROP COLUMN Project2_Feedback
GO

CREATE TABLE ProjectFeedback(


[ID] INT PRIMARY KEY IDENTITY,
[ProjectID] INT,
[CustomerID] INT,
[Feedback] TEXT,
CONSTRAINT FK_ProjectFeedbacks_Projects FOREIGN KEY ([ProjectID]) REFERENCES [Projects] ([ID]),
CONSTRAINT FK_ProjectFeedbacks_Customers FOREIGN KEY ([CustomerID]) REFERENCES [Customers]
([ID])
)
GO

As you can see, the Customers table has been altered and a new table ProjectFeedbacks has been added into the
schema. Thus, there are no repeating groups in the Customers or the ProjectFeedbacks table. We can also know
about the feedbacks as it refers to both the Customers and the Projects table.

Now, that the Customers table supports 1NF, let's go ahead and apply the second normal form.

Second Normal Form

To satisfy the conditions of the second normal form, all the rules of the first normal form should satisfy. And along
with that, we also need to ensure that all the columns in the table relate directly to the primary key of the record in
the table.

However, if you see the database schema diagram above (Fig 3), you can see that
the ContactPerson, ContactPersonRole and the PhoneNumber do not directly relate to the ID of the Customers table.
That is because the primary key refers to a customer and not to any person or role or the phone number of the
contact person. If ever, the contact person for a customer changes, we would have to update all of these columns,
running the risk that we will update the values in one of the columns but forget to modify the other.

So, in order to satisfy this rule, we need to remove these three columns from the Customers table and put them in a
separate table. This table should contain data that is related only to the contact person and not the customer.

Let us remove all these columns from the Customers table which do not relate to the primary key of the table
directly. The script below removes the three columns from the table as these are not related to the customer, instead
of to the contact person only.

ALTER TABLE [Customers]


DROP COLUMN ContactPerson
ALTER TABLE [Customers]
DROP COLUMN ContactPersonRole
ALTER TABLE [Customers]
DROP COLUMN PhoneNumber
GO

Once, the columns are removed from the Customers table, we need to create a new table that'll store the data for the
contact persons. Let us create a new table ContactPersons and relate it to the Customers table with a foreign key
relation. The script is provided below.

CREATE TABLE ContactPersons(


[ID] INT PRIMARY KEY IDENTITY,
[ContactPerson] VARCHAR(100),
[ContactPersonRole] VARCHAR(20),
[PhoneNumber] VARCHAR(12)
)
GO
ALTER TABLE [Customers]
ADD CONSTRAINT FK_Customers_ContactPersons FOREIGN KEY ([ContactPersonID])
REFERENCES ContactPersons([ID])
GO

Once this script is executed, you can see in the diagram below (Fig 4) that a new table has been added to the schema
and now it satisfies the second normal form of the database.

Fig 4 - Second Normal Form Diagram

Now, if the contact person for customer changes, we just need to insert a record into the ContactPersons table and
change the ContactPersonID in the Customers table.

Third Normal Form

To satisfy the conditions of the third normal form, all the rules of the second normal form must satisfy. And with
that, we also need to ensure that each column must be non-transitively dependent on the primary key of the table.
This means that all columns in a table should rely only on the primary key and no other column. If ColumnA relies
on the primary key and also on the ColumnB, then ColumnA is known to be transitively dependent on the primary
key and it violates the third normal form.

After applying 1NF and 2NF, below is what the Customers table looks like now (Fig 5).

Fig 5 - Customers table after 2NF


If you look carefully, there are transitive dependent columns in this table and it violates the 3NF. The transitive
dependent relationship is between the columns - City and Zip. The city in which a customer is situated relates to the
primary key of the customer, so this satisfies the second normal form. However, the city also depends on the zip
code. If a customer changes its location, there may be a chance we update one column but not the other. Because of
this relationship between the City and Zip, the database is not in 3NF.

In order to fix this and bring the table to satisfy the third normal form, we need to remove the City from
the Customers table and create a new table ZipCodes to store the Zip and City. This new table can be related to
the Customers table via a foreign key relation. The script is provided below.

ALTER TABLE [Customers]


DROP COLUMN City
GO
CREATE TABLE ZipCodes(
[ZipID] VARCHAR(5) PRIMARY KEY,
[City] VARCHAR(255)
)
GO
ALTER TABLE [Customers]
ADD CONSTRAINT FK_Customers_ZipCodes FOREIGN KEY ([Zip])
REFERENCES ZipCodes([ZipID])
GO
Now that all the changes are performed, lets look at the schema after the third normal form has also been satisfied
(Fig 6). As you can see, the new table ZipCodes has been added and it relates to the Customers table.

Fig 6 - Third Normal Form Diagram

That's all for the third normal form. The Customers table now supports all the three normal forms and can be used as
required. It is always tricky to find issues that are caused by a violation of the third normal form. However, for good
database design, these are quite essential that all the normal forms are satisfied

RESULT

Thus Database Design Normalization for any applicationis being designed and Executedsuccessfully.
EXP NO. 07 DEVELOP DATABASE APPLICATIONS USING IDE

AIM:
Installation of MySQL Steps for installing MySQL

Step1
Makesureyoualreadydownloaded theMySQLessential5.0.45 win32.msi file .Doubleclickonthe
.msifile.

Step2
This is MySQLServer 5.0 setupwizard.
The setupwizard will install
MySQL Server 5.0release5.0.45on your computer.
To continue,click next.

Step3
Choose the setup type that best suits your needs. For common program features select Typical
and it‟s recommended for general use.To continue,click next.
Step4
This wizard is ready to begin installation. Destination folder will be in
C:\ProgramFiles\MySQL\MySQLServer5.0\.Tocontinue,clicknext.

Step5
Theprogramfeaturesyouselectedarebeinginstalled.Pleasewaitwhilethesetupwizard
installsMySQL5.0.Thismaytakeseveralminutes.
Step6
To continue, click next.

Step7
To continue, click next.

Step8
Wizard Completed. Setup has finished installing MySQL 5.0. Check the configure the MySQL server now to
continue .Click Finish to exit the wizard
Step9 TheconfigurationwizardwillallowyoutoconfiguretheMySQLServer5.0serveinstance.Tocontinu e,clicknext.

Step10
Select a standard configuration and this will use a general purpose configuration for the server
thatcanbetunedmanually.Tocontinue,clicknext.

Step11:
Check on the install as windows service and include bin directory in windows path.Tocontinue,clicknext.

Step12:Please set the security options by entering the root password and confirm retype
thepassword.continue,clicknext.

Step13:Readytoexecute?Clicks execute tocontinue.

Step14 Processingconfigurationinprogress.Configurationfilecreated.WindowsserviceMySQL5installe
d.Press finishtoclose thewizard.

Result:
Thus the installation of MySQL is done successfully.
EXP NO.08. UML CLASS DIAGRAM

AIM:
Aggregation and Multiplicity are two important points that need to take into consideration while designing a
Class Diagram.Letus understanding detail.

Aggregation –

Aggregation simply how relationship where one thing can exist independently of other thing. It means to
create or compose different abstractions together in defining a class. Aggregation isrepresented as a part of
relationship in class diagram. In diagram given below, we can see thataggregation is represented by an edge
with a diamond end pointing towards superclass.
The“LibraryManagementSystem”issuperclassthatconsistsofvariousclasses.
TheseclassesareUser,Book,andLibrarianasshownindiagram.Further,for“Account”class,“User” isa superclass.
All of these, share a relationship and these relationships are known asaggregaterelationships.

Multiplicity:

Multiplicity means that number of elements of a class is associated with another class. Theserelations can be
one-to-one, many-to-many, and many-to-one or one-to-many. For denoting oneelement we use 1, for zero
elements we use 0, and for many elements we use *. We can see indiagram; many users are associated with
many books denoted by * and this represents a many-to-many type of relationship. One user has only one
account that is denotedby 1 and thisrepresentsaone-to-one typeofrelationship.
Many books are associated with one librarian and this represents many-to-one or one-to- manytype
ofrelationship.Allthese relationshipsare shown indiagram.
Class Diagram for Library Management System simply describes structure of LibraryManagement
Systemclass,attributes,methodsoroperations,relationshipamongobjects.
ClassesofLibraryManagementSystem:LibraryManagementSystemclass–
It manages all operations of Library Management System. It is central part of organization forwhichsoftwareis
beingdesigned.

User Class–It manages all operations of user.

Librarian Class–It manages alloperations of Librarian.

BookClass –Itmanages all operations of books. It is basic building block of system.

AccountClass–It managesalloperationsofaccount.

Library data base Class–Itmanage+6 sall operations of library database.

Staff Class–It manages all operations of staff.

Student Class–It manages all operations of student.

Attributes of Library Management System : Library Management System Attributes


UserType,Username,Password

UserAttributes – Name, Id LibrarianAttributes–


Name,Id,Password,SearchStringBookAttributes – Title,Author,ISBN,Publication AccountAttributes–
no_borrowed_books,no_reserved_books,no_returned_books,no_lost_booksfine_amount
Librarydatabase Attributes–List_of_books StaffClassAttributes–
Dept StudentClassAttributes–Class

MethodsofLibraryManagementSystem:
Library ManagementSystemMethods– Login(),Register(),Logout() UserMethods–
Verify(),CheckAccount(),get_book_info()LibrarianMethods –
Verify_librarian(), Search()
BookMethods – Show_duedt(),Reservation_status(),Feedback(),Book_request(),Renew_info() AccountMethods–
Calculate_fine()
Librarydatabase Methods–
Add(),Delete(),Update(),Display(),Search()
EXP NO.09. INHERITANCE METHOD DEFINITION

AIM:

To write a program for inheritance method in SQL.

PROGRAM:
CREATEORREPLACEtypeobj_subtypeunderobj_supertype(Obj_emp_jobVARCHAR2(30),
Obj_emp_salNUMBER, OverridingmemberFUNCTIONfunc_super_printR
ETURN VARCHAR2);
/ CREATEORREPLACEtypebodyobj_subtypeAS
OverridingmemberFUNCTIONfunc_super_printRETURN VARCHAR2
ISBEGIN
RETURN(selfASobj_supertype).func_super_print||‟,JobID:„||obj_emp_job||‟,Salary:„||obj_emp_sal||‟$‟;
END;
END;
/DECLARE
L_obj_subtypeobj_subtype:=obj_subtype(857,„ThomasKing‟,„AssistantManager‟,3500);
BE GIN
Dbms_output.put_line((l_obj_subtypeASobj_supertype).func_super_print);D
bms_output.put_line((l_obj_subtype AS obj_subtype).func_super_print);
END;
/

OUTPUT:

The Employee details for theID857isName: Thomas King

The Employee details fortheID857isName:Thomas King, Job ID: AssistantManager,Salary:3500$

RESULT:

Thus program for inheritance method in SQL has been executed successfully.
EXP NO.10. OBJECT-RELATIONAL DATABASE

AIM:

To demonstrate the implementation of Object-Relational Database

PROCEDURE:

The relational approach results in the tables describe in the following sections.

Customer_reltab

The Customer_reltab table has the following definition:

Example A-1 Creating the Customer_reltab Table

CREATE TABLE Customer_reltab (

CustNo NUMBER NOT NULL,

CustName VARCHAR2(200) NOTNULL,

Street VARCHAR2(200) NOT NULL,

City VARCHAR2(200) NOTNULL,

State CHAR(2) NOT NULL,

Zip VARCHAR2(20) NOT NULL,

Phone1 VARCHAR2(20),

Phone2 VARCHAR2(20),

Phone3 VARCHAR2(20),

PRIMARY KEY (CustNo));

This table, Customer_reltab, stores all the information about customers, which means that it fully contains
information that is intrinsic to the customer (defined with the NOT NULL constraint) and information that
is not as essential. According to this definition of the table, the application requires that every customer
have a shipping address.

Our Entity-Relationship (E-R) diagram showed a customer placing an order, but the table does not make
allowance for any relationship between the customer and the purchase order. This relationship must be
managed by the purchase order.
PurchaseOrder_reltab

The PurchaseOrder_reltab table has the following definition:

Example A-2 Creating the PurchaseOrder_reltab Table

CREATE TABLE PurchaseOrder_reltab (

PONo NUMBER, /* purchase order no */

Custno NUMBER references Customer_reltab, /* Foreign KEY referencing

customer */

OrderDate DATE, /* date of order */

ShipDate DATE, /* date to be shipped */

ToStreet VARCHAR2(200), /* shipto address */

ToCity VARCHAR2(200),

ToState CHAR(2),

ToZip VARCHAR2(20),

PRIMARY KEY(PONo));

PurchaseOrder_reltab manages the relationship between the customer and the purchase order by means of
the foreign key (FK) column CustNo, which references the CustNo key of the Customer_reltab.
The PurchaseOrder_reltab table contains no information about related line items. The line items table (next
section) uses the purchase order number to relate a line item to its parent purchase order.

Stock_reltab

The Stock_reltab table has the following definition:

Example A-3 Creating the Stock_reltab Table

CREATE TABLE Stock_reltab (

StockNo NUMBER PRIMARY KEY,

Price NUMBER,

TaxRate NUMBER);

LineItems_reltab

The LineItems_reltab table has the following definition:


Example A-4 Creating the LineItems_reltab Table

CREATE TABLE LineItems_reltab (

LineItemNo NUMBER,

PONo NUMBER REFERENCES PurchaseOrder_reltab,

StockNo NUMBER REFERENCES Stock_reltab,

Quantity NUMBER,

Discount NUMBER,

PRIMARY KEY (PONo, LineItemNo));

RESULT:

Thus the implementation of Object-Relational Database has been done successfully and output has been
verified.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy