0% found this document useful (0 votes)
1 views13 pages

SQL Queries

The document contains a lab assignment with SQL queries and database schema definitions. It covers various topics including querying instructors, defining user-defined data types, using joins, and creating constraints and views. Additionally, it includes advanced SQL concepts like recursive queries for prerequisites and ranking students based on GPA.

Uploaded by

b22cs048
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views13 pages

SQL Queries

The document contains a lab assignment with SQL queries and database schema definitions. It covers various topics including querying instructors, defining user-defined data types, using joins, and creating constraints and views. Additionally, it includes advanced SQL concepts like recursive queries for prerequisites and ranking students based on GPA.

Uploaded by

b22cs048
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Lab Assignment - 4

Name Shahil Sharma


Roll Num B22CS048

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%";

B) Define a user-defined data type for a phone number and a domain


for email addresses in the database schema.

In PostgreSQL, we can use the CREATE DOMAIN statement to define a custom


data type for a phone number. The domain can enforce specific constraints, such
as length or format (e.g., 10-digit numbers).

CREATE DOMAIN phone_number AS VARCHAR(15)


CHECK (VALUE ~ ‘^\+?[0-9]{10,15} ');

Domain for Email Addresses:


Similarly, we can define a domain for email addresses that ensures the input
follows a valid email format.

CREATE DOMAIN email_address AS VARCHAR(255)


CHECK (VALUE ~* ‘^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,} ’);

Here’s an example of how you might use them in a student table:


CREATE TABLE student (
ID SERIAL PRIMARY KEY,
name VARCHAR(100),
phone phone_number,
$
$
email email_address
);

C) Write a SQL query to find the average salary of instructors


grouped by department and display departments where the average
salary is greater than $60,000.

select instructor.dept_name, avg(instructor.salary) as average_salary


from instructor
group by instructor.dept_name
having average_salary > 60000;

d) Modify the previous query to order the results by average salary


in descending order.

select instructor.dept_name, avg(instructor.salary) as average_salary


from instructor
group by instructor.dept_name
having average_salary > 60000
order by average_salary desc;
e) Write a SQL query to find departments with more than 3
instructors, using the HAVING clause.

select instructor.dept_name, avg(instructor.salary) as average_salary


from instructor
group by instructor.dept_name
having average_salary > 60000
order by average_salary desc;

f) Write SQL queries demonstrating the use of natural join, right


outer join, and left outer join between the instructor and
department tables.

-- 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

SELECT DISTINCT cs.course_id, cs.title, cs.dept_name


FROM course cs
JOIN course math ON cs.title = math.title
WHERE cs.dept_name = 'CSE'
AND math.dept_name = 'Mathematics';

I) Write a SQL query to demonstrate the use of EXCEPT to find all


courses not taught in the Spring semester.

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.

Using NOT IN to Simulate EXCEPT:

SELECT course.course_id, course.title


FROM course
WHERE course.course_id NOT IN (
SELECT course_id
FROM section
WHERE semester = 'Spring'
);
J) Write SQL queries using SOME and ALL to compare instructor
salaries.

-- 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.

select name, dept_name, salary


from instructor as outer_instructor
where salary > (
select avg(salary)
from instructor as inner_instructor
where inner_instructor.dept_name = outer_instructor.dept_name
);

L) Define a constraint to ensure that the department budget cannot


be less than $10,000.

CREATE TABLE department (


dept_name VARCHAR(50),
building VARCHAR(50),
budget DECIMAL(10, 2),
PRIMARY KEY (dept_name),
CONSTRAINT chk_budget CHECK (budget >= 10000)
);

OR

If the department table already exists, you can add the constraint using an
ALTER TABLE statement:

ALTER TABLE department


ADD CONSTRAINT chk_budget CHECK (budget >= 10000);
M) Write an assertion to ensure that the number of students in a
department does not exceed 500.

In SQL, an assertion is a database-wide constraint that ensures a certain


condition holds across multiple rows or tables. However, MySQL does not
support ASSERTION directly. we can achieve a similar result by using triggers.

DELIMITER

CREATE TRIGGER check_student_limit


BEFORE INSERT ON student
FOR EACH ROW
BEGIN
DECLARE student_count INT;

-- Count the number of students in the department


SELECT COUNT(*) INTO student_count
FROM student
WHERE dept_name = NEW.dept_name;

-- Check if the student count exceeds 500


IF student_count >= 500 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Number of students in this department exceeds
500.';
END IF;
END

DELIMITER ;

N) Create a view that lists all students along with the total
number of credits they have completed.

CREATE VIEW student_total_credits AS


SELECT s.ID, s.name, SUM(c.credit) AS
total_credits
FROM student s
JOIN takes t ON s.ID = t.ID
JOIN course c ON t.course_id = c.course_id
GROUP BY s.ID, s.name;
$
$
$
$
O) Write a SQL query to update the budget of a department and
ensure that changes cascade to related tables.

If we want to ensure that changes to the dept_name (which is a foreign key in


other tables) cascade across related tables, we should define foreign key
constraints with the ON UPDATE CASCADE option when creating or altering the
tables.

For example, when creating the instructor table, you could set up the foreign key
like this:

CREATE TABLE instructor (


ID INT PRIMARY KEY,
name VARCHAR(50),
dept_name VARCHAR(50),
salary DECIMAL(10, 2),
FOREIGN KEY (dept_name) REFERENCES department(dept_name) ON UPDATE
CASCADE
);

UPDATE department
SET dept_name = 'CS'
WHERE dept_name = 'CSE';

P) Rank the students within their respective departments based on


their GPA.Students with the highest GPA should receive the highest
rank (rank = 1).Handle ties appropriately.

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;

Q) For each course in the database, identify the full chain of


prerequisites. A course may have direct prerequisites, which
themselves may have their own prerequisites, and so on. The chain
should represent all courses that a student needs to complete
before enrolling in the given course.

WITH RECURSIVE PrerequisiteChain AS (


-- Base case: Start with direct prerequisites
SELECT
course_id,
prereq_id
FROM prereq
UNION
-- Recursive case: Find prerequisites of prerequisites
SELECT
pc.course_id, p.prereq_id
FROM PrerequisiteChain pc
JOIN prereq p ON pc.prereq_id = p.course_id
)
SELECT * FROM PrerequisiteChain;

R) For each student, determine if they have completed all indirect


prerequisites for the courses they are currently enrolled in. An
indirect prerequisite is any course in the prerequisite chain except
the direct prerequisite.

WITH RECURSIVE PrerequisiteChain AS (


SELECT
p.course_id,
p.prereq_id,
p.prereq_id AS root_prereq
FROM prereq p
UNION
SELECT
pc.course_id,
p.prereq_id,
pc.root_prereq
FROM PrerequisiteChain pc
JOIN prereq p ON pc.prereq_id = p.course_id
)
SELECT
s.ID AS student_id,
t.course_id AS enrolled_course,
pc.prereq_id AS indirect_prereq,
CASE
WHEN sc.course_id IS NULL THEN 'Missing'
ELSE 'Completed'
END AS status
FROM student s
JOIN takes t ON s.ID = t.ID
JOIN PrerequisiteChain pc ON t.course_id = pc.course_id -- Match to all
prerequisites
LEFT JOIN takes sc ON s.ID = sc.ID AND pc.prereq_id = sc.course_id AND
sc.grade IS NOT NULL -- Check if the student completed the
prerequisite
WHERE t.grade IS NULL -- Only courses currently enrolled in
AND pc.prereq_id <> pc.root_prereq; -- Exclude direct prerequisites

You might also like