0% found this document useful (0 votes)
12 views32 pages

DBMS lab project

engineering 2nd year dbms project.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views32 pages

DBMS lab project

engineering 2nd year dbms project.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI

[230169]

Practical :- 6
AIM :- Import database from CSV to postgres.
create database
rems; create schema
remsa;
set search_path to remsa;

CREATE TABLE Property (

Property_ID INT PRIMARY KEY

AUTO_INCREMENT, Address VARCHAR(255),

City VARCHAR(100),

State VARCHAR(100),

Zip_Code VARCHAR(10),

Property_Type ENUM('Residential', 'Commercial',

'Industrial'), Size INT, -- Size in square feet

Price DECIMAL(15, 2),

Stats ENUM('Available', 'Sold', 'Rented'),

Date_Listed DATE );

CREATE TABLE Owners (

Owner_ID INT PRIMARY KEY AUTO_INCREMENT,

First_Name VARCHAR(100),

Last_Name VARCHAR(100),

Contact_Number VARCHAR(15),

Email VARCHAR(100),

Address VARCHAR(255),

City VARCHAR(100),

State VARCHAR(100),

Zip_Code VARCHAR(10),

Ownership_Type ENUM('Individual',

'Company'), Date_Of_Ownership DATE );

CREATE TABLE Clients (


AIIE-CSE(B2)
Client_ID INT PRIMARY KEY AUTO_INCREMENT, 1|Page
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]
First_Name VARCHAR(100),

Last_Name VARCHAR(100),

Contact_Number VARCHAR(15),

Email VARCHAR(100),

Address VARCHAR(255),

City VARCHAR(100),

State VARCHAR(100),

Zip_Code VARCHAR(10),

Client_Type ENUM('Buyer', 'Renter') );

CREATE TABLE Agent (

Agent_ID INT PRIMARY KEY AUTO_INCREMENT,

First_Name VARCHAR(100),

Last_Name VARCHAR(100),

Contact_Number VARCHAR(15),

Email VARCHAR(100),

License_Number VARCHAR(50),

Agency_Name VARCHAR(100),

Commission_Rate DECIMAL(5, 2),

Years_Of_Experience INT,

Specialization ENUM('Residential', 'Commercial', 'Industrial') );

CREATE TABLE Transactions (

Transaction_ID INT PRIMARY KEY AUTO_INCREMENT,

Property_ID INT,

Client_ID INT,

Agent_ID INT,

Transaction_Type ENUM('Sale', 'Rent'),

Transaction_Date DATE,

Transaction_Amount DECIMAL(15, 2),

Payment_Method ENUM('Cash',

'Mortgage'), Stats ENUM('Completed',

'Pending'), Commission_Amount

DECIMAL(15, 2),

FOREIGN KEY (Property_ID) REFERENCES Property(Property_ID),


AIIE-CSE(B2) 2|Page
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]
FOREIGN KEY (Client_ID) REFERENCES Clients(Client_ID),

FOREIGN KEY (Agent_ID) REFERENCES Agent(Agent_ID) );

CREATE TABLE Lease (

Lease_ID INT PRIMARY KEY AUTO_INCREMENT,

Property_ID INT,

Client_ID INT,

Agent_ID INT,

Lease_Start_Date DATE,

Lease_End_Date DATE,

Monthly_Rent DECIMAL(15, 2),

Security_Deposit DECIMAL(15, 2),

Payment_Terms ENUM('Monthly', 'Quarterly'),

Stats ENUM('Active', 'Terminated'),

FOREIGN KEY (Property_ID) REFERENCES Property(Property_ID),

FOREIGN KEY (Client_ID) REFERENCES Clients(Client_ID),

FOREIGN KEY (Agent_ID) REFERENCES Agent(Agent_ID) );

CREATE TABLE Maintenance_Request (

Request_ID INT PRIMARY KEY AUTO_INCREMENT,

Property_ID INT,

Client_ID INT,

Request_Date DATE,

Request_Description TEXT,

Stats ENUM('Open', 'In Progress', 'Closed'),

Assigned_Technician VARCHAR(100),

Completion_Date DATE,

Cost DECIMAL(15, 2),

Notes TEXT,

FOREIGN KEY (Property_ID) REFERENCES Property(Property_ID),

FOREIGN KEY (Client_ID) REFERENCES Clients(Client_ID) );

