SQL Queries
SQL Queries
A)Write a SQL query to find all instructors whose names start with
the letter 'A'.
select name
from instructor
where name like "A%" or "a%";
-- natural join--
select instructor.name, instructor.salary, department.building,
department.budget
from instructor
natural join department;
-- right join--
select instructor.name, instructor.salary, department.dept_name,
department.building, department.budget
from instructor
right outer join department on instructor.dept_name =department.dept_name;
-- left join--
select instructor.name, instructor.salary, department.dept_name,
department.building, department.budget
from instructor
left outer join department ON instructor.dept_name = department.dept_name;
G) Write SQL queries using IN and EXISTS to find all students who
are also instructors.
Using IN
SELECT student.ID, student.name, student.dept_name
FROM student
WHERE student.ID IN (SELECT instructor.ID FROM instructor);
Using EXISTS
SELECT student.ID, student.name, student.dept_name
FROM student
WHERE EXISTS (
SELECT 1
FROM instructor
WHERE instructor.ID = student.ID
);
H) Write SQL queries using INTERSECT and UNION to find the union
and intersection of two sets of courses.
In MySQL, the INTERSECT operator is not directly supported, but we can achieve
the same result using a combination of JOIN and DISTINCT.
Union
SELECT course_id, title, dept_name
FROM course
WHERE dept_name = 'Computer Science'
UNION
SELECT course_id, title, dept_name
FROM course
WHERE dept_name = ‘Mathematics';
INTERSECT
In MySQL, the EXCEPT operator is not directly supported, but we can achieve
the same result using a combination of LEFT JOIN or a NOT IN subquery.
-- some--
SELECT name, salary
FROM instructor
WHERE salary > SOME (
SELECT salary
FROM instructor
WHERE dept_name = 'Mathematics'
);
-- all--
SELECT name, salary
FROM instructor
WHERE salary > ALL (
SELECT salary
FROM instructor
WHERE dept_name = 'CSE'
);
k) Write a SQL query using a nested subquery to find instructors
who earn more than the average salary of all instructors in their
department.
OR
If the department table already exists, you can add the constraint using an
ALTER TABLE statement:
DELIMITER
DELIMITER ;
N) Create a view that lists all students along with the total
number of credits they have completed.
For example, when creating the instructor table, you could set up the foreign key
like this:
UPDATE department
SET dept_name = 'CS'
WHERE dept_name = 'CSE';
WITH student_gpa AS (
SELECT
s.ID,
s.name,
s.dept_name,
SUM(gp.points * c.credit) / SUM(c.credit) AS GPA
FROM student s
JOIN takes t ON s.ID = t.ID
JOIN course c ON t.course_id = c.course_id
JOIN grade_points gp ON t.grade = gp.grade
GROUP BY s.ID, s.name, s.dept_name
)
SELECT
ID,
name,
dept_name,
GPA,
RANK() OVER (PARTITION BY dept_name ORDER BY GPA DESC) AS `rank`
FROM student_gpa;