IT Learning HubIT Learning Hub
PRACTICE 01 · BTHT1

Database Fundamentals

5 periodsDatabaseSQL Server

Objective: Get familiar with SQL Server, create databases, create tables, set up integrity constraints, and perform insert, update, and delete operations.

01 · DATABASE OVERVIEW

What Is a Database?

A Database is a collection of data organized and stored in a defined structure, making it easy to manage, retrieve, and process.

In practice, databases are used across many fields:

BankingAccounts, transactions, balances
HotelsGuests, rooms, bookings
AirlinesPassengers, flights, schedules
LibrariesBooks, readers, borrowing/returns

Example

A university might need to manage:

Student │ ├── Student ID ├── Full Name ├── Date of Birth └── Class

With tens of thousands of students, storing everything in separate files becomes hard to manage. A database organizes the data into related tables:

DATABASE: QuanLySinhVien

LOP (1) - parent table
MaLop
TenLop

↓ 1-N relationship: one LOP has many SINHVIEN.

SINHVIEN (N) - child table
MaSV
HoTen
NgaySinh
MaLop (FK)
Common mistake when drawing this diagram: pointing the arrow the wrong way, which makes readers think "1 student has many classes." The correct direction goes from parent down to child: LOP is the parent table (holds the primary key MaLop), SINHVIEN is the child table (holds the foreign key MaLop referencing LOP) - one class has many students (1-N), not the other way around.

Database Management System (DBMS)

A Database Management System (DBMS) is dedicated software used to create, manage, and operate a database, letting users access, control, and process data efficiently without touching the underlying storage files directly.

Some common DBMS products:

SQL Server ➜ Microsoft's DBMS, widely used in enterprises - used in this course MySQL ➜ Open-source DBMS, popular for web applications Oracle ➜ A powerful DBMS used by large organizations, complex systems PostgreSQL, SQLite, MongoDB... ➜ Many other options depending on the need

A database and a DBMS together form a complete database system: users/developers send queries through an application program, the DBMS receives and processes those queries, then retrieves the matching data from the database.

02 · SQL SERVER MANAGEMENT STUDIO

Installing SQL Server & SSMS

Before the practice sessions, install 2 components on your computer: SQL Server (the database engine) and SQL Server Management Studio - SSMS (the client tool for connecting, writing queries, and managing SQL Server). SQL Server doesn't come with a built-in interface, so SSMS is required.

Introducing Microsoft SQL Server

SQL Server is a relational database management system (RDBMS) built by Microsoft, first released in 1989 and continuously updated since then:

SOME MAJOR VERSION MILESTONES

VersionRelease YearKey Features
SQL Server 1.01989The first version (a Microsoft-Sybase partnership), basic relational database features
SQL Server 6.51996The first Windows NT version built entirely in-house by Microsoft
SQL Server 7.01998A full storage engine rewrite, improved management interface
SQL Server 20002000XML support, improved performance and security
SQL Server 20052005Introduced SQL Server Management Studio (SSMS), .NET CLR integration, Reporting Services
SQL Server 20082008Data Compression, Policy-Based Management
SQL Server 20122012AlwaysOn Availability Groups, Columnstore Index
SQL Server 20162016Always Encrypted, JSON support, R language integration
SQL Server 20172017Runs on Linux for the first time, Python integration
SQL Server 20192019Big Data Clusters, AI integration, faster database recovery
SQL Server 20222022Deep Azure integration - the version used in this course
SQL Server 20252025Built-in AI directly in SQL Server (vector search, calling AI models from T-SQL), the newest version available today

SQL Server 2025 is the newest release, but this course still uses SQL Server 2022 to keep things stable and consistent across everyone's setup.

EDITIONS

Each SQL Server version is also packaged into several editions, serving different needs and budgets:

