Skip to content

Commit 7aecb45

Browse files
authored
Difference Between CTE and Subquery (#209)
1 parent ab0bc64 commit 7aecb45

File tree

6 files changed

+82
-0
lines changed

6 files changed

+82
-0
lines changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
SELECT name
2+
FROM student s
3+
WHERE (
4+
SELECT COUNT(*)
5+
FROM registration r
6+
WHERE r.student_id = s.id
7+
) = (
8+
SELECT MAX(course_count)
9+
FROM (
10+
SELECT COUNT(*) AS course_count
11+
FROM registration
12+
GROUP BY student_id
13+
) AS subquery
14+
);
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
-- View the tables
2+
SELECT * FROM student LIMIT 3;
3+
4+
SELECT * FROM registration LIMIT 3;
5+
6+
7+
-- Let's create the CTE here, named course_count
8+
WITH Course_count AS (
9+
SELECT student_id, COUNT(course_id) AS total_courses
10+
FROM Registration GROUP BY student_id
11+
)
12+
13+
-- select a column from student and CTE (Course_count) table, and filter information
14+
SELECT s.name AS student_name, cc.total_courses As courses_registered
15+
FROM Student s
16+
JOIN Course_count cc ON s.id = cc.student_id
17+
WHERE cc.total_courses > 12;
18+
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
SELECT name
2+
FROM student
3+
WHERE id IN (
4+
SELECT student_id
5+
FROM registration
6+
WHERE course_id IN (
7+
SELECT course_id
8+
FROM teaching
9+
WHERE faculty_id = (
10+
SELECT id
11+
FROM faculty
12+
WHERE name = 'Rory Ross'
13+
)
14+
)
15+
);
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
WITH RECURSIVE prerequisite_chain AS (
2+
-- Anchor member: Start with the target course
3+
SELECT c.id, c.name, p.prerequisite_id
4+
FROM course c
5+
JOIN prerequisite p ON c.id = p.course_id
6+
WHERE c.name = 'Advanced Algorithms'
7+
8+
UNION ALL
9+
10+
-- Recursive member: Find all prerequisites for the courses in the current level
11+
SELECT c.id, c.name, p.prerequisite_id
12+
FROM course c
13+
JOIN prerequisite_chain pc ON c.id = pc.prerequisite_id
14+
JOIN prerequisite p ON c.id = p.course_id
15+
)
16+
17+
SELECT DISTINCT name
18+
FROM prerequisite_chain;
19+
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
SELECT name, gpa,
2+
(SELECT AVG(gpa) FROM student) AS avg_gpa
3+
FROM student
4+
WHERE gpa > (SELECT AVG(gpa) FROM student);
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
SELECT name
2+
FROM student
3+
WHERE id IN (
4+
SELECT student_id
5+
FROM registration
6+
WHERE course_id = (
7+
SELECT id
8+
FROM course
9+
WHERE name = 'Introduction to Structural Engineering'
10+
)
11+
);
12+

0 commit comments

Comments
 (0)