CREATE TABLE Technician (

Technician_ID INT PRIMARY KEY AUTO_INCREMENT,

AIIE-CSE(B2) 3|Page
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]
First_Name VARCHAR(100),

Last_Name VARCHAR(100),

Contact_Number VARCHAR(15),

Email VARCHAR(100),

Specialization ENUM('Plumbing', 'Electrical', 'HVAC', 'General'),

Experience_Years INT,

Certification ENUM('Licensed', 'Certified', 'None'),

Availability_Status ENUM('Available', 'Unavailable'),

Hourly_Rate DECIMAL(10, 2) );

CREATE TABLE Agency (

Agency_ID INT PRIMARY KEY AUTO_INCREMENT,

Agency_Name VARCHAR(100),

Address VARCHAR(255),

City VARCHAR(100),

State VARCHAR(100),

Zip_Code VARCHAR(10),

Contact_Number VARCHAR(15),

Email VARCHAR(100),

License_Number VARCHAR(50),

Number_Of_Agents INT,

Specialization ENUM('Residential', 'Commercial', 'Industrial') );

CREATE TABLE Payment (

Payment_ID INT PRIMARY KEY AUTO_INCREMENT,

Transaction_ID INT,

Payment_Date DATE,

Payment_Amount DECIMAL(15, 2),

Payment_Method ENUM('Credit Card', 'Bank Transfer', 'Cash'),

Payment_Status ENUM('Completed', 'Pending'),

Payment_Confirmation_Number VARCHAR(50),

Bank_Name VARCHAR(100),

Account_Number VARCHAR(100),

Notes TEXT,

AIIE-CSE(B2) 4|Page
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]
FOREIGN KEY (Transaction_ID) REFERENCES Transactions(Transaction_ID) );

1. Property:
Copy remsa.Property (Property_ID, Address, City, State, Zip_Code, Property_Type, Size, Price, Stats,
Date_Listed) FROM ‘C:\Users\MS\OneDrive\Desktop\DBMS lab\Lab Project\rems\Property.csv’
DELIMITER ’,’ CSV HEADER ;
select * from Property;

2. Owners:
Copy remsa.Owners (Owner_ID, First_Name, Last_Name, Contact_Number, Email, Address, City, State,
Zip_Code, Ownership_Type, Date_Of_Ownership) FROM ‘C:\Users\MS\OneDrive\Desktop\DBMS lab\Lab
Project\rems\Owners.csv’ DELIMITER ’,’ CSV HEADER ; select
* from Owners;

3. Clients:
Copy remsa.Clients (Client_ID, First_Name, Last_Name, Contact_Number, Email, Address, City, State,
Zip_Code, Client_Type) FROM ‘C:\Users\MS\OneDrive\Desktop\DBMS lab\Lab Project\rems\Clients.csv’
DELIMITER ’,’ CSV HEADER ; select
* from Clients;

4. Agent:
Copy remsa.Agent (Agent_ID, First_Name, Last_Name, Contact_Number, Email, License_Number,
Agency_Name, Commission_Rate, Years_Of_Experience, Specialization) FROM

AIIE-CSE(B2) 5|Page
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]
‘C:\Users\MS\OneDrive\Desktop\DBMS lab\Lab Project\rems\Agent.csv’ DELIMITER ’,’ CSV HEADER ;
select * from Agent;

5. Transactions:
Copy remsa.Transactions (Transaction_ID, Property_ID, Client_ID, Agent_ID, Transaction_Type,
Transaction_Date, Transaction_Amount, Payment_Method, Stats, Commission_Amount) FROM ‘C:\Users\
MS\OneDrive\Desktop\DBMS lab\Lab Project\rems\Transactions.csv’ DELIMITER ’,’ CSV HEADER ;
select * from Transactions;

6. Lease:
Copy remsa.Lease (Lease_ID, Property_ID, Client_ID, Agent_ID, Lease_Start_Date, Lease_End_Date,
Monthly_Rent, Security_Deposit, Payment_Terms, Stats) FROM ‘C:\Users\MS\OneDrive\Desktop\
DBMS lab\Lab Project\rems\Lease.csv’ DELIMITER ’,’ CSV HEADER ;
select * from Lease;