EditionDescriptionCost
EnterpriseThe most advanced feature set (security, performance, large-scale data analytics) - built for large enterprises/organizationsPaid, very expensive
StandardCore features, sufficient for small and medium-sized businessesPaid
WebOptimized for website hosting, only available through hosting providersPaid (low cost)
DeveloperHas all the same features as Enterprise, but is only licensed for learning/development/testing - not for a live production systemFree
ExpressA scaled-down edition with a database size cap (10GB max) and limited CPU/RAM usage - suited to small applicationsFree
Which edition does this course install? Install the Developer Edition - it's free but has all the same features as Enterprise, without Express's database size or resource caps, making it the best fit for learning and practicing with real-world capabilities. Don't use Express (limited features), and none of the paid Enterprise/Standard/Web editions are needed.

Installing SQL Server 2022 (Developer Edition)

  1. Download the installer from the Microsoft site, choosing Download Media to download the setup files first instead of installing directly over the network.
  2. Run SQLServer2022-DEV-x64-ENU.exe, go to Installation, and choose the Developer edition.
  3. Accept the license terms. You can uncheck automatic update checks if you don't need them.
  4. On the Feature Selection step, checking Database Engine Services alone is enough for this course.
  5. Leave the Instance ID at its default, MSSQLSERVER.
  6. On the authentication step (Database Engine Configuration), leave it on the default Windows Authentication Mode and click Next - no need to switch to Mixed Mode or set an sa password for individual practice.
  7. Wait for the install to finish, verify the components installed successfully, then click Close.

Installing SQL Server Management Studio (SSMS)

  1. Download the SSMS installer from the Microsoft site (search "Download SQL Server Management Studio").
  2. Run SSMS-Setup-ENU.exe and click Install.
  3. Wait a few minutes for the install to finish, then click Close.
See the full install guide with step-by-step screenshots at SQL Server Tutorial. View guide ›
Installation errors? If installing SQL Server or SSMS runs into an error you can't resolve on your own, contact the instructor in charge of your practicum class for direct help rather than spending time troubleshooting alone.

Once installed, the SSMS interface is typically used to:

  • Connect to SQL Server
  • Create a Database
  • Create a Table
  • Write and execute SQL statements
  • View data
  • Manage objects within the Database

Basic Workflow

Open SSMS ↓ Connect to SQL Server ↓ Select / create a Database ↓ Open a New Query ↓ Write the SQL statement ↓ Execute ↓ View the results

Example: Your First Statement

SELECT 'Hello SQL Server';

Result:

Hello SQL Server

03 · DATA TYPES IN SQL

Data Types in SQL

When creating a table, every column must be assigned a data type - defining what kind of value it can store (numbers, text, dates...) and how much storage it uses. Choosing the right data type keeps data accurate, saves storage, and ensures later operations work correctly.
SinhVien MaSV ➜ INT HoTen ➜ NVARCHAR(50) NgaySinh ➜ DATE DiemTB ➜ DECIMAL(4,2) DaTotNghiep ➜ BIT

Integer Types

TypeStorageValue Range
TINYINT1 byte0 ➜ 255
SMALLINT2 bytes-32,768 ➜ 32,767
INT4 bytes≈ -2.1 billion ➜ 2.1 billion
BIGINT8 bytesVery large range
MaSV INT
SoLuong INT
Tuoi TINYINT
Selection principle: Prefer the smallest range that still fits your real-world data, to save storage. For example, Tuoi (age, 0-150) should use TINYINT instead of INT.

Boolean Type - BIT

BIT stores true/false values, commonly used for "yes/no" columns:

DaTotNghiep BIT

Stored values: 1 (true), 0 (false), or NULL (undefined).

Decimal / Floating-Point Types

TypeDescriptionUse When
DECIMAL(p,s) / NUMERIC(p,s)Exact decimal number - p is the total digit count, s is the number of digits after the decimal pointGrades, quantities, unit prices - when exact results matter
FLOATFloating-point number, approximate precision, very large value rangeScientific calculations that don't require exact precision
REALSimilar to FLOAT but lower precision and storageApproximate figures where precision matters less
MONEYDedicated currency type, precise to 4 decimal placesCurrency values with a large range
SMALLMONEYSimilar to MONEY but a smaller value rangeCurrency values with a small range

DECIMAL(p,s) lets you define the total number of digits (p) and the number of digits after the decimal point (s). For example:

DiemTB DECIMAL(4,2)

Can store: 8.50, 9.25, 10.00

