Question 1

Using the university schema, write an SQL query to find the names of those departments whose budget is higher than that of Physics. List them in alphabetical order.

  1. select X.dept_name
  2. from department as X, department as H
  3. where H.dept_name = 'Physics' and X.budget > H.budget
  4. order by X.dept_name

Question 2

Using the university schema, use SQL to do the following:
For each student who has retaken a course at least twice
(i.e., the student has taken the course at least three times),
show the course ID and the student’s ID.

Please display your results in order of course ID and do not display duplicate rows.

  1. select distinct course_id, ID
  2. from takes
  3. group by ID, course_id
  4. having count(*) > 2
  5. order by course_id

Question 3

Using the university schema, write an SQL query to find the IDs of those students who have retaken at least three distinct courses at least once
(i.e, the student has taken the course at least two times).

  1. select distinct ID
  2. from (
  3. -- At lease one time--
  4. select course_id, ID
  5. from takes
  6. group by ID, course_id
  7. having count(*) > 1)
  8. group by ID
  9. -- Have at lease three distinct course, count the number inside ID --
  10. having count(course_id) > 2

Question 4

Using the university schema, write an SQL query to find the ID and name of each instructor who has never given an A grade in any course she or he has taught.
(Instructors who have never taught a course trivially satisfy this condition.)

  1. select ID, name
  2. from instructor
  3. except (
  4. select distinct instructor.ID, instructor.name
  5. from (
  6. (instructor join teaches using (ID))
  7. join takes using (course_id, year, semster, sec_id)
  8. where takes.grade = "A"
  9. )

Question 5

Using the university schema, write an SQL query to find the number of students in each section. The result columns should appear in the order “courseid, secid, year, semester, num”. You do not need to output sections with 0 students.

  1. select course_id, sec_id, year, semester, count(*) as num
  2. from takes
  3. group by course_id,sec_id,year,semester