02 Advancedsql
02 Advancedsql
Also includes:
→ View definition
→ Integrity & Referential Constraints
→ Transactions
Aggregations + Group By
String / Date / Time Operations
Output Control + Redirection
Nested Queries
Common Table Expressions
Window Functions
student(sid,name,login,gpa) enrolled(sid,cid,grade)
sid name login age gpa sid cid grade
53666 Kanye kanye@cs 44 4.0 53666 15-445 C
53688 Bieber jbieber@cs 27 3.9 53688 15-721 A
53655 Tupac shakur@cs 25 3.5 53688 15-826 B
53655 15-445 B
course(cid,name) 53666 15-721 C
cid name
15-445 Database Systems
15-721 Advanced Database Systems
15-826 Data Mining
15-823 Advanced Topics in Databases
Get the names and GPAs of all students who are older
than 25 years old.
Get the names and GPAs of all students who are older
than 25 years old.
Get the names and GPAs of all students who are older
than 25 years old.
SELECT s.name
FROM enrolled AS e, student AS s
WHERE e.grade = ‘A’ AND e.cid = ‘15-721’
AND e.sid = s.sid
AVG(gpa) COUNT(sid)
SELECT AVG(gpa), COUNT(sid) 3.8 3
FROM student WHERE login LIKE '%@cs'
X
SELECT AVG(s.gpa), e.cid, s.name
FROM enrolled AS e, student AS s
WHERE e.sid = s.sid
GROUP BY e.cid
X
SELECT AVG(s.gpa), e.cid, s.name
FROM enrolled AS e, student AS s
WHERE e.sid = s.sid
GROUP BY e.cid,
e.cid s.name
AVG(s.gpa) e.cid
3.75 15-415 avg_gpa e.cid
3.950000 15-721 3.950000 15-721
3.900000 15-826
15-445/645 (Fall 2021)
21
cid name
15-823 Advanced Topics in Databases
cid name
15-823 Advanced Topics in Databases
Aggregation functions:
→ Anything that we discussed earlier
Special window functions:
→ ROW_NUMBER()→ # of the current row
→ RANK()→ Order position of the current
row.
SELECT *,
ROW_NUMBER() OVER (ORDER BY cid)
FROM enrolled
ORDER BY cid
Find the student with the second highest grade for each
course.
SELECT * FROM (
SELECT *, RANK() OVER (PARTITION BY cid
ORDER BY grade ASC) AS rank
FROM enrolled) AS ranking
WHERE ranking.rank = 2
Find the student with the second highest grade for each
course.
SELECT * FROM (
SELECT *, RANK() OVER (PARTITION BY cid
ORDER BY grade ASC) AS rank
FROM enrolled) AS ranking
WHERE ranking.rank = 2
Find the student with the second highest grade for each
course.
SELECT * FROM (
SELECT *, RANK() OVER (PARTITION BY cid
ORDER BY grade ASC) AS rank
FROM enrolled) AS ranking
WHERE ranking.rank = 2
WITH cteName AS (
SELECT 1
)
SELECT * FROM cteName
WITH cteName AS (
SELECT 1
)
SELECT * FROM cteName
Demo: CTEs!
Demo: CTEs!
https://15445.courses.cs.cmu.edu/fall2021/homework1
Storage Management