MONEY and SMALLMONEY are dedicated to currency values, more precise than FLOAT/REAL for calculations:

DonGia MONEY
Recommendation: For grades, unit prices, and money - prefer DECIMAL(p,s) or MONEY since they give exact results. FLOAT/REAL are approximate and can drift after repeated calculations.

String Types

CHAR(n) - a fixed-length string (always occupies exactly n characters, padded with spaces):

MaSV CHAR(8)

Example value: "23520001"

VARCHAR(n) - a variable-length string (only uses as much storage as the actual number of characters):

Email VARCHAR(100)

NCHAR and NVARCHAR - similar to CHAR/VARCHAR but store Unicode strings, suitable for storing accented Vietnamese text:

HoTen NVARCHAR(50)
DiaChi NVARCHAR(200)

When text can be very long with no fixed length in advance (e.g. a product description), use VARCHAR(MAX) or NVARCHAR(MAX) instead of declaring a fixed size.

Quick Comparison - Which String Type to Use?

TypeLengthUnicode (Vietnamese)Use When
CHAR(n)FixedNoCodes that are always the same length (e.g. an 8-character student ID)
VARCHAR(n)VariableNoEnglish/numeric strings of variable length
NCHAR(n)FixedYesVietnamese codes that are always the same length
NVARCHAR(n)VariableYesVietnamese names, addresses, descriptions - the most commonly used
Recommendation: When storing Vietnamese data in SQL Server, use NVARCHAR and prefix string literals with N when inserting values.
INSERT INTO SinhVien
VALUES (1, N'Nguyễn Văn An', 'HTTT2022.1');

Date and Time Types

TypeStoresExample Value
DATEDate only'2004-05-20'
TIMETime only'14:30:00'
DATETIMEDate + time'2004-05-20 14:30:00'
SMALLDATETIMEDate + time (lower precision)'2004-05-20 14:30:00'
DATETIME2Date + time (higher precision, recommended over DATETIME for new systems)'2004-05-20 14:30:00.123'
NgaySinh DATE
NgayLap DATETIME
Note on entering dates: Date values must be enclosed in single quotes and follow the default format 'yyyy-mm-dd'. For example, '2004-05-20' means May 20, 2004.

You can change the expected input format with SET DATEFORMAT. For example, to enter dates as day-month-year 'dd-mm-yyyy':

SET DATEFORMAT dmy;

INSERT INTO SinhVien (MaSV, HoTen, NgaySinh, Lop)
VALUES (104, N'Phạm Thị Dung', '20-05-2004', N'HTTT2022.1');

SET DATEFORMAT only affects the current SSMS session - it does not permanently change the database configuration.

04 · DATABASE

Database

Creating a Database

Syntax:

CREATE DATABASE <Database name>;

Example:

CREATE DATABASE QuanLySinhVien;

Selecting a Database to Work With

After creating a database, use USE:

USE QuanLySinhVien;

From this point on, subsequent statements run against the QuanLySinhVien database. Always check which database is currently selected in SSMS before running commands.

Dropping a Database

DROP DATABASE QuanLySinhVien;
Cannot be undone: This deletes the database and all data inside it. A database that is in use or has active connections cannot be dropped directly.

05 · TABLE

Table

A Table consists of Columns (data attributes) and Rows (records). A Table is a collection of records sharing the same structure. Example:

SINHVIEN

MaSVHoTenNgaySinh
1Nguyễn Văn An2004-05-20
2Trần Thị Bình2004-08-15
3Lê Văn Cường2004-11-02

SQL uses its own set of terms, corresponding to the terms used in relational database theory:

SQL TermDatabase Term
TableRelation
ColumnAttribute
RowTuple

To define a table in SQL, you need: the table name, its columns, each column's data type, and any integrity constraints on it.

Creating a Table

Basic syntax:

CREATE TABLE <Table name>
(
    <Column 1> <Data type>,
    <Column 2> <Data type>,
    ...
);

Example:

CREATE TABLE SinhVien
(
    MaSV INT,
    HoTen NVARCHAR(50),
    NgaySinh DATE,
    Lop NVARCHAR(20)
);

QUICK CHECK

Which statement is used to create a Table?