7. Maintenance_Request:
Copy remsa.Maintenance_Request (Request_ID, Property_ID, Client_ID, Request_Date, Request_Description,
Stats, Assigned_Technician, Completion_Date, Cost, Notes) FROM ‘C:\Users\MS\OneDrive\Desktop\DBMS lab\
Lab Project\rems\ Maintenance_Request.csv’ DELIMITER ’,’ CSV HEADER ;
select * from Maintenance_Request;

AIIE-CSE(B2) 6|Page
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]

8. Technician:
Copy remsa.Technician (Technician_ID, First_Name, Last_Name, Contact_Number, Email, Specialization,
Experience_Years, Certification, Availability_Status, Hourly_Rate) FROM ‘C:\Users\MS\OneDrive\Desktop\
DBMS lab\Lab Project\rems\Technician.csv’ DELIMITER ’,’ CSV HEADER
;
select * from Technician;

9. Agency:
Copy remsa.Agency (Agency_ID, Agency_Name, Address, City, State, Zip_Code, Contact_Number, Email,
License_Number, Number_Of_Agents, Specialization) FROM ‘C:\Users\MS\OneDrive\Desktop\DBMS lab\Lab
Project\rems\ Agency.csv’ DELIMITER ’,’ CSV HEADER ;
select * from Agency;

10. Payment:
Copy remsa.Payment () FROM ‘C:\Users\MS\OneDrive\Desktop\DBMS lab\Lab Project\rems\
Agency.csv’ DELIMITER ’,’ CSV HEADER ;
select * from Agency;

AIIE-CSE(B2) 7|Page
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]

Queries: -

1. Find the Total number of registered properties.


SELECT COUNT(*) AS Total_Registered_Properties
FROM Property;

2. Update the City name to "Gandhinagar" for all records where the owner city is misspelled, and find
the number of properties registered in "Gandhinagar".
UPDATE Owners
SET City = 'Gandhinagar'
WHERE LOWER(City) LIKE 'gandhinag%';

SELECT COUNT(*) AS Properties_In_Gandhinagar


FROM Property
WHERE City = 'Gandhinagar';

3. List the number of properties registered in each


state. SELECT State, COUNT(*) AS
Number_Of_Properties FROM Property
GROUP BY State;

AIIE-CSE(B2) 8|Page
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]
4. Find the property types with the largest size.
SELECT Property_Type, MAX(Size) AS
Largest_Size FROM Property
GROUP BY Property_Type
ORDER BY Largest_Size
DESC;

5. Find the residential property with the highest price listed.


SELECT Property_Type, Address, City, State, Price
FROM Property
WHERE Property_Type = 'Residential'
ORDER BY Price DESC
LIMIT 1;

6. Find the property IDs registered to a client with the name "Bee".
SELECT DISTINCT p.Property_ID, p.Address
FROM Property p
JOIN Transactions t ON p.Property_ID = t.Property_ID
JOIN Clients c ON t.Client_ID = c.Client_ID
WHERE c.First_Name = 'Bee' OR c.Last_Name = 'Bee';

7. Find the client's name who has registered the most properties.
SELECT c.First_Name, c.Last_Name, COUNT(t.Property_ID) AS Total_Properties
FROM Transactions t
JOIN Clients c ON t.Client_ID = c.Client_ID
GROUP BY c.Client_ID
ORDER BY Total_Properties
DESC LIMIT 1;

8. Find the most registered property type.


SELECT Property_Type, COUNT(*) AS Total_Registered
FROM Property
GROUP BY Property_Type
ORDER BY Total_Registered DESC
LIMIT 1;

AIIE-CSE(B2) 9|Page
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]

9. Find all different types of agent specializations, their details, and their frequency.
SELECT Specialization, COUNT(*) AS Frequency
FROM Agent
GROUP BY Specialization;

10. Find the average commission rate of all agents.


SELECT AVG(Commission_Rate) AS
Average_Commission_Rate FROM Agent;

AIIE-CSE(B2) 10 | P a g e
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]

