1. Write an SQL statement that adds an advisorid attribute to relation student,
ID: 3593301 • Letter: 1
Question
1. Write an SQL statement that adds an advisorid attribute to relation student, and sets it to be a foreign key to facultyid in relation faculty. In case a faculty’s id is changed, the change would be reected on advisorid attribute; in case a student’s advisor left the school, advisorid would be set to NULL.
2. Write an SQL statement that adds a constraint to the student relation to make sure that the gpa attribute cannot be NULL, and that the value of this attribute has to be between 0 and 4. Furthermore, the default value for this attribute should be 3.
Explanation / Answer
Question 1:
ALTER TABLE student
ADD advisorid int
CONSTRAINT student_faculty_id
FOREIGN KEY (advisorid) REFERENCES faculty (facultyid)
ON DELETE SET NULL
ON UPDATE CASCADE;
Here We are adding advisorid column to student table and making it a foreign key to facultyid in faculty table using line# 4 and creating a constraint for it in line# 3. And setting up it as on update to Cascade(when facultyid in faculty chages then advisorid will get change) in Line# 6, on delete to null in Line# 5(When faculty record deleted from faaculty table then advisorid will set to null)
Question 2:
ALTER TABLE student
ALTER COLUMN gpa numeric(10,1) NOT NULL;
ALTER TABLE student
ADD CONSTRAINT DF_gpa DEFAULT 3.0 FOR gpa,
CONSTRAINT check_gpa CHECK (gpa >= 0.0 AND gpa <= 4.0);
Here first setting the gpa to not null using alter column and then adding two different constraints to set the default value and to check the gpa value.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.