Relational Algebra and SQL Queries for Doctor-Patient Database with Examples

Relational Algebra and SQL Examples for Doctor-Patient Database

This post demonstrates relational algebra operations along with their equivalent SQL queries using the Doctor and Patient tables.


Given Tables

Doctor

doctor_id doctor_name specialization room_no
D101Dr. KhanDermatologist101
D102Dr. AliCardiologist102
D103Dr. SultanaNeurologist103

Patient

patient_id patient_name age doctor_id
P001Rahim30D101
P002Fatema22D102
P003Karim27D101
P004Salma35D103

1. Patients with age > 25 and doctor_id = D101

Relational Algebra:

σ_{age>25 ∧ doctor_id='D101'}(Patient)[patient_name, age]

SQL:

SELECT patient_name, age
FROM Patient
WHERE age > 25 AND doctor_id = 'D101';

Result:

patient_nameage
Rahim30
Karim27

2. Patients whose doctor is a Dermatologist

Relational Algebra:

π_{patient_name, age} (Patient ⨝ σ_{specialization='Dermatologist'}(Doctor))

SQL:

SELECT p.patient_name, p.age
FROM Patient p
JOIN Doctor d ON p.doctor_id = d.doctor_id
WHERE d.specialization = 'Dermatologist';

Result:

patient_nameage
Rahim30
Karim27

3. All attributes of doctors (renamed)

Relational Algebra:

ρ_{DoctorDetails(d_name/doctor_name, room_number/room_no)}(Doctor)

SQL:

SELECT doctor_id,
       doctor_name AS d_name,
       specialization,
       room_no AS room_number
FROM Doctor;

Result:

doctor_idd_namespecializationroom_number
D101Dr. KhanDermatologist101
D102Dr. AliCardiologist102
D103Dr. SultanaNeurologist103

4. Cartesian product: doctor specialization with each patient age

Relational Algebra:

π_{specialization, age} (Doctor × Patient)

SQL:

SELECT d.specialization, p.age
FROM Doctor d
CROSS JOIN Patient p;

Result:

specializationage
Dermatologist30
Dermatologist22
Dermatologist27
Dermatologist35
Cardiologist30
Cardiologist22
Cardiologist27
Cardiologist35
Neurologist30
Neurologist22
Neurologist27
Neurologist35

কোন মন্তব্য নেই:

একটি মন্তব্য পোস্ট করুন