IT Learning HubIT Learning Hub
REVIEW 06 · COMPREHENSIVE PRACTICE

Database Practice Review

5 periodsDatabaseSQL Server

Objective: Consolidate everything covered in Weeks 1-5, read and analyze a real-world management problem, identify Entity/Attribute/Relationship, convert from ER/EER to a relational model, and combine multiple SQL techniques to solve a complete problem.

01 · OBJECTIVES & BIG PICTURE

Objectives

By the end of Week 6, students should be able to:

  • Consolidate everything covered in the practice sessions so far
  • Read and analyze a real-world management problem
  • Identify the Entities, Attributes, and Relationships involved
  • Convert from an ER/EER model to a relational model
  • Identify the Primary Key, Foreign Key, and Candidate Key
  • Create a database and tables with SQL, and set up integrity constraints
  • Perform SELECT, WHERE, ORDER BY, GROUP BY, HAVING, JOIN, Subquery, aggregate functions, INSERT, UPDATE, DELETE
  • Combine multiple SQL techniques to solve a complete problem
  • Spot and fix common mistakes when writing queries

The Big Picture

Students need to look back over the whole process of building a database:

Real-world problem ↓ Requirements analysis ↓ Identify Entity / Attribute / Relationship ↓ ERD ↓ Relational model ↓ Primary Key / Foreign Key ↓ CREATE DATABASE / CREATE TABLE ↓ INSERT DATA ↓ SELECT / JOIN / GROUP BY ↓ Data analysis
Key point: SQL is not where the problem begins. Before writing any SQL, students need to understand how the data is organized and how the tables relate to each other.

02 · REVIEWING THE DATABASE MODEL

Data Model

Entity

An Entity is an object that needs to be managed within the system. Example - a student management system:

SINHVIEN MONHOC LOPHOC GIANGVIEN

Attribute

Example - the SINHVIEN Entity:

SINHVIEN ├── MaSV ├── HoTen ├── NgaySinh ├── GioiTinh └── MaLop
AttributeMeaning
MaSVStudent identifier
HoTenStudent name
NgaySinhDate of birth
GioiTinhGender
MaLopStudent's class

03 · KEYS IN A DATABASE

Keys in a Database

Primary Key

A Primary Key uniquely identifies a record:

CREATE TABLE SinhVien (
    MaSV VARCHAR(10) PRIMARY KEY,
    HoTen NVARCHAR(100),
    NgaySinh DATE
);

MaSV cannot be duplicated and cannot be NULL.

Foreign Key

A Foreign Key creates a relationship between tables:

CREATE TABLE SinhVien (
    MaSV VARCHAR(10) PRIMARY KEY,
    HoTen NVARCHAR(100),
    MaLop VARCHAR(10),

    FOREIGN KEY (MaLop)
        REFERENCES Lop(MaLop)
);

Relationship - one class has many students:

LOP (1) ↓ SINHVIEN (N)

04 · REVIEWING DATABASE CREATION & INSERT

Creating a Database & INSERT

Example: building a student and academic results management database with 4 tables, LOP, SINHVIEN, MONHOC, KETQUA, related as follows:

LOP 1 ─────── N SINHVIEN SINHVIEN 1 ─────── N KETQUA MONHOC 1 ─────── N KETQUA

Creating the tables

CREATE TABLE Lop (
    MaLop VARCHAR(10) PRIMARY KEY,
    TenLop NVARCHAR(100)
);

CREATE TABLE MonHoc (
    MaMH VARCHAR(10) PRIMARY KEY,
    TenMH NVARCHAR(100),
    SoTinChi INT
);

CREATE TABLE SinhVien (
    MaSV VARCHAR(10) PRIMARY KEY,
    HoTen NVARCHAR(100),
    MaLop VARCHAR(10),

    FOREIGN KEY (MaLop)
        REFERENCES Lop(MaLop)
);

INSERT

INSERT INTO Lop
VALUES
('HTTT01', N'Hệ thống thông tin 01'),
('HTTT02', N'Hệ thống thông tin 02');

