IS5413 Lab 3 Advanced SQL
IS5413 Lab 3 Advanced SQL
Objectives:
Prerequisites:
SQL Knowledge:
Environment:
1
2
Start SQL Server Management Studio
3
Lab3Prerequisite.sql
-- Prerequisite for Lab 3 Environment
4
insert into Course values ('IS6400', 'Business Data Analytics', 3);
insert into Course values ('GE0001', 'Internet', 2);
5
Select Statement with Subqueries
In SQL, a subquery is a query within another query.
A subquery can reside in the WHERE clause, the FROM clause, or the SELECT clause of another query.
Exercise 1: Subquery
Non-correlated Subquery
Write a query to find out the name, student ID of the student enrolled the course ‘IS5413’ or
‘CB2500’.
6
The result should look like the following:
Hint: You need to use data from tables: Student and Enrollment
Alternatively:
7
Write a query to find out the name, student ID of the student enrolled the course ‘IS5413’ or
‘CB2500’ with Course ID.
Hint: You need to use data from tables: Student and Enrollment
Alternatively:
8
WHERE E.CID = 'IS5413' OR E.CID = 'CB2500'
Correlated Subquery
Write a query to find out the total number of courses enrolled for each student.
Hint: You need to use data from table: Student and Enrollment
SELECT S.Name,
(SELECT COUNT(*)
FROM Enrollment AS E
WHERE S.SID = E.SID) AS CNUM
FROM Student AS S
Alternatively:
9
GROUP BY S.Name
10
Exercise
Non-correlated Subquery (Do not depend on data from the outer query, execute once only)
A: Write a query to find out the student ID and name of all the students who have enrolled in a CB or GE course.
B: Write a query to find out the enrollment records of course named “Data Management”. Display the Student ID,
Student Name, Course ID, and the enrollment date of the records.
Correlated Subquery (Make use of data from the outer query, execute row by row)
C: Write a query to find out the total number of courses enrolled by each student:
Reference:
Modern Database Management, 10th Edition, Chapter 6, 7
http://msdn2.microsoft.com/en-us/library/ms189826.aspx
https://www.w3schools.com/sql/default.asp
End of Tutorial
11