Practical :- 7
AIM: To execute complex SQL queries using JOIN operations and subqueries.
Subquery: A subquery is a query nested inside another query. It is used to retrieve data that will be used
in the main query. Subqueries can be used in the SELECT, INSERT, UPDATE, and DELETE statements.

Syntax: SELECT column_name FROM table_name WHERE column_name = (SELECT column_name FROM
table_name WHERE condition);

1. ORDER BY
 Definition: ORDER BY is used to sort the result set of a query in ascending or
descending order based on one or more columns.
 Syntax:
SELECT column1, column2, ... FROM
table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC];
 Example: To list all Owners in order of their Date of Ownership, from earliest to latest.

2. GROUP BY
 Definition: GROUP BY is used to group rows that have the same values in specified columns, often used
with aggregate functions like COUNT, SUM, AVG, etc.
 Syntax:-
SELECT column1,
aggregate_function(column2) FROM
table_name
GROUP BY column1;
 Example: To count the number of property type in property.

AIIE-CSE(B2) 11 | P a g e
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]

3. JOIN & ORDER

Explanation:-

 The query joins the Client, Lease, and Property tables and orders the results by Property_ID
and Monthly_Rent.

4. Use a subquery to find maximum monthly rent.


Use of a subquery: Subqueries can be used to get a value that is used by the outer query. In the case of
finding a maximum record, the subquery first retrieves the maximum value, and the outer query uses
this value to fetch the required record.
Step 1: Find the Maximum Monthly Rent in the Lease Table

SELECT MAX(Monthly_Rent)

AIIE-CSE(B2) 12 | P a g e
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]
FROM Lease;

Step 2: Use the Subquery to Get the Lease Details with the Maximum Monthly Rent

SELECT Lease_ID, Monthly_Rent

FROM Lease

WHERE Monthly_Rent = (SELECT MAX(Monthly_Rent) FROM Lease);

Step 3: Join with the Client and Property Tables to Get Full Details of the Client with the Highest Rent

SELECT c.First_Name, c.Email, p.Address, l.Monthly_Rent


FROM Client c
JOIN Lease l ON c.Client_ID = l.Client_ID
JOIN Property p ON l.Property_ID = p.Property_ID
WHERE l.Monthly_Rent = (SELECT MAX(Monthly_Rent) FROM Lease);

Output: -

Explanation:

 Step 1: The first query finds the maximum Monthly_Rent in the Lease table.
 Step 2: The second query retrieves the Lease_ID and Monthly_Rent where the Monthly_Rent
matches the maximum found in Step 1.
 Step 3: The third query joins the Client and Property tables with the Lease table on Client_ID and
Property_ID to retrieve the client and property details, including the client name, email, property
name, and monthly rent, for the client with the highest rent.

5. Use of a limit & Order by & Subquery as Tables to find maximum monthly rent.
Step 1: Write a Subquery to find the Maximum Monthly Rent in the Lease
Table

SELECT Property_ID,

Monthly_Rent FROM Lease

ORDER BY Monthly_Rent DESC

LIMIT 1;

Step 2: Join the Subquery with the Client and Property Table

AIIE-CSE(B2)
SELECT c.First_Name, c.Email, p.Address, T1.Monthly_Rent 13 | P a g e
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]
FROM Client c

JOIN (

SELECT Property_ID, Monthly_Rent

FROM Lease

ORDER BY Monthly_Rent DESC

LIMIT 1

) AS T1 ON c.Client_ID = T1.Client_ID

JOIN Property p ON T1.Property_ID = p.Property_ID;

Output:-

Explanation:

 Step 1: The subquery now includes Client_ID along with Property_ID and Monthly_Rent, so it can be
joined with the Client table.
 Step 2: The main query joins the Client table using Client_ID and the subquery result, and also joins
the Property table using Property_ID to retrieve the details of the property and the client renting it.

1) Run the given complex queries.

Q-11. Find the property with the biggest size.

AIIE-CSE(B2) 14 | P a g e
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]

Q-12. Get only the transaction amount for all transaction in descending order.

Q-13. Use Q12 SQL and find the Property_ID, Address, and Size of the top 5 property with the biggest
size.

Q-14. Use Q13 SQL as a subquery to find the Address and Monthly Rent of Property top 5 property based
on rent.

AIIE-CSE(B2) 15 | P a g e
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]