INSERT INTO SinhVien
VALUES
('SV001', N'Nguyễn Văn An', 'HTTT01'),
('SV002', N'Trần Văn Bình', 'HTTT01'),
('SV003', N'Lê Văn Cường', 'HTTT02');
If the SinhVien table has a Foreign Key referencing Lop, then HTTT01 and HTTT02 must already exist in the Lop table before students can be added.

05 · REVIEWING SELECT, WHERE & LIKE

SELECT, WHERE & LIKE

SELECT

Retrieve all data:

SELECT *
FROM SinhVien;

Select specific columns and give them an alias:

SELECT
    MaSV AS [Mã sinh viên],
    HoTen AS [Họ tên]
FROM SinhVien;

WHERE

Find students in class HTTT01:

SELECT *
FROM SinhVien
WHERE MaLop = 'HTTT01';

Multiple conditions:

SELECT *
FROM SinhVien
WHERE MaLop = 'HTTT01'
AND HoTen LIKE N'Nguyễn%';

LIKE - % and _

See the full details on both wildcard characters in Week 2 - Special Operators. Quick review:

WildcardMeaning
%Represents any string of characters, including an empty string (0, 1, or more characters)
_Represents exactly one character
-- Starts with "Nguyễn"
WHERE HoTen LIKE N'Nguyễn%'

-- Ends with "An"
WHERE HoTen LIKE N'%An'

-- Contains "Văn"
WHERE HoTen LIKE N'%Văn%'

-- Exactly 4 characters, starting "PB0" + 1 any character
WHERE MaPB LIKE 'PB0_'

06 · ORDER BY & AGGREGATE FUNCTIONS

ORDER BY & Aggregate Functions

ORDER BY

Sort students by name:

SELECT *
FROM SinhVien
ORDER BY HoTen ASC;   -- Change to DESC to sort descending

Aggregate functions

Functions to remember: COUNT(), SUM(), AVG(), MIN(), MAX(). Example - how many students are there:

SELECT COUNT(*) AS SoLuongSinhVien
FROM SinhVien;

07 · GROUP BY & HAVING

GROUP BY & HAVING

GROUP BY

Count the number of students in each class:

SELECT
    MaLop,
    COUNT(*) AS SoLuong
FROM SinhVien
GROUP BY MaLop;
MaLopSoLuong
HTTT012
HTTT021

HAVING

WHERE ➜ Filters individual rows HAVING ➜ Filters groups after GROUP BY

Only keep classes with 2 or more students:

SELECT
    MaLop,
    COUNT(*) AS SoLuong
FROM SinhVien
GROUP BY MaLop
HAVING COUNT(*) >= 2;

08 · REVIEWING JOIN

JOIN

This is the core topic of the review week. To display Student ID, Full Name, and Class Name:

SELECT
    SV.MaSV,
    SV.HoTen,
    L.TenLop
FROM SinhVien SV
JOIN Lop L
    ON SV.MaLop = L.MaLop;

INNER JOIN

Only returns records that have a match in both tables - if a class has no students yet, that class won't appear in the result.

LEFT JOIN

Shows every class, including ones with no students yet - this is a question type students commonly run into during practice:

SELECT
    L.MaLop,
    L.TenLop,
    SV.MaSV,
    SV.HoTen
FROM Lop L
LEFT JOIN SinhVien SV
    ON L.MaLop = SV.MaLop;

JOIN across multiple tables

Example: given LOP ➜ SINHVIEN ➜ KETQUA ➜ MONHOC. Query which student took which course and what score they got:

SELECT
    SV.MaSV,
    SV.HoTen,
    MH.TenMH,
    KQ.Diem
FROM SinhVien SV
JOIN KetQua KQ
    ON SV.MaSV = KQ.MaSV
JOIN MonHoc MH
    ON KQ.MaMH = MH.MaMH;

This is the kind of comprehensive query students need to master before finishing the practical portion of the course.

09 · REVIEWING SUBQUERY