Dropping a Table

DROP TABLE SinhVien;
Cannot be undone: When a Table is dropped, the data inside it is also deleted. A Table cannot be dropped while another table's Foreign Key still references it.

ALTER TABLE

ALTER TABLE is used to change a Table's structure after it has been created.

Add a column

ALTER TABLE SinhVien
ADD Email NVARCHAR(100);

Drop a column

ALTER TABLE SinhVien
DROP COLUMN Email;

Change a column's data type

ALTER TABLE SinhVien
ALTER COLUMN NgaySinh DATE;

06 · INTEGRITY CONSTRAINTS

Constraints

A Constraint helps ensure that data in the Database follows certain rules.

Types of Integrity Constraints

Integrity constraints in SQL Server fall into 2 main categories:

TypeDescription
Simple constraintsDescribed directly in CREATE TABLE/ALTER TABLE using the CONSTRAINT keyword - covers most everyday integrity rules.
Complex constraintsUse a TRIGGER to enforce more complex integrity rules that CONSTRAINT can't handle (e.g. rules spanning multiple tables or multiple rows).

Week 1 only covers the simple constraints below - TRIGGER is covered in later weeks:

PRIMARY KEY FOREIGN KEY UNIQUE NOT NULL CHECK DEFAULT

PRIMARY KEY

The primary key uniquely identifies each record in a Table.

CREATE TABLE SinhVien
(
    MaSV INT PRIMARY KEY,
    HoTen NVARCHAR(50),
    NgaySinh DATE
);

This means no two students can share the same MaSV.

Composite Primary Key

Sometimes the primary key isn't a single column but a combination of several columns - common in "detail" tables representing N-N relationships. For example, an CTHD (invoice line item) table has no dedicated ID column, and instead uses the pair (SOHD, MASP) to uniquely identify each row:

CREATE TABLE CTHD
(
    SOHD INT,
    MASP CHAR(4),
    SL INT,

    CONSTRAINT PK_CTHD PRIMARY KEY (SOHD, MASP)
);

Placing the CONSTRAINT on its own line at the end is the only way to declare a multi-column primary key - you cannot write PRIMARY KEY after each individual column in this case.

NOT NULL

NOT NULL requires a column to always have a value.

CREATE TABLE SinhVien
(
    MaSV INT PRIMARY KEY,
    HoTen NVARCHAR(50) NOT NULL,
    NgaySinh DATE
);

The following statement is invalid because HoTen is declared NOT NULL:

INSERT INTO SinhVien
VALUES (1, NULL, '2004-05-20');

UNIQUE

Ensures values in a column are never duplicated.

CREATE TABLE SinhVien
(
    MaSV INT PRIMARY KEY,
    Email NVARCHAR(100) UNIQUE
);
SV001 ➜ kha@uit.edu.vn SV002 ➜ kha@uit.edu.vn ✗ duplicate

FOREIGN KEY

FOREIGN KEY is used to create a relationship between tables. For example, given two tables:

LOP

MaLopTenLop
1HTTT2022.1
2HTTT2022.2

↑ SINHVIEN.MaLop references LOP.MaLop.

SINHVIEN

MaSVMaLop
1011
1021
1032
CREATE TABLE Lop
(
    MaLop INT PRIMARY KEY,
    TenLop NVARCHAR(50)
);