Q-15. Find all details of properties (Property_ID, Address, etc.) that have payments made by clients
involved in transactions with a specific transaction status. HINT: Use "IN"

Q-16. List the status of property with the maximum price.

Q-17. Display the Agent name, commission rate, and the count of commission rate commissioned by an
agent.

AIIE-CSE(B2) 16 | P a g e
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]

Q-18. Use Q7 SQL to find the Student_Name and Email of students with the highest and lowest subject
counts.

AIIE-CSE(B2) 17 | P a g e
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]

Practical :- 8
AIM: - To understand and implement functions, stored procedures, and triggers in
PostgreSQL.
1. Functions: - A function in PostgreSQL is a reusable block of SQL or procedural code that
performs a specific task. Functions can take input parameters, process data, and return
a value or a table. They help modularize and automate repetitive tasks, improving code
readability and maintainability.
 Key Features of Functions:
i. Reusability: Functions can be called multiple times in different queries.
ii. Parameterization: Functions can accept input parameters to make
them flexible for varying data.
iii. Return Values: Functions can return:
a. A scalar value (e.g., integer, text).
b. A table.
c. A JSON or other complex type.
iv.Stored Logic: Encapsulates logic within the database,
improving performance by reducing data movement.
v. Trigger Compatibility: Functions can be used in triggers to automate
actions.
 Syntax for Creating a Function:
CREATE OR REPLACE FUNCTION function_name(parameter_name data_type [, ...])
RETURNS return_data_type
LANGUAGE plpgsql
AS $$
BEGIN
RETURN expression;
END;
$$;

2. Triggers: -A trigger in PostgreSQL is a database mechanism that automatically performs a specified


action (such as inserting, updating, or deleting records) when a predefined event occurs on a
table. Triggers are often used to enforce constraints, maintain audit logs, or implement complex
business rules directly within the database.
 Key Features of Triggers:
i. Automatic Execution: Triggers are fired automatically when the associated event
(INSERT, UPDATE, DELETE) occurs.
ii. Trigger Functions: Triggers rely on special functions called trigger functions to define
the action.
iii. Event-based: Triggers can be fired BEFORE or AFTER an event.
iv. Row-level or Statement-level:
AIIE-CSE(B2) 18 | P a g e
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]
a. Row-level: Executes for every affected row.
b. Statement-level: Executes once per statement, regardless of the number of
affected rows.
 Syntax for Creating a Trigger Function:
CREATE OR REPLACE FUNCTION function_name()
RETURNS TRIGGER
LANGUAGE plpgsql AS $
$
BEGIN
RETURN NEW; -- or RETURN NULL for certain triggers
END;
$$;

 Syntax for Creating a Trigger:


CREATE TRIGGER trigger_name
AFTER | BEFORE event_name ON table_name FOR
EACH ROW | STATEMENT
EXECUTE FUNCTION function_name();

3. Stored Procedures: - A stored procedure is a set of SQL and procedural commands that are
stored and executed on the database server. Unlike functions, stored procedures are
invoked with the CALL statement, and they can perform operations that affect the database
(e.g., transactions, inserts, updates). They allow for complex logic and encapsulation of
database operations.
 Key Features of Stored Procedures:
i. Transactional Control: Stored procedures can include transaction management
commands like COMMIT, ROLLBACK, and SAVEPOINT.
ii. Multiple Operations: They can execute multiple SQL statements in a single call

iii. Parameters: They accept input and output parameters to interact with
data dynamically.
iv. Reusable: Once created, they can be reused across the application.
v. Improved Performance: Reduces network traffic by executing logic directly on the
database server.
 Syntax for Creating a Stored Procedure: -
CREATE OR REPLACE PROCEDURE procedure_name(parameter_name data_type [, ...]) LANGUAGE
plpgsql
AS $$
BEGIN
END;
$$;

AIIE-CSE(B2) 19 | P a g e
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]
EXERCISE:-
Q-1)Create before-trigger functions to avoid the common error message.
Q-1.1)Create a trigger on the Property table to check if the primary key Property_ID already
exists before inserting a new record. If it does, the trigger will send a custom reply instead of a
standard error.

Solution:-
Trigger Function:-

Create Trigger:-