Subquery

Find students whose grade is higher than the average grade:

SELECT *
FROM KetQua
WHERE Diem > (
    SELECT AVG(Diem)
    FROM KetQua
);

The thinking:

Step 1: Calculate the average grade ↓ Step 2: Find students with a grade > the average

10 · REVIEWING UPDATE & DELETE

UPDATE & DELETE

UPDATE

Fix a student's name:

UPDATE SinhVien
SET HoTen = N'Nguyễn Văn Nam'
WHERE MaSV = 'SV001';
Cannot be undone: Don't write UPDATE SinhVien SET HoTen = N'Nguyễn Văn Nam'; without a WHERE, since that statement would update every student.

DELETE

DELETE FROM SinhVien
WHERE MaSV = 'SV001';

Same idea - always double-check the WHERE clause before running DELETE.

11 · PRACTICE REQUIREMENTS

Practice Requirements

This week's formal exercise uses the classic "Suppliers - Parts - Shipments" schema (Goods Management) - the schema, sample data, and all 36 questions are on the exercise page below.

PRACTICE REQUIREMENTS · 36 QUESTIONS

Comprehensive Review - Goods Management

See the full assignment and detailed answers (access code required) for this comprehensive review exercise.

View exercise & answers ›

12 · CHALLENGE PROBLEMS

Challenge Problems

Extra practice with the Training Management schema (LOP, SINHVIEN, MONHOC, KETQUA) used throughout the theory sections above - no longer the formal exercise, but still useful for building reflexes. For stronger students to attempt in addition - each has a hidden hint, click to reveal.

01

Hasn't taken the course

Find students who haven't taken course IS210.

Hint
NOT IN (SELECT MaSV FROM KetQua WHERE MaMH = 'IS210')
02

Passed every course

Find students whose grade is 5 or higher in every course.

Hint
GROUP BY MaSV + HAVING MIN(Diem) >= 5
03★★

Find the student with the highest average grade.

Hint
GROUP BY MaSV + ORDER BY AVG(Diem) DESC + TOP 1
04★★

Rank students by average grade.

Hint
ORDER BY AVG(Diem) DESC (You could also look into the RANK() OVER (...) function for proper ranking)
05★★

Find the course with the most students scoring below 5.

Hint
WHERE Diem < 5 + GROUP BY MaMH + ORDER BY COUNT(*) DESC

13 · COMMON MISTAKES

Common Mistakes

Mistake 1 - Wrong JOIN condition

-- Wrong
JOIN Lop L ON SV.MaSV = L.MaLop

-- Correct
JOIN Lop L ON SV.MaLop = L.MaLop

Mistake 2 - Using WHERE instead of HAVING

-- Wrong logic
WHERE COUNT(*) > 2

-- Correct
GROUP BY MaLop
HAVING COUNT(*) > 2

Mistake 3 - Forgetting GROUP BY

-- Wrong
SELECT MaLop, COUNT(*)
FROM SinhVien;

-- Must include GROUP BY
SELECT MaLop, COUNT(*)
FROM SinhVien
GROUP BY MaLop;

Mistake 4 - UPDATE/DELETE without a WHERE

Always check with SELECT before running UPDATE or DELETE:

SELECT *
FROM SinhVien
WHERE MaSV = 'SV001';

14 · REVIEW CHECKLIST

Review Checklist

Students should self-assess before the practical exam:

Database

  • Understand Entity, Attribute, Relationship
  • Can draw an ERD
  • Can identify Primary Key, Foreign Key

Basic SQL

  • CREATE DATABASE, CREATE TABLE
  • INSERT, SELECT, WHERE, ORDER BY, LIKE

Advanced SQL

  • GROUP BY, HAVING
  • COUNT, SUM, AVG, MIN, MAX
  • INNER JOIN, LEFT JOIN, Subquery

Data manipulation & synthesis

  • Check with WHERE before running UPDATE, DELETE
  • Read the problem, identify tables, relationships, and keys before writing SQL
  • Can explain their own SQL statements