CREATE TABLE SinhVien
(
    MaSV INT PRIMARY KEY,
    HoTen NVARCHAR(50),
    MaLop INT,

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

In that case, the following statement is rejected if 999 doesn't exist in Lop.MaLop:

INSERT INTO SinhVien
VALUES (101, N'Nguyễn Văn An', 999);

The foreign key must be defined on the table that holds it.

CHECK

CHECK restricts data to satisfy a condition. For example, a student's grade must be between 0 and 10:

CREATE TABLE KetQua
(
    MaSV INT,
    Diem DECIMAL(4,2),

    CHECK (Diem >= 0 AND Diem <= 10)
);
INSERT INTO KetQua
VALUES (101, 8.5);

✓ Valid. But:

INSERT INTO KetQua
VALUES (102, 15);

✗ Invalid.

DEFAULT

DEFAULT supplies a fallback value when the user doesn't provide one.

CREATE TABLE SinhVien
(
    MaSV INT PRIMARY KEY,
    HoTen NVARCHAR(50),
    GioiTinh CHAR(1) DEFAULT 'M'
);

If:

INSERT INTO SinhVien(MaSV, HoTen)
VALUES (101, N'Nguyễn Văn An');

then SQL Server automatically sets GioiTinh = 'M'.

Declaring Multiple Constraints

Multiple constraints can be combined - data types and constraints always go together when designing a Table:

CREATE TABLE SinhVien
(
    MaSV INT PRIMARY KEY,

    HoTen NVARCHAR(50) NOT NULL,

    Email NVARCHAR(100) UNIQUE,

    MaLop INT
        FOREIGN KEY REFERENCES Lop(MaLop),

    NgaySinh DATE
        CHECK (NgaySinh >= '1900-01-01'),

    GioiTinh CHAR(1)
        DEFAULT 'M'
);

07 · DATA MANIPULATION - DML

Data Manipulation Language

DML (Data Manipulation Language) is the group of commands used to manipulate data within a Table.

In Week 1, students get familiar with:

INSERT ➜ Add data DELETE ➜ Remove data UPDATE ➜ Modify data SELECT INTO ➜ Copy data

INSERT - Adding Data

Method 1: Without specifying column names

INSERT INTO SinhVien
VALUES (101, N'Nguyễn Văn An', '2004-05-20', N'HTTT2022.1');

Method 2: Specifying column names - this is the preferred method, since the statement is clearer and less dependent on column order.

INSERT INTO SinhVien
(
    MaSV,
    HoTen,
    NgaySinh,
    Lop
)
VALUES
(
    101,
    N'Nguyễn Văn An',
    '2004-05-20',
    N'HTTT2022.1'
);

Multiple records can be inserted in a single statement:

INSERT INTO SinhVien
VALUES
    (101, N'Nguyễn Văn An', '2004-05-20', N'HTTT2022.1'),
    (102, N'Trần Thị Bình', '2004-08-15', N'HTTT2022.1'),
    (103, N'Lê Văn Cường', '2004-11-02', N'HTTT2022.2');

Then verify:

SELECT *
FROM SinhVien;

DELETE - Removing Data

DELETE FROM <Table name>
WHERE <Condition>;

Example - only the student with MaSV = 101 is deleted:

DELETE FROM SinhVien
WHERE MaSV = 101;
Cannot be undone: Without a WHERE clause -
DELETE FROM SinhVien;
➜ every row in the table gets deleted.

UPDATE - Modifying Data

UPDATE <Table name>
SET <Column 1> = <New value>
WHERE <Condition>;
UPDATE SinhVien
SET HoTen = N'Nguyễn Văn Nam'
WHERE MaSV = 101;

Multiple columns can be updated at once:

UPDATE SinhVien
SET
    HoTen = N'Nguyễn Văn Nam',
    Lop = N'HTTT2022.2'
WHERE MaSV = 101;

SELECT INTO - Copying Data

SELECT INTO creates a new Table from a query's result.

SELECT *
INTO SinhVien_Backup
FROM SinhVien;
SINHVIEN ↓ SELECT INTO ↓ SINHVIEN_BACKUP

To copy only part of the data, filter with WHERE combined with the LIKE operator - used to match strings against a pattern with 2 wildcard characters:

CharacterMeaningExample
_Matches exactly 1 characterLIKE 'a__' - a string starting with "a", followed by exactly 2 more characters
%Matches 0, 1, or many charactersLIKE 'HTTT%' - a string starting with "HTTT", followed by anything
SELECT *
INTO SinhVien_HTTT
FROM SinhVien
WHERE Lop LIKE 'HTTT%';

Comprehensive Example - Student Management

Step 1 - Create the Database

CREATE DATABASE QuanLySinhVien;
GO

USE QuanLySinhVien;
GO

Step 2 - Create the Class Table

CREATE TABLE Lop
(
    MaLop INT PRIMARY KEY,
    TenLop NVARCHAR(50) NOT NULL
);

Step 3 - Create the Student Table

CREATE TABLE SinhVien
(
    MaSV INT PRIMARY KEY,
    HoTen NVARCHAR(50) NOT NULL,
    NgaySinh DATE,
    MaLop INT,

    CONSTRAINT FK_SinhVien_Lop
        FOREIGN KEY (MaLop)
        REFERENCES Lop(MaLop),

    CONSTRAINT CK_SinhVien_NgaySinh
        CHECK (NgaySinh >= '1900-01-01')
);

Step 4 - Insert Classes

INSERT INTO Lop
VALUES
    (1, N'HTTT2022.1'),
    (2, N'HTTT2022.2');

Step 5 - Insert Students

INSERT INTO SinhVien
VALUES
    (101, N'Nguyễn Văn An', '2004-05-20', 1),
    (102, N'Trần Thị Bình', '2004-08-15', 1),
    (103, N'Lê Văn Cường', '2004-11-02', 2);

Step 6 - Verify

SELECT *
FROM SinhVien;
MaSVHoTenNgaySinhMaLop
101Nguyễn Văn An2004-05-201
102Trần Thị Bình2004-08-151
103Lê Văn Cường2004-11-022

Step 7 - Update

UPDATE SinhVien
SET HoTen = N'Nguyễn Văn Nam'
WHERE MaSV = 101;

Step 8 - Delete

DELETE FROM SinhVien
WHERE MaSV = 103;

08 · PRACTICE EXERCISES & Q&A

Comprehensive Practice

OFFICIAL ASSIGNMENT · BTTH1

Sports & Fitness Center (TrungTam_TDTT)

See the full assignment, attached files, and detailed answers (access code required) for BTTH1.

View exercise & answers ›
EXTRA PRACTICE · OPTIONAL

Additional worked examples using the sample QuanLyBanHang database, to reinforce this week's DDL/Constraint content - not part of the BTTH1 submission.

PRACTICE LAB

Sales Management

  1. Exercise 1 - Create the Database: Create the QuanLyBanHang database
  2. Exercise 2 - Create Tables: KHACHHANG, NHANVIEN, SANPHAM, HOADON, CTHD
  3. Exercise 3 - Set Up Constraints: Primary Key, Foreign Key, NOT NULL, UNIQUE, CHECK, DEFAULT
  4. Exercise 4 - Insert Data: At least 5 customers, 5 employees, 10 products, 10 invoices
  5. Exercise 5 - Manipulate Data: Perform INSERT, UPDATE, DELETE, SELECT INTO
  6. Exercise 6 - Test Constraints: Try entering invalid data and observe SQL Server's error messages

Exercise 6 - Constraint Testing Example

Try entering invalid data to observe SQL Server's error messages:

INSERT INTO SinhVien
VALUES (101, N'Duplicate ID student', '2004-01-01', 1);

➜ Violates PRIMARY KEY.

INSERT INTO SinhVien
VALUES (104, N'Student without a class', '2004-01-01', 999);

➜ Violates FOREIGN KEY.

INSERT INTO SinhVien
VALUES (105, N'Student with invalid date', '1800-01-01', 1);

➜ Violates CHECK.

09 · END-OF-WEEK 1 CHECKLIST

Self-Check

After completing this week, students should check that they can:

  • Know what a Database is
  • Know how to use SQL Server Management Studio
  • Know the basic data types
  • Know CREATE DATABASE
  • Know USE DATABASE
  • Know CREATE TABLE
  • Know DROP TABLE
  • Know ALTER TABLE
  • Understand PRIMARY KEY
  • Understand FOREIGN KEY
  • Understand UNIQUE
  • Understand NOT NULL
  • Understand CHECK
  • Understand DEFAULT
  • Know INSERT
  • Know UPDATE
  • Know DELETE
  • Know SELECT INTO
  • Know how to verify data after an operation

Core Concepts to Remember

DATABASE ↓ TABLE ↓ COLUMN + DATA TYPE ↓ CONSTRAINT ↓ DATA ↓ INSERT / UPDATE / DELETE

This is the foundation for all of IT004. In Week 2, students begin using this data to perform SELECT, operators, functions, JOIN, set operations, and Subqueries.