Assignment 3
Assignment 3
2. According to the existing schema, one student can have only one advisor.
1. Alter the schema to allow a student to have multiple advisors and make sure
that you are able to insert multiple advisors for a student.
Sol: alter table advisor drop constraint advisor_pkey;
alter table advisor add constraint advisor_pkey primary key (s_id, i_id);
2. Write SQL queries on the modified schema. You will need to insert data to
ensure the query results are not empty.
1. Find all students who have more than 3 advisors
Sol: select s_id, name
from advisor,student
where advisor.s_ID=student.ID
group by s_id, name
having count(i_ID)>3;
2. Find all students who are co-advised by Prof. Srinivas and Prof. Ashok.
Sol: select name
from student
where ID in
(select s_id from advisor,instructor
where advisor.i_id = instructor.ID
and instructor.name='Srinivasan')
and ID in
(select s_id from advisor,instructor
where advisor.i_id = instructor.ID
and instructor.name='Ashok');
2. Delete the course CS 101. All courses which have this as a prereq should
remove this from its prereq set. Create a cascade constraint and verify.
Sol: delete from course where course_id='CS-101'
4. Write the create table SQL commands to create the following tables:
1. phone(phone_id, brand, model, price)
This table represents a mobile phone.
brand is some string like 'Nokia', 'Samsung' etc.
model is a string such as 'N95', 'Galaxy3' etc.
Sol: create table phone
(phone_id varchar(20),
brand varchar(20),
model varchar(20),
price numeric(12,2),
primary key (phone_id)
);
2. The network type should be one of the following values: 'GSM', 'CDMA',
'BOTH'
Sol: alter table network add check (type in ('GSM', 'CDMA', 'BOTH'))
3. Modify the create table script and add a cascade constraint so that, when a phone is
deleted (i.e., no longer being manufactured), all deals for that phone are deleted.
Sol: alter table deal drop constraint "deal_phone_id_fkey"
alter table deal add constraint "deal_phone_id_fkey" foreign
key(phone_id) references phone on delete cascade
4. Try to insert inconsistent data and verify the constraints. Provide insert statements
that fail, along with the error message.
Sol: Check deal start_date <= end_date:
insert into phone values(1, 'Nokia', 'N95', 10000);
insert into network values(1, 'Airtel', 'GSM');