ANNA UNIVERSITY,
REGIONAL CAMPUS, COIMBATORE- 641046
LABORATORY RECORD
2023-2024
NAME : …………………………………….
REG.NO : ………………………………….…
BRANCH : …………………………………….
SUBJECT CODE : …………………………………….
SUBJECT TITLE :……………………………………..
DEPARTMENT OF COMPUTER SCIENCE AND
ENGINEERING
ANNA UNIVERSITY REGIONAL CAMPUS
COIMBATORE- 641 046.
ANNA UNIVERSITY,
REGIONAL CAMPUS, COIMBATORE- 641046
DEPARTMENT OF COMPUTER SCIENCE AND
ENGINEERING
BONAFIDE CERTIFICATE
Certified that this is the bonafide record of Practical done in AD3381- DATABASE DESIGN
AND MANAGEMENT LABORATORY by……………………………………………...
Roll No…............................... Second Year/Third Semester during 2023-2024.
Staff in Charge Head of the Department
University Register No: …………………………………………………………………………………
Submitted for the University Practical Examination held on………………………….
Internal Examiner External Examiner
INDEX
S.NO DATE TITLE Page. Mark Signature
No
EX.NO : 1
DATABASE DEVELOPMENT LIFE CYCLE: PROBLEM DEFINITION
DATE: AND REQUIREMENT ANALYSIS SCOPE AND CONSTRAINTS
AIM:
To define the problem and requirements of a database system and identify its scope
and constraints.
INTRODUCTION :
Database development is just one part of the much wider field of software engineering,
the process of developing and maintaining software. A core aspect of software engineering is the
subdivision of the development process into a series of phases, or steps, each of which focuses on
one aspect of the development. The collection of these steps is sometimes referred to as a
development life cycle. The software product moves through this life cycle (sometimes repeatedly
as it is refined or redeveloped) until it is finally retired from use. Ideally, each phase in the life
cycle can be checked for correctness before moving on to the next phase.
REQUIREMENT ANALYSIS:
Analysis starts by considering the statement of requirements and finishes by producing a
system specification. The specification is a formal representation of what a system should do,
expressed in terms that are independent of how it may be realised.
Data analysis begins with the statement of data requirements and then produces a
conceptual data model. The aim of analysis is to obtain a detailed description of the data that will
suit user requirements so that both high and low level properties of data and their use are dealt
with. These include properties such as the possible range of values that can be permitted for
attributes (e.g., in the school database example, the student course code, course title and credit
points).
The conceptual data model provides a shared, formal representation of what is being
communicated between clients and developers during database development – it is focused on the
data in a database, irrespective of the eventual use of that data in user processes or implementation
of the data in specific computer environments. Therefore, a conceptual data model is concerned
with the meaning and structure of data, but not with the details affecting how they are
implemented.
The conceptual data model then is a formal representation of what data a database should
contain and the constraints the data must satisfy. This should be expressed in terms that are
independent of how the model may be implemented. As a result, analysis focuses on the questions,
“What is required?” not “How is it achieved?”.
Information is gathered for each major user view (that is, job role or enterprise application area),
including:
• a description of the data used or generated;
• the details of how data is to be used or generated;
• any additional requirements for the new database system.
This information is then analyzed to identify the requirements (or features) to be included in the
new database system. These requirements are described in documents collectively referred to as
requirements specifications for the new database system. The amount of data gathered depends
on
i) nature of the problem and
ii) policies of the enterprise.
Identifying the required functionality for a database system is a critical activity, as systems with
inadequate or incomplete functionality will annoy the users, which may lead to rejection or
underutilization of the system. However, excessive functionality can also be problematic, as it
can overcomplicate a system, making it difficult to implement, maintain, use, or learn.
DEFINE PROBLEMS AND CONSTRAINTS:
The designer has both formal and informal sources of information. The process of
defining problems might initially appear to be unstructured. Company end users are often unable
to describe precisely the larger scope of company operations or to identify the real problems
encountered during company operations.
DEFINE SCOPE AND BOUNDARIES:
The designer must recognize the existence of two sets of limits: scope and boundaries.
The system’s scope defines the extent of the design according to operational requirements. Will
the database design encompass the entire organization, one or more departments within the
organization, or one or more functions of a single department? Knowing the scope helps in
defining the required data structures, the type and number of entities, the physical size of the
database, and so on. Boundaries are also imposed by existing hardware and software.
RESULT:
Thus the study on problem definition, requirement analysis, scope and constraints of
database development life cycle is successfully performed.
EX.NO : 2(a) DATABASE DESIGN USING CONCEPTUAL MODELING (ER-EER) –
TOP-DOWN APPROACH MAPPING CONCEPTUAL TO RELATIONAL
DATE: DATABASE AND VALIDATE USING NORMALIZATION FOR COLLEGE
MANAGEMENT SYSTEM
AIM:
To design a database using conceptual modeling (ER-EER) and map it to a relational
database using normalization for college management system.
CONCEPTUAL DESIGN:
The process of constructing a model of the data used in an enterprise, independent of all
physical considerations.
Ideas → High-level design → Relational database schema → Relational DBMS
COMMANDS:
Commands used in this program:
• CREATE
• INSERT
• DELETE
PROCEDURE TO BUILD CONCEPTUAL DATA MODELS:
Step 1 Identify entity types.
Step 2 Identify relationship types.
Step 3 Identify and associate attributes with entity or relationship types.
Step 4 Determine attribute domains.
Step 5 Determine candidate, primary, and alternate key attributes.
Step 6 Consider use of enhanced modelling concepts (optional step).
Step 7 Check model for redundancy.
Step 8 Validate conceptual model against user transaction.
Step 9 Review conceptual data model with user.
ER DIAGRAM :
PROGRAM:
-- Creating a student table with specified columns
CREATE TABLE student (
name VARCHAR(100),
age INT,
roll_no INT PRIMARY KEY
);
-- Inserting 3 sets of values into the student table
INSERT INTO student (name, age, roll_no)
VALUES ('John Doe', 22, 1),
('Jane Doe', 21, 2),
('Sam Smith', 20, 3);
-- Using SELECT to display the student table
SELECT * FROM student;
-- Creating a faculty table with specified columns
CREATE TABLE faculty (
name VARCHAR(100),
age INT,
staff_id INT PRIMARY KEY
);
-- Inserting 3 sets of values into the faculty table
INSERT INTO faculty (name, age, staff_id)
VALUES ('Dr. Adam Smith', 40, 1),
('Dr. Jane Brown', 35, 2),
('Dr. Tom Johnson', 32, 3);
-- Using SELECT to display the faculty table
SELECT * FROM faculty;
-- Creating a department table with specified columns
CREATE TABLE department (
dept_id INT PRIMARY KEY,
dept_ name VARCHAR(100),
location VARCHAR(100)
);
-- Inserting 3 sets of values into the department table
INSERT INTO department (dept_id, dept_name, location)
VALUES (1, 'Computer Science', 'Main Campus'),
(2, 'Mathematics', 'Main Campus'),
(3, 'Physics', 'Main Campus');
-- Using SELECT to display the department table
SELECT * FROM department;
OUTPUT:
CREATE TABLE
INSERT 0 3
CREATE TABLE
INSERT 0 3
CREATE TABLE
INSERT 0 3
RESULT:
Thus the database design using conceptual modeling (ER-EER) and map it to
relational database using normalization for college management system is performed
successfully.
EX.NO : 2(b) DATABASE DESIGN USING CONCEPTUAL MODELING (ER-EER) –
TOP-DOWN APPROACH MAPPING CONCEPTUAL TO RELATIONAL
DATE: DATABASE AND VALIDATE USING NORMALIZATION FOR
HOSPITAL MANAGEMENT SYSTEM
AIM:
To design a database using conceptual modeling (ER-EER) and map it to a relational
database using normalization for hospital management system.
CONCEPTUAL DESIGN:
The process of constructing a model of the data used in an enterprise, independent of all
physical considerations.
Ideas → High-level design → Relational database schema → Relational DBMS
COMMANDS:
Commands used in this program:
• CREATE
• INSERT
• DELETE
PROCEDURE TO BUILD CONCEPTUAL DATA MODELS:
Step 1 Identify entity types.
Step 2 Identify relationship types.
Step 3 Identify and associate attributes with entity or relationship types.
Step 4 Determine attribute domains.
Step 5 Determine candidate, primary, and alternate key attributes.
Step 6 Consider use of enhanced modelling concepts (optional step).
Step 7 Check model for redundancy.
Step 8 Validate conceptual model against user transaction.
Step 9 Review conceptual data model with user.
ER DIAGRAM :
PROGRAM :
-- Creating a patient table with specified columns
CREATE TABLE patient (
name VARCHAR(100),
age INT,
patient_id INT PRIMARY KEY,
diagnosis VARCHAR(100),
doctor_id INT
);
-- Creating a doctor table with specified columns
CREATE TABLE doctor (
name VARCHAR(100),
age INT,
doctor_id INT PRIMARY KEY,
specialization VARCHAR(100),
salary INT
);
-- Adding the correct references to the doctor_id column in the patient table
ALTER TABLE patient
ADD FOREIGN KEY (doctor_id) REFERENCES doctor(doctor_id);
-- Using SELECT to display the patient table
SELECT * FROM patient;
-- Using SELECT to display the doctor table
SELECT * FROM doctor;
-- Creating a hospital table with specified columns
CREATE TABLE hospital (
hospital_id INT PRIMARY KEY,
hospital_name VARCHAR(100),
location VARCHAR(100)
);
-- Inserting 3 sets of values into the hospital table
INSERT INTO hospital (hospital_id, hospital_name, location)
VALUES (1, 'ABC Hospital', 'Coimbatore'),
(2, 'XYZ Hospital', 'Chennai'),
(3, 'PQR Hospital', 'Madurai');
-- Using SELECT to display the hospital table
SELECT * FROM hospital;
OUTPUT :
CREATE TABLE
CREATE TABLE
ALTER TABLE
CREATE TABLE
RESULT :
Thus the database design using conceptual modeling (ER-EER) and map it to
relational database using normalization for hospital management system is performed
successfully.
EX.NO : 2(c) DATABASE DESIGN USING CONCEPTUAL MODELING (ER-EER) –
TOP-DOWN APPROACH MAPPING CONCEPTUAL TO RELATIONAL
DATE: DATABASE AND VALIDATE USING NORMALIZATION FOR HOTEL
MANAGEMENT SYSTEM
AIM:
To design a database using conceptual modeling (ER-EER) and map it to a relational
database using normalization for hotel management system.
CONCEPTUAL DESIGN:
The process of constructing a model of the data used in an enterprise, independent of all
physical considerations.
Ideas → High-level design → Relational database schema → Relational DBMS
COMMANDS:
Commands used in this program:
• CREATE
• INSERT
• DELETE
PROCEDURE TO BUILD CONCEPTUAL DATA MODELS:
Step 1 Identify entity types.
Step 2 Identify relationship types.
Step 3 Identify and associate attributes with entity or relationship types.
Step 4 Determine attribute domains.
Step 5 Determine candidate, primary, and alternate key attributes.
Step 6 Consider use of enhanced modelling concepts (optional step).
Step 7 Check model for redundancy.
Step 8 Validate conceptual model against user transaction.
Step 9 Review conceptual data model with user.
ER DIAGRAM :
PROGRAM :
-- Creating a room table with specified columns
CREATE TABLE room (
room_no INT PRIMARY KEY,
room_type VARCHAR(100),
price INT
);
-- Inserting 3 sets of values into the room table
INSERT INTO room (room_no, room_type, price)
VALUES (101, 'Single', 1000),
(102, 'Double', 1500),
(103, 'Suite', 2000);
-- Using SELECT to display the room table
SELECT * FROM room;
-- Creating a guest table with specified columns
CREATE TABLE guest (
name VARCHAR(100),
age INT,
guest_id INT PRIMARY KEY,
room_no INT,
check_in_date DATE,
check_out_date DATE,
FOREIGN KEY (room_no) REFERENCES room(room_no)
);
-- Inserting 3 sets of values into the guest table
INSERT INTO guest (name, age, guest_id, room_no, check_in_date, check_out_date)
VALUES ('George Lee', 28, 1, 101, '2023-12-01', '2023-12-03'),
('Helen Chen', 32, 2, 102, '2023-12-02', '2023-12-04'),
('Ivan Wang', 36, 3, 103, '2023-12-03', '2023-12-05');
-- Using SELECT to display the guest table
SELECT * FROM guest;
-- Creating a hotel table with specified columns
CREATE TABLE hotel (
hotel_id INT PRIMARY KEY,
hotel_name VARCHAR(100),
location VARCHAR(100)
);
-- Inserting 3 sets of values into the hotel table
INSERT INTO hotel (hotel_id, hotel_name, location)
VALUES (1, 'ABC Hotel', 'Coimbatore'),
(2, 'XYZ Hotel', 'Chennai'),
(3, 'PQR Hotel', 'Madurai');
-- Using SELECT to display the hotel table
SELECT * FROM hotel;
OUTPUT :
CREATE TABLE
INSERT 0 3
CREATE TABLE
INSERT 0 3
CREATE TABLE
INSERT 0 3
RESULT :
Thus the database design using conceptual modeling (ER-EER) and map it to
relational database using normalization for hotel management system is performed successfully.
EX.NO : 2(d) DATABASE DESIGN USING CONCEPTUAL MODELING (ER-EER) –
TOP-DOWN APPROACH MAPPING CONCEPTUAL TO RELATIONAL
DATE: DATABASE AND VALIDATE USING NORMALIZATION FOR BANK
MANAGEMENT SYSTEM
AIM:
To design a database using conceptual modeling (ER-EER) and map it to a relational
database using normalization for bank management system.
CONCEPTUAL DESIGN:
The process of constructing a model of the data used in an enterprise, independent of all
physical considerations.
Ideas → High-level design → Relational database schema → Relational DBMS
COMMANDS:
Commands used in this program:
• CREATE
• INSERT
• DELETE
PROCEDURE TO BUILD CONCEPTUAL DATA MODELS:
Step 1 Identify entity types.
Step 2 Identify relationship types.
Step 3 Identify and associate attributes with entity or relationship types.
Step 4 Determine attribute domains.
Step 5 Determine candidate, primary, and alternate key attributes.
Step 6 Consider use of enhanced modelling concepts (optional step).
Step 7 Check model for redundancy.
Step 8 Validate conceptual model against user transaction.
Step 9 Review conceptual data model with user.
ER DIAGRAM :
PROGRAM :
-- Creating a branch table with specified columns
CREATE TABLE branch (
branch_id INT PRIMARY KEY,
branch_name VARCHAR(100),
location VARCHAR(100)
);
-- Creating a customer table with specified columns
CREATE TABLE customer (
name VARCHAR(100),
age INT,
customer_id INT PRIMARY KEY,
account_no INT,
address VARCHAR(100)
);
-- Creating an account table with specified columns
CREATE TABLE account (
account_no INT PRIMARY KEY,
balance INT,
interest_rate DECIMAL(2,2),
branch_id INT,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customer(customer_id),
FOREIGN KEY (branch_id) REFERENCES branch(branch_id)
);
-- Inserting 3 sets of values into the customer table
INSERT INTO customer (name, age, customer_id, account_no, address)
VALUES ('Jack Lee', 26, 1, 1001, 'Coimbatore'),
('Kelly Chen', 31, 2, 1002, 'Chennai'),
('Leo Wang', 34, 3, 1003, 'Madurai');
-- Inserting 3 sets of values into the account table
INSERT INTO account (account_no, balance, interest_rate, branch_id, customer_id)
VALUES (1001, 10000, 0.05, 1, 1),
(1002, 15000, 0.06, 2, 2),
(1003, 20000, 0.07, 3, 3);
-- Inserting 3 sets of values into the branch table
INSERT INTO branch (branch_id, branch_name, location)
VALUES (1, 'ABC Bank', 'Coimbatore'),
(2, 'XYZ Bank', 'Chennai'),
(3, 'PQR Bank', 'Madurai');
-- Using SELECT to display the customer table
SELECT * FROM customer;
-- Using SELECT to display the account table
SELECT * FROM account;
-- Using SELECT to display the branch table
SELECT * FROM branch;
OUTPUT :
CREATE TABLE
INSERT 0 3
CREATE TABLE
INSERT 0 3
CREATE TABLE
INSERT 0 3
RESULT :
Thus the database design using conceptual modeling (ER-EER) and map it to
relational database using normalization for bank management system is performed successfully.
EX.NO : 3
IMPLEMENT THE DATABASE USING SQL DATA DEFINITION WITH
DATE: CONSTRAINTS, VIEWS
AIM :
To implement the database using SQL data definition language and create constraints
and views.
COMMAND :
Commands used in this program
• Create
• Alter
• Drop
• Truncate
PROCEDURE :
1. Create a new database for the student system using CREATE DATABASE statement.
2. Use CREATE TABLE to establish the "Students" table with columns: StudentID (Primary
Key, Identity), FirstName (Not Null), LastName (Not Null), Email (Unique), and DepartmentID
(Foreign Key).
3. Create additional tables (e.g., Departments, Courses, Enrollments) with appropriate
constraints using CREATE TABLE.
4. Utilize CREATE VIEW to make querying data easier, like creating a view showing students
enrolled in a specific department.
5. Test the created views and tables by running queries to ensure they function as expected.
6. Modify existing table structures if needed using the ALTER TABLE statement.
7. If necessary, remove tables from the student database permanently using the DROP TABLE
statement. Exercise caution, as this action deletes the table and its data.
8. Retrieve and display all records from the "student" table after the deletion. 1. Create a new
database for the student system using CREATE DATABASE statement.
2. Use CREATE TABLE to establish the "Students" table with columns: StudentID (Primary
Key, Identity), FirstName (Not Null), LastName (Not Null), Email (Unique), and DepartmentID
(Foreign Key).
3. Create additional tables (e.g., Departments, Courses, Enrollments) with appropriate
constraints using CREATE TABLE.
4. Utilize CREATE VIEW to make querying data easier, like creating a view showing students
enrolled in a specific department.
5. Test the created views and tables by running queries to ensure they function as expected.
6. Modify existing table structures if needed using the ALTER TABLE statement.
7. If necessary, remove tables from the student database permanently using the DROP TABLE
statement. Exercise caution, as this action deletes the table and its data.
8. Retrieve and display all records from the "student" table after the deletion.
PROGRAM :
-- Create Student Table
CREATE TABLE student (
student_id INT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
major VARCHAR(50),
gpa DECIMAL(3,2) CHECK (gpa >= 0.0 AND gpa <= 4.0)
);
-- Create Assignment Table
CREATE TABLE assignment (
assignment_id INT PRIMARY KEY,
student_id INT,
assignment_name VARCHAR(50) NOT NULL,
due_date DATE NOT NULL,
submitted BOOLEAN DEFAULT FALSE,
CONSTRAINT fk_student_id
FOREIGN KEY (student_id)
REFERENCES student(student_id)
);
-- Insert Student Records
INSERT INTO student (student_id, first_name, last_name, email, major, gpa)
VALUES
(1, 'John', 'Doe', 'john.doe@email.com', 'Computer Science', 3.8),
(2, 'Jane', 'Smith', 'jane.smith@email.com', 'Physics', 3.9),
(3, 'Bob', 'Johnson', 'bob.johnson@email.com', 'Engineering', 3.4);
-- Create Honor Roll View (constraints)
CREATE VIEW honor_roll AS
SELECT * FROM student
WHERE gpa >= 3.5;
-- Update Student Major
UPDATE student
SET major = 'Mathematics'
WHERE student_id = 1;
-- Select Student Records
SELECT * FROM student;
---View honor_roll
Select * from honor_roll
-- Delete Student Record
DELETE FROM student
WHERE student_id = 1;
-- Select Remaining Student Records
SELECT * FROM student;
OUTPUT :
CREATE TABLE
CREATE TABLE
INSERT 0 3
CREATE VIEW
UPDATE 1
DELETE 1
RESULT :
Thus the implementation of the database using SQL data definition with constraints,
views is performed successfully.
EX.NO : 4
QUERY THE DATABASE USING SQL MANIPULATION
DATE:
AIM :
To query the database using SQL data manipulation language and perform various
operations on the data.
DATA MANIPULATION LANGUAGE COMMANDS:
DML used to manipulation the database or table’s data The DML commands are
• Insert
• Update
• Delete
• Select
PROCEDURE :
1. Create a table named "Student" with columns: StudentID (primary key), FirstName,
LastName, Age, and GPA.
2. Insert multiple student records with details, including StudentID, FirstName, LastName, Age,
and GPA, into the "Student" table.
3. Retrieve and display all student records from the "Student" table using the SELECT
command.
4. Identify a specific student by StudentID using the WHERE clause with the UPDATE
command.
- Increment the student's Age by 1 and multiply their GPA by 1.1.
5. Identify a specific student by StudentID using the WHERE clause with the DELETE
command.
- Remove the corresponding record from the "Student" table.
6. Retrieve and display students with a GPA greater than 3.5 or whose StudentID is in a
specified list using the SELECT command.
- Optionally, use an alias for the GPA column with AS.
- Employ the WHERE clause with conditions for GPA and StudentID.
7. Retrieve and display students whose StudentID is not in a specified list using the SELECT
command.
- Filter records based on an age range (e.g., BETWEEN 20 AND 22) with the WHERE
clause.
- Order the results by GPA in descending order using the ORDER BY command.
PROGRAM :
-- Create a Student table
CREATE TABLE Student (
StudentID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Age INT,
GPA FLOAT
);
-- Insert data into the Student table
INSERT INTO Student VALUES
(1, 'John', 'Doe', 20, 3.5),
(2, 'Jane', 'Smith', 22, 3.9),
(3, 'Bob', 'Johnson', 21, 3.2),
(4, 'Alice', 'Brown', 23, 3.8),
(5, 'Charlie', 'Miller', 19, 3.4);
-- Select all students
SELECT * FROM Student;
-- Update student information (increase age and GPA)
UPDATE Student
SET Age = Age + 1, GPA = GPA * 1.1
WHERE StudentID = 1;
-- Delete a student
DELETE FROM Student
WHERE StudentID = 3;
-- Select students with GPA greater than 3.5 or in a specific list
SELECT StudentID, FirstName, LastName, GPA AS GradePointAverage
FROM Student
WHERE GPA > 3.5 OR StudentID IN (1, 2, 4)
ORDER BY GPA DESC;
-- Select students not in a specific list and age between 20 and 22, order by GPA
SELECT StudentID, FirstName, LastName, GPA AS GradePointAverage
FROM Student
WHERE StudentID NOT IN (1)
AND Age BETWEEN 20 AND 22
ORDER BY GPA DESC;
OUTPUT :
CREATE TABLE
INSERT 0 5
UPDATE 1
DELETE 1
RESULT :
Thus the query on the database using SQL manipulation is performed
successfully.
EX.NO : 5(a)
QUERYING/MANAGING THE DATABASE USING SQL PROGRAMMING -
STORED PROCEDURES/FUNCTIONS - CONSTRAINTS AND SECURITY
DATE: USING TRIGGERS
AIM :
To manage the database using SQL programming and create stored procedures,
functions, triggers, and security features.
COMMANDS :
Commands used in this program
• CREATE PROCEDURE
• CREATE FUNCTION
• ALTER PROCEDURE
• ALTER FUNCTION
• DROP PROCEDURE
• DROP FUNCTION
• EXECUTE
• CALL
• DECLARE
• SET
• SELECT
• INSERT
• UPDATE
• DELETE
• BEGIN
• END
• IF
• ELSE
• WHILE
• RETURN
PROCEDURE :
1. Defines the structure of the "Employees" table with columns for EmployeeID, FirstName,
LastName, Department, and Salary, specifying EmployeeID as the primary key.
2. Inserts sample data into the "Employees" table with Indian names, employee IDs,
departments, and salaries.
3. Defines a stored procedure named GetEmployeeDetails to retrieve all information for a
specific employee based on the provided EmployeeID using the SELECT command.
4. Defines a function named UpdateSalary to modify an employee's salary based on the
provided EmployeeID using the UPDATE command and returns the number of affected rows
using @@ROWCOUNT.
5. Defines a stored procedure named AddEmployee to add a new employee record with
provided details using the INSERT INTO command.
6. Retrieves all records from the "Employees" table using the SELECT command.
7. Filters and retrieves employees who work in the IT department using the SELECT command
with a WHERE clause.
8. Filters and retrieves employees with a salary greater than 60000.00 using the SELECT
command with a WHERE clause.
PROGRAM :
-- Create Employees table
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Department VARCHAR(50),
Salary DECIMAL(10,2)
);
-- Insert sample data with Indian names
INSERT INTO Employees (EmployeeID, FirstName, LastName, Department, Salary)
VALUES
(1, 'Rahul', 'Sharma', 'IT', 60000.00),
(2, 'Priya', 'Verma', 'HR', 55000.00),
(3, 'Amit', 'Patel', 'Finance', 70000.00);
-- Create GetEmployeeDetails function
CREATE OR REPLACE FUNCTION GetEmployeeDetails(
employee_id_param INT
) RETURNS TABLE (
EmployeeID INT,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Department VARCHAR(50),
Salary DECIMAL(10,2)
) AS $$
BEGIN
RETURN QUERY
SELECT *
FROM Employees
WHERE EmployeeID = employee_id_param;
END;
$$ LANGUAGE plpgsql;
-- Create UpdateSalary function
CREATE OR REPLACE FUNCTION UpdateSalary(
employee_id_param INT, new_salary_param DECIMAL(10,2)
) RETURNS INT AS $$
BEGIN
UPDATE Employees
SET Salary = new_salary_param
WHERE EmployeeID = employee_id_param;
RETURN FOUND; -- Return true if a row was affected
END;
$$ LANGUAGE plpgsql;
-- Create AddEmployee function
CREATE OR REPLACE FUNCTION AddEmployee(
first_name_param VARCHAR(50),
last_name_param VARCHAR(50),
department_param VARCHAR(50),
salary_param DECIMAL(10,2)
) RETURNS VOID AS $$
BEGIN
INSERT INTO Employees (FirstName, LastName, Department, Salary)
VALUES (first_name_param, last_name_param, department_param, salary_param);
END;
$$ LANGUAGE plpgsql;
-- Select all employees
SELECT * FROM Employees;
-- Select employees in the IT department
SELECT * FROM Employees WHERE Department = 'IT';
-- Select employees with a salary greater than 60000
SELECT * FROM Employees WHERE Salary > 60000.00;
OUTPUT :
CREATE TABLE
INSERT 0 3
CREATE FUNCTION
CREATE FUNCTION
CREATE FUNCTION
RESULT :
Thus the querying/managing on the database using SQL programming - stored
procedures/functions is performed successfully.
EX.NO : 5(b)
QUERYING/MANAGING THE DATABASE USING SQL PROGRAMMING -
STORED PROCEDURES/FUNCTIONS - CONSTRAINTS AND SECURITY
DATE: USING TRIGGERS
AIM :
To manage the database using SQL programming and create stored procedures,
functions, triggers, and security features.
COMMANDS :
Commands used in this program.
• CREATE PROCEDURE
• CREATE FUNCTION
• ALTER PROCEDURE
• ALTER FUNCTION
• DROP PROCEDURE
• DROP FUNCTION
• EXECUTE
• CALL
• DECLARE
• SET
• SELECT
• INSERT
• UPDATE
• DELETE
• BEGIN
• END
• IF
• ELSE
• WHILE
• RETURN
PROCEDURE :
1. The script initiates by establishing a table named "Employees" with fundamental attributes
such as EmployeeID, FirstName, LastName, Salary, and HireDate.
2. The introduction of a trigger called "SalaryConstraint" adds a layer of validation, ensuring
that salaries below $30,000 are restricted during both insertion and updating operations.
3. Another pivotal trigger, "LogChanges," is implemented to systematically record alterations
post-insertion, updating, or deletion events. This trigger captures essential details like action
type (add, update, delete), employee ID, and the timestamp of the change in the designated
ChangeLog table.
4. To illustrate the functionality, the script populates the Employees table with sample data for
two employees, providing specific details such as EmployeeID, names, salary, and hire dates.
5. Employing the SELECT statement, the script retrieves and showcases all available records
within the Employees table, presenting comprehensive information about each employee.
6. In addition, a SELECT statement filters and retrieves records from the Employees table
where the salary surpasses $35,000, offering a targeted view of higher-salaried employees.
7. A subsequent UPDATE statement dynamically adjusts the salary of the employee with
EmployeeID 1 to $38,000, showcasing the script's ability to modify existing data.
8. Lastly, a DELETE statement is utilized to remove the employee with EmployeeID 2 from the
Employees table, highlighting the script's capability to manage and eliminate specific records.
PROGRAM :
-- Creating Employees table
CREATE TABLE Employees (
EmployeeID SERIAL PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Salary DECIMAL(10, 2),
HireDate DATE
);
-- Creating ChangeLog table for PostgreSQL
CREATE TABLE ChangeLog (
LogID SERIAL PRIMARY KEY,
EmployeeID INT,
ActionMessage VARCHAR(255),
ActionTime TIMESTAMP
);
-- Creating a Trigger to enforce a salary constraint for PostgreSQL
CREATE OR REPLACE FUNCTION enforce_salary_constraint()
RETURNS TRIGGER AS $$
BEGIN
IF NEW.Salary < 30000 THEN
RAISE EXCEPTION 'Salary must be at least $30,000';
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER SalaryConstraint
BEFORE INSERT OR UPDATE ON Employees
FOR EACH ROW
EXECUTE FUNCTION enforce_salary_constraint();
-- Creating a Trigger for logging changes for PostgreSQL
CREATE OR REPLACE FUNCTION log_changes()
RETURNS TRIGGER AS $$
BEGIN
IF TG_OP = 'UPDATE' AND NEW.EmployeeID IS NOT NULL AND OLD.EmployeeID IS
NOT NULL THEN
INSERT INTO ChangeLog (EmployeeID, ActionMessage, ActionTime)
VALUES (COALESCE(NEW.EmployeeID, OLD.EmployeeID), 'Employee information
updated', CURRENT_TIMESTAMP);
ELSIF TG_OP = 'INSERT' AND NEW.EmployeeID IS NOT NULL THEN
INSERT INTO ChangeLog (EmployeeID, ActionMessage, ActionTime)
VALUES (NEW.EmployeeID, 'Employee added', CURRENT_TIMESTAMP);
ELSIF TG_OP = 'DELETE' THEN
INSERT INTO ChangeLog (EmployeeID, ActionMessage, ActionTime)
VALUES (OLD.EmployeeID, 'Employee deleted', CURRENT_TIMESTAMP);
END IF;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER LogChanges
AFTER INSERT OR UPDATE OR DELETE ON Employees
FOR EACH ROW
EXECUTE FUNCTION log_changes();
-- Inserting sample data
INSERT INTO emploo (employeeid,FirstName, LastName, Salary, HireDate)
VALUES
(1,'John', 'Doe', 35000, '2023-01-01'),
(2,'Jane', 'Smith', 40000, '2023-02-15');
-- Selecting all employees
SELECT * FROM Employees;
-- Selecting employees with a salary above $35,000
SELECT * FROM Employees WHERE Salary > 35000;
-- Updating an employee's salary
UPDATE Employees SET Salary = 38000 WHERE EmployeeID = 1;
-- Deleting an employee
DELETE FROM Employees WHERE EmployeeID = 2;
-- Selecting all employees
SELECT * FROM Employees;
OUTPUT :
CREATE TABLE
CREATE TABLE
CREATE FUNCTION
CREATE TRIGGER
CREATE FUNCTION
CREATE TRIGGER
INSERT 0 2
UPDATE 1
DELETE 1
RESULT :
Thus querying/managing on the database using programming - stored
procedures/functions - constraints and security using triggers
EX.NO : 6 DATABASE DESIGN USING NORMALIZATION – BOTTOM-UP
DATE: APPROACH
AIM :
To design a database using normalization and decompose the relations into smaller ones
based on functional dependencies.
COMMANDS :
Commands used in this program.
1. Table Creation Commands:
- CREATE TABLE
2. Primary Key Constraint Commands:
- PRIMARY KEY
3. Foreign Key Constraint Commands:
- CONSTRAINT
- FOREIGN KEY
- REFERENCES
4. Data Types Commands:
- INT
- VARCHAR
- DATE
- CHAR
- DECIMAL
- TIME
5. Select Statement Commands:
- SELECT
- FROM
- JOIN
- WHERE
6. Alter Table Commands:
- ALTER TABLE
PROCEDURE :
1. Normalization Purpose:
- Analyze functional dependencies between attributes/data items.
- Reduce complex user views to small, stable subgroups for logical data modeling.
2. Normalization Levels:
- First Normal Form (1NF):
- Domain of an attribute must include only atomic values.
- Disallows multivalued attributes and relations within relations.
- Second Normal Form (2NF):
- A relation is in 2NF if it's in 1NF and has no partial dependency.
- Full functional dependency is crucial (x-(A))→y, where A→x doesn't hold.
- Third Normal Form (3NF):
- A relation is in 3NF if it's in 2NF and has no transitive dependency.
- Transitive dependency involves attributes z that aren't a candidate key.
3. 1NF Command Usage:
- Use CREATE TABLE to define tables with atomic values in attribute domains.
- Avoid creating tables with multivalued or composite attributes.
4. 2NF Command Usage:
- Ensure the relation is in 1NF using CREATE TABLE.
- Establish full functional dependencies by designing tables with proper primary keys.
- Use ALTER TABLE to modify tables if needed.
5. 3NF Command Usage:
- Confirm the relation is in 2NF using CREATE TABLE.
- Eliminate transitive dependencies by organizing tables appropriately.
- Utilize ALTER TABLE for modifications if required.
6. Overall Best Practices:
- Use foreign keys (FOREIGN KEY) to establish relationships between tables.
- Regularly check for anomalies and dependencies that violate normal forms.
- Employ proper indexing for performance improvement, considering specific querying needs.
7. Example Select Statements:
- Use SELECT statements to retrieve data based on normalized structure.
- Implement joins (JOIN) to combine information from different tables.
This breakdown emphasizes the conceptual steps of normalization and the practical use of SQL
commands for creating and modifying tables to achieve normalization.
PROGRAM :
-- Creating the Doctor table
CREATE TABLE Doctor (
DoctorID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Specialization VARCHAR(50),
Salary DECIMAL(10, 2)
);
-- Creating the Patient table
CREATE TABLE Patient (
PatientID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
DOB DATE,
Gender CHAR(1),
Address VARCHAR(100)
);
-- Creating the MedicalRecord table with foreign keys
CREATE TABLE MedicalRecord (
RecordID INT PRIMARY KEY,
PatientID INT,
DoctorID INT,
Diagnosis VARCHAR(100),
Prescription VARCHAR(200),
CONSTRAINT FK_MedicalRecord_Patient FOREIGN KEY (PatientID) REFERENCES
Patient(PatientID),
CONSTRAINT FK_MedicalRecord_Doctor FOREIGN KEY (DoctorID) REFERENCES
Doctor(DoctorID)
);
-- Example values for Doctor and Patient tables
INSERT INTO Doctor VALUES (1, 'John', 'Doe', 'Cardiologist', 120000.00);
INSERT INTO Patient VALUES (1, 'Alice', 'Johnson', '1990-05-15', 'F', '123 Main St');
-- Creating DoctorContact and PatientContact tables for contact information
CREATE TABLE DoctorContact (
DoctorID INT PRIMARY KEY,
Email VARCHAR(100),
Phone VARCHAR(15),
CONSTRAINT FK_DoctorContact_Doctor FOREIGN KEY (DoctorID) REFERENCES
Doctor(DoctorID)
);
CREATE TABLE PatientContact (
PatientID INT PRIMARY KEY,
Email VARCHAR(100),
Phone VARCHAR(15),
CONSTRAINT FK_PatientContact_Patient FOREIGN KEY (PatientID) REFERENCES
Patient(PatientID)
);
-- Example values for DoctorContact and PatientContact tables
INSERT INTO DoctorContact VALUES (1, 'john.doe@email.com', '123-456-7890');
INSERT INTO PatientContact VALUES (1, 'alice.j@email.com', '111-222-3333');
-- Creating DoctorSchedule table for scheduling information
CREATE TABLE DoctorSchedule (
DoctorID INT,
DayOfWeek VARCHAR(10),
ShiftStartTime TIME,
ShiftEndTime TIME,
PRIMARY KEY (DoctorID, DayOfWeek),
CONSTRAINT FK_DoctorSchedule_Doctor FOREIGN KEY (DoctorID) REFERENCES
Doctor(DoctorID)
);
-- Example value for DoctorSchedule table
INSERT INTO DoctorSchedule VALUES (1, 'Monday', '08:00:00', '16:00:00');
-- Creating Department table
CREATE TABLE Department (
DepartmentID INT PRIMARY KEY,
DepartmentName VARCHAR(50)
);
-- Creating DoctorDepartment table for doctor and department relationship
CREATE TABLE DoctorDepartment (
DoctorID INT,
DepartmentID INT,
PRIMARY KEY (DoctorID),
CONSTRAINT FK_DoctorDepartment_Doctor FOREIGN KEY (DoctorID) REFERENCES
Doctor(DoctorID),
CONSTRAINT FK_DoctorDepartment_Department FOREIGN KEY (DepartmentID)
REFERENCES Department(DepartmentID)
);
-- Example value for Department table
INSERT INTO Department VALUES (1, 'Cardiology');
-- Example value for DoctorDepartment table
INSERT INTO DoctorDepartment VALUES (1, 1);
-- Retrieve all patients of a specific doctor with their medical records
SELECT Patient.FirstName, Patient.LastName, MedicalRecord.Diagnosis,
MedicalRecord.Prescription
FROM Patient
JOIN MedicalRecord ON Patient.PatientID = MedicalRecord.PatientID
WHERE MedicalRecord.DoctorID = 1;
-- Get contact information for a specific doctor
SELECT Doctor.FirstName, Doctor.LastName, DoctorContact.Email, DoctorContact.Phone
FROM Doctor
JOIN DoctorContact ON Doctor.DoctorID = DoctorContact.DoctorID
WHERE Doctor.DoctorID = 1;
-- List doctors and their schedules for a given day
SELECT Doctor.FirstName, Doctor.LastName, DoctorSchedule.DayOfWeek,
DoctorSchedule.ShiftStartTime, DoctorSchedule.ShiftEndTime
FROM Doctor
JOIN DoctorSchedule ON Doctor.DoctorID = DoctorSchedule.DoctorID
WHERE DoctorSchedule.DayOfWeek = 'Monday';
-- Retrieve all doctors in a specific department
SELECT Doctor.FirstName, Doctor.LastName, Department.DepartmentName
FROM Doctor
JOIN DoctorDepartment ON Doctor.DoctorID = DoctorDepartment.DoctorID
JOIN Department ON DoctorDepartment.DepartmentID = Department.DepartmentID
WHERE Department.DepartmentName = 'Cardiology';
OUTPUT :
CREATE TABLE
CREATE TABLE
CREATE TABLE
INSERT 0 1
INSERT 0 1
CREATE TABLE
CREATE TABLE
INSERT 0 1
INSERT 0 1
CREATE TABLE
INSERT 0 1
CREATE TABLE
CREATE TABLE
INSERT 0 1
INSERT 0 1
RESULT :
Thus the database design using normalization – bottom-up approach is performed
successfully.
EX.NO : 7
DEVELOPING A DATABASE APPLICATIONS USING VISUALSTUDIO
DATE:
AIM :
To develop an Employee Management System using VisualStudio
PROCEDURE :
1. Import Modules: Import the sqlite3, tkinter, and tkinter.ttk modules.
2. Create Database: Establish a connection to the SQLite database and create a cursor object.
3. Define Table: Create a table named "employees" with specified fields (id, name, age, doj,
email, gender, contact, address).
4. Insert Data: Insert sample data into the "employees" table.
5. Fetch and Display Data: Retrieve all data from the table and display it.
6. Import Database Module: Import the db.py module.
7. Create Root Window: Create a root window for the GUI application.
8. Configure Window: Set title, geometry, background color, and state (zoomed) of the root
window.
9. Importing tkinter.ttk Module: Import the tkinter.ttk module.
10. Finalize Database Creation: Commit changes, close the database connection, and finalize
the database creation process.
PROGRAM :
import sqlite3
from tkinter import *
from tkinter import ttk, messagebox
# Database setup
db = sqlite3.connect("employee_database.db")
cursor = db.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS employees (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER,
doj TEXT,
email TEXT,
gender TEXT,
contact TEXT,
address TEXT
''')
db.commit()
# Functions
def add_employee():
# ... [same as before]
def update_employee():
# ... [same as before]
def delete_employee():
# ... [same as before]
def clear_all_entries():
# ... [same as before]
def get_data(event):
# ... [same as before]
def display_all_records():
# ... [same as before]
# GUI
root = Tk()
root.title("Employee Management System")
root.geometry("1080x720+0+0")
root.config(bg="#2c3e50")
entries_frame = Frame(root, bg="#535c68")
entries_frame.pack(side=TOP, fill=X)
labels = ["Name", "Age", "D.O.J", "Email", "Gender", "Contact"]
entries = [Entry(entries_frame, font=("Calibri", 16), width=30) for _ in range(6)]
address_text = Text(entries_frame, width=94, height=5, font=("Calibri", 16))
for label, entry in zip(labels, entries):
Label(entries_frame, text=label, font=("Calibri", 16), bg="#535c68",
fg="white").pack(side=LEFT, padx=10, pady=10)
entry.pack(side=LEFT, padx=10, pady=10)
# Buttons
Button(entries_frame, command=add_employee, text="Add", width=15, font=("Calibri", 16,
"bold"), bg="#16a085", bd=0).pack(side=LEFT, padx=10)
Button(entries_frame, command=update_employee, text="Update", width=15, font=("Calibri",
16, "bold"), bg="#2980b9", bd=0).pack(side=LEFT, padx=10)
Button(entries_frame, command=delete_employee, text="Delete", width=15, font=("Calibri",
16, "bold"), bg="#c0392b", bd=0).pack(side=LEFT, padx=10)
Button(entries_frame, command=clear_all_entries, text="Clear", width=15, font=("Calibri", 16,
"bold"), bg="#f39c12", bd=0).pack(side=LEFT, padx=10)
# Treeview
tv = ttk.Treeview(root)
columns = ["Name", "Age", "D.O.J", "Email", "Gender", "Contact", "Address"]
for idx, col in enumerate(columns, 1):
tv.heading(str(idx), text=col)
tv.column(str(idx), width=10 if idx in [3, 4, 6] else 20)
tv['show'] = 'headings'
tv.bind("<ButtonRelease-1>", get_data)
tv.pack(fill=X)
# Initial data display
display_all_records()
root.mainloop()
OUTPUT :
RESULT:
Thus the application to develop Employee Management System using VisualStudio
is successfully implemented.
EX.NO : 8
DATABASE DESIGN USING EER-TO-ODB MAPPING / UML CLASS
DATE: DIAGRAMS
AIM :
To design a database using EER-to-ODB mapping and create UML class diagrams for
the object-oriented database model.
ALGORITHM :
1. Develop EER or UML diagrams representing system entities, attributes, and relationships.
2. Extract entities and attributes for tables, considering each entity as a table and attributes as
columns.
3. Translate relationships into foreign keys in corresponding tables, considering cardinalities and
participation constraints.
4. Decide on a mapping strategy for inheritance (table-per-class or table-per-hierarchy) for
generalization/specialization.
5. Map aggregations to foreign keys or separate tables.
6. Assign appropriate data types to attributes based on requirements and the DBMS.
7. Apply normalization to eliminate redundancy and anomalies.
8. Establish primary keys, foreign keys, unique constraints, and other integrity constraints.
9. Create a SQL script to implement the database schema, relationships, and constraints.
10. Execute the SQL script to create the database, test and optimize the schema for performance
and functionality, and document the structure.
DETAILS OF THE CLASSES:
1. Library management systemAttributes:
Usertype
Username
PasswordOperations:
Login()
Register()
Logout()
2.User Attributes:
Name
Id Operations: Verify()
CheckAccount()
get_book_info()
3. staff Attributes:
Dept
4. Student Attributes:
Class
5. AccountAttributes:
no_borrowed_books no_reserved_books no_returned_books
no_lost_books fine_amountOperations: Calculate_fine()
6. Book Attributes:
Title
Author
ISBN
publication Operations: Show_duedt()
Reservation_status()
Feedback()
Book_request()
Renew_info()
7. librarianAttributes:
Name
Id
Password
SearchString Operations: Verify_librarian()
Search()
8. Library database
Attributes:
List_of_books Operations:
Add()
Delete()
Update()
Display()
Search()
UML DIAGRAM :
RESULT :
Thus the implementation on database design using eer-to-odb mapping / uml class
diagrams is performed successfully.
EX.NO : 9(a)
OBJECT FEATURES OF TABLES USING UDTS
DATE:
AIM :
To use object feature of tables using UDTs
COMMANDS :
Commands used in this program.
• CREATE
• SELECT
• TYPE
• INSERT
PROCEDURE :
1. Specify the fields and data types for the UDT and create it.
2. Define a table with columns using the UDT.
3. Insert records into the table using the UDT for structured data.
4. Retrieve and display records from the table using SQL queries.
5. Extend the original UDT with additional fields or constraints.
6. Define a new table using the sub-type.
7. Insert records into the table created with the sub-type.
8. Retrieve and display records from the sub-type table using SQL queries.
9. Terminate the procedure once all operations are completed.
PROGRAM :
-- Create a UDT for Address
CREATE TYPE address_type AS (
street VARCHAR(100),
city VARCHAR(50),
country VARCHAR(50)
);
-- Create a table using the UDT
CREATE TABLE employees (
emp_id SERIAL PRIMARY KEY,
emp_name VARCHAR(100),
emp_address address_type
);
-- Inserting data into the table
INSERT INTO employees (emp_name, emp_address)
VALUES
('John Doe', ROW('123 Main St', 'Springfield', 'USA')),
('Jane Smith', ROW('456 Oak Ave', 'Rivertown', 'Canada'));
-- Querying the table
SELECT * FROM employees;
-- Creating a sub-type of the address_type
CREATE TYPE canadian_address AS (
street_address VARCHAR(255),
city VARCHAR(100),
province VARCHAR(50),
postal_code VARCHAR(10)
);
-- Create a new table using the sub-type
CREATE TABLE canadian_employees (
emp_id SERIAL PRIMARY KEY,
emp_name VARCHAR(100),
emp_address canadian_address
);
-- Inserting data into the sub-type table
INSERT INTO canadian_employees (emp_name, emp_address)
VALUES
('Alice Brown', ROW('789 Maple Rd', 'Snowville', 'Canada', 'A1B 2C3'));
-- Querying the sub-type table
SELECT * FROM canadian_employees;
OUTPUT :
CREATE TYPE
CREATE TABLE
INSERT 0 2
CREATE TYPE
CREATE TABLE
INSERT 0 1
RESULT :
Thus use of object features of tables using UDTs is performed successfully.
EX.NO : 9(b)
OBJECT FEATURES OF TABLES USING UDTS
DATE:
AIM :
To use object feature of tables using UDTs
COMMANDS :
Commands used in this program.
• CREATE
• SELECT
• TYPE
• INSERT
PROCEDURE :
1. Define the UDT with specified fields and data types.
2. Create a table that utilizes the UDT for one or more of its columns.
3. Insert records into the table using the UDT for structured data.
4. Retrieve and display records from the table using SQL queries.
5. Update records within the table that involve the UDT columns.
6. Delete specific records from the table.
7. Query and display specific fields or conditions based on UDT attributes.
PROGRAM :
-- Define the UDT
CREATE TYPE address_type AS (
street VARCHAR(100),
city VARCHAR(50),
country VARCHAR(50)
);
-- Create a Table Using the UDT
CREATE TABLE employees (
emp_id SERIAL PRIMARY KEY,
emp_name VARCHAR(100),
emp_address address_type
-- Insert Data into the UDT Table
INSERT INTO employees (emp_name, emp_address)
VALUES
('John Doe', ROW('123 Main St', 'Springfield', 'USA')),
('Jane Smith', ROW('456 Oak Ave', 'Rivertown', 'Canada'));
-- Query the UDT Table
SELECT * FROM employees;
-- Update Data in the UDT Table
UPDATE employees
SET emp_address = ROW('789 Pine St', 'Greenville', 'USA')
WHERE emp_name = 'John Doe';
-- Delete Data from the UDT Table
DELETE FROM employees WHERE emp_name = 'Jane Smith';
-- Query Specific Fields of the UDT
SELECT emp_id, emp_name, emp_address.street FROM employees;
-- Query Using UDT Fields
SELECT * FROM employees WHERE emp_address.city = 'Springfield';
OUTPUT :
CREATE TYPE
CREATE TABLE
INSERT 0
UPDATE 1
DELETE 1
RESULT :
Thus use of object features of tables using UDTs is performed successfully.
EX.NO : 9(c)
OBJECT FEATURES OF INHERITANCE
DATE:
AIM :
To use object features of inheritance.
COMMANDS :
Commands used in this program.
• CREATE
• SELECT
• TYPE
• INSERT
PROCEDURE :
1. Create a parent table with specified columns.
2. Insert records into the parent table.
3. Define a child table that inherits from the parent table.
4. Insert records into the child table, optionally adding new columns.
5. Retrieve and display records from both parent and child tables.
6. Update specific records in the child table.
7. Delete records from the parent table.
8. Query the child table to observe updates and deletions.
PROGRAM :
-- Create Parent Table
CREATE TABLE parent_table (
id SERIAL PRIMARY KEY,
name VARCHAR(100)
);
-- Insert Data into Parent Table
INSERT INTO parent_table (name) VALUES ('Parent Entry 1'), ('Parent Entry 2');
-- Create Child Table Inheriting from Parent
CREATE TABLE child_table (
attribute VARCHAR(50)
) INHERITS (parent_table);
-- Insert Data into Child Table
INSERT INTO child_table (name, attribute) VALUES ('Child Entry 1', 'Attribute 1'), ('Child
Entry 2', 'Attribute 2');
-- Query Parent Table
SELECT * FROM parent_table;
-- Query Child Table
SELECT * FROM child_table;
-- Update Data in Child Table
UPDATE child_table SET name = 'Updated Child Entry' WHERE attribute = 'Attribute 1';
-- Delete Data from Parent Table
DELETE FROM parent_table WHERE name = 'Parent Entry 2';
-- Query Child Table After Update and Delete
SELECT * FROM child_table;
OUTPUT :
CREATE TABLE
INSERT 0 2
CREATE TABLE
INSERT 0 2
UPDATE 1
DELETE 1
RESULT :
Thus use of object features of inheritance is performed successfully.
EX.NO : 9(d)
OBJECT FEATURES OF METHOD DEFINITION
DATE:
AIM :
To use object features of method definition.
COMMANDS :
Commands used in this program.
• CREATE
• SELECT
• TYPE
• INSERT
PROCEDURE :
1. Define a function with a specified name and input parameters.
2. Specify the return type of the function and the language used (e.g., plpgsql for PostgreSQL).
3. Encapsulate the function's logic within a BEGIN...END block.
4. Optionally declare local variables within the function for temporary storage.
5. Use control structures like loops or conditionals to implement the desired functionality.
6. Return the computed or processed result using the RETURN keyword.
7. Call the function in SQL queries to utilize its functionality and display the output.
PROGRAM :
-- Define a function to calculate the area of a circle
CREATE OR REPLACE FUNCTION calculate_circle_area(radius FLOAT)
RETURNS FLOAT AS $$
BEGIN
RETURN 3.14159 * radius * radius;
END;
$$ LANGUAGE plpgsql;
-- Define a function to find the maximum value in an array
CREATE OR REPLACE FUNCTION find_max_value(arr INT[])
RETURNS INT AS $$
DECLARE
max_val INT := arr[1];
i INT;
BEGIN
FOR i IN 2 .. array_length(arr, 1) LOOP
IF arr[i] > max_val THEN
max_val := arr[i];
END IF;
END LOOP;
RETURN max_val;
END;
$$ LANGUAGE plpgsql;
-- Calling the functions
SELECT calculate_circle_area(5.0) AS circle_area;
SELECT find_max_value(ARRAY[4, 7, 2, 9, 5]) AS max_value;
OUTPUT :
CREATE FUNCTION
CREATE FUNCTION
RESULT :
Thus use of object features of method definition is performed successfully.
EX.NO : 10
QUERYING THE OBJECT-RELATIONAL DATABASE USING OBJET
DATE: QUERY LANGUAGE
AIM :
To query the object-relational database using object query language and access the data
stored in the objects.
COMMANDS:
Commands used in this program.
• CREATE TABLE
• INSERT INTO
• SELECT COUNT(*)
• SELECT DISTINCT
• SELECT ... JOIN ... ON
• SELECT *
• DELETE FROM
• UPDATE
• DROP TABLE
PROCEDURE:
1. Define tables with their respective columns, specifying data types and constraints.
2. Insert specific records into the defined tables.
3. Count the number of records in a specified table.
4. Use the DISTINCT operator to retrieve unique values from a column.
5. Perform JOIN operations to fetch common values between two tables based on related
attributes.
6. Utilize the OR operator to fetch rows meeting either of two conditions.
7. Use the AND operator to fetch rows meeting all specified conditions.
8. Apply the LIKE operator with wildcard (%) to fetch rows based on pattern matching.
9. Count the number of rows in a specific table using the COUNT function.
10. Delete specific rows from a table based on certain conditions using the DELETE statement.
11. Update existing rows in a table based on specified conditions using the UPDATE statement.
12. Delete an entire table and its associated data using the DROP TABLE statement.
PROGRAM :
-- Create the staffemployee table
CREATE TABLE staffemployee (
EmployeeId INT,
Name VARCHAR(15),
Skills VARCHAR(30),
Gender VARCHAR(8),
Age INT
);
-- Insert values into the staffemployee table
INSERT INTO staffemployee (EmployeeId, Name, Skills, Gender, Age)
VALUES (6, 'Paul', 'HTML, C++ , Java', 'Male', 26);
-- Create the staffmanagers table
CREATE TABLE staffmanagers (
EmployeeID INT,
EmployeeName VARCHAR(20),
Department VARCHAR(15),
Gender VARCHAR(7),
Age INT
);
-- Insert values into the staffmanagers table
INSERT INTO staffmanagers (EmployeeID, EmployeeName, Department, Gender, Age)
VALUES (1, 'Matt', 'Development', 'Male', 28);
-- Create the staffcontractors table
CREATE TABLE staffcontractors (
EmployeeId INT,
Name VARCHAR(20),
Gender VARCHAR(20),
Age INT,
Extrainfo VARCHAR(50)
);
-- Insert values into the staffcontractors table
INSERT INTO staffcontractors (EmployeeId, Name, Gender, Age, Extrainfo)
VALUES (1, 'Richard', 'Male', 23, 'ContractLength = 1 month; Department = Operations');
-- Count the number of records in the staffmanagers table
SELECT COUNT(*) FROM staffmanagers;
-- Using DISTINCT operator to fetch unique departments from staffmanagers
SELECT DISTINCT Department FROM staffmanagers;
-- Selecting common values from staffemployee and staffmanagers
SELECT e.Name, m.EmployeeName
FROM staffemployee e
JOIN staffmanagers m ON e.EmployeeId = m.EmployeeID;
-- Using OR and AND operators
-- Example: Fetching employees either from 'Development' department or those aged 28
SELECT * FROM staffmanagers WHERE Department = 'Development' OR Age = 28;
-- Example: Fetching employees from 'Development' department and those aged 28
SELECT * FROM staffmanagers WHERE Department = 'Development' AND Age = 28;
-- Using LIKE operator to fetch names starting with 'R'
SELECT * FROM staffcontractors WHERE Name LIKE 'R%';
-- Counting the number of rows in the staffemployee table
SELECT COUNT(*) FROM staffemployee;
-- Deleting values from staffmanagers where the Department is 'Development'
DELETE FROM staffmanagers WHERE Department = 'Development';
-- Updating the Age of employees in staffemployee where the Skills include 'Java'
UPDATE staffemployee SET Age = Age + 1 WHERE Skills LIKE '%Java%';
-- Deleting the staffcontractors table
DROP TABLE staffcontractors;
OUTPUT :
CREATE TABLE
INSERT 0 1
CREATE TABLE
INSERT 0 1
CREATE TABLE
INSERT 0 1
DELETE 1
UPDATE 1
DROP TABLE
RESULT :
Thus Implementation on Querying the Object-relational database using Objet Query
language is performed successfully.