To verify the trigger to check if the primary key Property_ID already exists in the Student table,
follow these steps:

(i) Test the Trigger with an Existing Property_ID:

Attempt to insert a record with an existing Property_ID to see if the custom error
message is raised.

AIIE-CSE(B2) 20 | P a g e
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]

(ii) Test the Trigger with a New Property_ID:


Insert a record with a new, non- existing Property_ID to verify that the trigger allows the
insertion.

Q-1.2)Create a trigger on a table (e.g., property) to check if the foreign key (program_id) exists
before inserting a new record. Send a custom reply instead of an error message.

Solution: -

Trigger Function:-

Create Trigger: -

AIIE-CSE(B2) 21 | P a g e
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]
To verify the trigger to check if the foreign key (Mission_ID) exists before inserting a new
record, follow these steps:
(i) Insert with Existing Mission_ID: -

(ii) Insert with Non-Existing Mission_ID: -

Q-2) Create functions for a specific section.


Q-2.1) Find the maximum attendance rate for students in a semester.
This query will calculate the attendance rate for each student (i.e., the percentage of classes they
attended) and return the student with the highest attendance for a given semester.
Solution:-
Create Function: -

AIIE-CSE(B2) 22 | P a g e
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]
Call the Function: -

Q-2.2) Add a new column, Reg_Student_Count, to the class table. write a function to count the
total students for each class.
Solution:-

Add Column: -

Create the trigger Function: -

Call the Function: -

AIIE-CSE(B2) 23 | P a g e
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]
Verify the output:

Q-3)Create Trigger functions for a specific section.


Q-3.1) To create a trigger for the Property table that counts records and calculates the
average price per square foot for each program_id.

Add new columns to the Attendance table

Create the trigger function:

AIIE-CSE(B2) 24 | P a g e
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]
Create the trigger to execute the function:

Output: -

Q-3.2)Create a trigger function that updates the Max_Students count in the Class table
whenever an INSERT, UPDATE, or DELETE operation occurs in the Attendance table, to reflect
the number of students enrolled in each class.
Add a new column:

AIIE-CSE(B2) 25 | P a g e
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]
Create the trigger function:

execute the function:

AIIE-CSE(B2) 26 | P a g e
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]

AIIE-CSE(B2) 27 | P a g e
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]

Practical :- 9
AIM:- Create stored procedure in Postgres.

1. Retrieve Subscription Plan by Client's Name.


CREATE OR REPLACE PROCEDURE
get_transactions_by_client_name( IN client_first_name VARCHAR,
IN client_last_name VARCHAR,
OUT result_set REFCURSOR
)
AS $$
BEGIN
OPEN result_set FOR
SELECT t.Transaction_ID, t.Transaction_Date, t.Transaction_Type, t.Transaction_Amount,
p.Address, p.City, p.State, p.Property_Type
FROM Transactions t
JOIN Property p ON t.Property_ID = p.Property_ID
JOIN Clients c ON t.Client_ID = c.Client_ID
WHERE c.First_Name = client_first_name
AND c.Last_Name = client_last_name;
END;
$$ LANGUAGE plpgsql;

-- Calling the procedure:


DO $$
DECLARE
transaction_cursor REFCURSOR;
record RECORD;
BEGIN
CALL get_transactions_by_client_name('John', 'Doe', transaction_cursor);
LOOP
FETCH transaction_cursor INTO record;
EXIT WHEN NOT FOUND;
RAISE NOTICE 'Transaction ID: %, Date: %, Type: %, Amount: %, Property: %, %, %, %',
record.Transaction_ID, record.Transaction_Date, record.Transaction_Type, record.Transaction_Amount,
record.Address, record.City, record.State, record.Property_Type;
END LOOP;
CLOSE transaction_cursor;
END;
$$;

2. Count Properties by Type.


CREATE OR REPLACE PROCEDURE count_properties_by_type(OUT result_set REFCURSOR)
AS $$
BEGIN
OPEN result_set FOR

AIIE-CSE(B2) 28 | P a g e
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]
SELECT Property_Type, COUNT(*) AS Property_Count
FROM Property
GROUP BY
Property_Type; END;
$$ LANGUAGE plpgsql;

-- Calling the procedure:


DO $$
DECLARE
property_type_cursor REFCURSOR;
record RECORD;
BEGIN
CALL count_properties_by_type(property_type_cursor);
LOOP
FETCH property_type_cursor INTO record;
EXIT WHEN NOT FOUND;
RAISE NOTICE 'Property Type: %, Count: %',
record.Property_Type, record.Property_Count;
END LOOP;
CLOSE property_type_cursor;
END;
$$;

3. Retrieve Rental Details for Clients.


CREATE OR REPLACE PROCEDURE
get_rental_details_for_client( IN client_first_name
VARCHAR,
IN client_last_name VARCHAR,
OUT result_set REFCURSOR
)
AS $$
BEGIN
OPEN result_set FOR
SELECT c.First_Name, c.Last_Name, p.Address, p.City, p.State, p.Property_Type,
t.Transaction_Date, t.Transaction_Type, t.Transaction_Amount, t.Stats
FROM Transactions t
JOIN Property p ON t.Property_ID = p.Property_ID
JOIN Clients c ON t.Client_ID = c.Client_ID
WHERE c.First_Name = client_first_name
AND c.Last_Name = client_last_name;
END;
$$ LANGUAGE plpgsql;

-- Calling the procedure:


DO $$
DECLARE
AIIE-CSE(B2) 29 | P a g e
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]
rental_details_cursor REFCURSOR;
record RECORD;
BEGIN
CALL get_rental_details_for_client('John', 'Doe',
rental_details_cursor); LOOP
FETCH rental_details_cursor INTO
record; EXIT WHEN NOT FOUND;
RAISE NOTICE 'Client: %, % | Property: %, %, %, % | Transaction Date: %, Type: %, Amount: %, Status:
%', record.First_Name, record.Last_Name, record.Address, record.City, record.State,
record.Property_Type, record.Transaction_Date, record.Transaction_Type,
record.Transaction_Amount, record.Stats;
END LOOP;
CLOSE rental_details_cursor;
END;
$$;

AIIE-CSE(B2) 30 | P a g e
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]

Practical :- 10
AIM:- Normalization of database till 5NF all functional dependencies mentioned.
To normalize the provided Real Estate Management System (REMS) database
schema to 5NF (Fifth Normal Form), we need to analyze the dependencies between
attributes in each table and eliminate redundancies caused by non-atomic
dependencies. Below is a breakdown of normalization up to 5NF for your schema.
1. Normalization Steps:
- 1NF (First Normal
Form) A table is in 1NF
if:

1. Each cell contains a single value (atomic).


2. Each record is unique.
The provided schema is already in 1NF because:

 All attributes store atomic values.


 Each table has a unique identifier (primary key).

2NF (Second Normal Form)

A table is in 2NF if:


1. It is in 1NF.
2. All non-key attributes are fully functionally dependent on the entire primary key (no partial dependencies).

Analysis:
Each table’s non-key attributes depend entirely on their primary keys. For example:

o In the Property table, attributes like Address, City, and State depend on Property_ID.
o In the Transaction table, attributes depend on
Transaction_ID. The schema satisfies 2NF.

3NF (Third Normal Form)


A table is in 3NF if:

1. It is in 2NF.
2. It has no transitive dependency (a non-key attribute depends on another non-key attribute).

Analysis:
 In the Owner table:
o Address, City, State, and Zip_Code could be factored out into a separate Location table
because they are repeating fields for addresses.
o Solution: Create a new Location table and reference it using Location_ID.

2. Create Location Table: -


This creates a new table named Location with the following fields:
AIIE-CSE(B2) 31 | P a g e
DBMS REAL ESTATE MANAGEMENT SYSTEM KANISHK CHAUDHARI
[230169]
 Location_ID as the primary key (auto-incremented).
 Address, City, State, and Zip_Code as non-null attributes for storing location details.

3. Alter Owners Table


 Adds a new column Location_ID to serve as the foreign key reference.
Drops the redundant columns (Address, City, State, Zip_Code) that are now in the Location table.

4. Add Foreign Key Constraint


This ensures referential integrity between the Owners table and the Location table, so that Location_ID in
Owners must correspond to an existing Location_ID in the Location table.

Modified Owner Table:

AIIE-CSE(B2) 32 | P a g e

You might also like