Lý thuyết
Bài 1/10

Introduction to SQL Server

Làm quen với SQL Server, cài đặt AdventureWorks và viết truy vấn SQL đầu tiên

Bài 1: Introduction to SQL Server

SQL Server Database

1. Tại sao học SQL Server?

SQL Server là hệ quản trị cơ sở dữ liệu hàng đầu của Microsoft:

  • 🏢 Enterprise-grade - Được dùng bởi Fortune 500 companies
  • 📊 Tích hợp BI - SQL Server Reporting Services, Analysis Services
  • 🔒 Bảo mật cao - Row-level security, encryption, auditing
  • ☁️ Azure ready - Dễ dàng migrate lên cloud

SQL Server vs Các RDBMS khác

FeatureSQL ServerMySQLPostgreSQL
VendorMicrosoftOracleOpen Source
CostExpress Free / Enterprise $$$Free / EnterpriseFree
BI ToolsSSRS, SSAS, SSISLimitedLimited
T-SQL✅ Full support
Window Functions✅ Advanced✅ Basic✅ Advanced
Azure Integration✅ Native🔸 Partial🔸 Partial

2. Cài đặt môi trường

2.1 SQL Server Express (Free)

  1. Download SQL Server 2022 Express

    Truy cập SQL Server Downloads và tải Express edition (miễn phí).

  2. Cài đặt với Basic mode

    Chọn "Basic" installation để cài đặt nhanh với cấu hình mặc định.

  3. Download SQL Server Management Studio (SSMS)

    Tải SSMS - công cụ GUI để làm việc với SQL Server.

2.2 Restore AdventureWorks Database

AdventureWorks Database

AdventureWorks là database mẫu chính thức của Microsoft, mô phỏng công ty sản xuất xe đạp với dữ liệu HR, Sales, Production, Purchasing.

Download: AdventureWorks2022.bak

Các bước restore:

SQL
1-- 1. Copy file .bak vào thư mục backup của SQL Server
2-- Mặc định: C:\Program Files\Microsoft SQL Server\MSSQL16.MSSQLSERVER\MSSQL\Backup
3
4-- 2. Restore database bằng T-SQL
5RESTORE DATABASE AdventureWorks2022
6FROM DISK = 'C:\...\AdventureWorks2022.bak'
7WITH MOVE 'AdventureWorks2022' TO 'C:\...\AdventureWorks2022.mdf',
8 MOVE 'AdventureWorks2022_log' TO 'C:\...\AdventureWorks2022_log.ldf';

Hoặc dùng SSMS GUI: Right-click "Databases" → "Restore Database..." → Chọn file .bak


3. Khám phá AdventureWorks

3.1 Cấu trúc Schemas

AdventureWorks sử dụng Schemas để tổ chức tables:

Text
1┌─────────────────────────────────────────────────────────────┐
2│ AdventureWorks Database │
3├─────────────────────────────────────────────────────────────┤
4│ │
5│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
6│ │ HumanRe- │ │ Sales │ │ Production │ │
7│ │ sources │ │ │ │ │ │
8│ │ • Employee │ │ • Customer │ │ • Product │ │
9│ │ • Department│ │ • SalesOrder│ │ • WorkOrder │ │
10│ │ • Shift │ │ • Territory │ │ • BillOf │ │
11│ │ • JobCandi- │ │ • Store │ │ Materials │ │
12│ │ date │ │ • Currency │ │ • Location │ │
13│ └─────────────┘ └─────────────┘ └─────────────┘ │
14│ │
15│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
16│ │ Purchasing │ │ Person │ │ dbo │ │
17│ │ │ │ │ │ │ │
18│ │ • Vendor │ │ • Person │ │ • Error- │ │
19│ │ • Purchase │ │ • Address │ │ Log │ │
20│ │ Order │ │ • Email │ │ • Database │ │
21│ │ • ShipMethod│ │ • Phone │ │ Log │ │
22│ └─────────────┘ └─────────────┘ └─────────────┘ │
23│ │
24└─────────────────────────────────────────────────────────────┘

3.2 Tables quan trọng nhất

SchemaTableMô tảRows ước tính
HumanResourcesEmployeeThông tin nhân viên~290
HumanResourcesDepartmentCác phòng ban~16
PersonPersonThông tin cá nhân~19,000
SalesCustomerKhách hàng~19,000
SalesSalesOrderHeaderĐơn hàng~31,000
SalesSalesOrderDetailChi tiết đơn hàng~121,000
ProductionProductSản phẩm~500
ProductionProductCategoryDanh mục sản phẩm~4

4. Truy vấn SQL đầu tiên

4.1 SELECT Statement

Cú pháp cơ bản nhất để lấy dữ liệu:

SQL
1SELECT column1, column2
2FROM schema.table_name;

Ví dụ với AdventureWorks:

SQL
1-- Lấy tất cả departments
2SELECT *
3FROM HumanResources.Department;

Kết quả:

Text
1DepartmentID | Name | GroupName
2-------------|-------------------------|----------------------------------
31 | Engineering | Research and Development
42 | Tool Design | Research and Development
53 | Sales | Sales and Marketing
64 | Marketing | Sales and Marketing
75 | Purchasing | Inventory Management
8...
SQL
1-- Lấy columns cụ thể
2SELECT
3 Name,
4 GroupName
5FROM HumanResources.Department;

4.2 Column Alias (AS)

Đổi tên cột trong kết quả:

SQL
1SELECT
2 Name AS DepartmentName,
3 GroupName AS Division
4FROM HumanResources.Department;

4.3 DISTINCT - Loại bỏ trùng lặp

SQL
1-- Các Division khác nhau trong công ty
2SELECT DISTINCT GroupName
3FROM HumanResources.Department;

Kết quả:

Text
1GroupName
2----------------------------------
3Executive General and Administration
4Inventory Management
5Manufacturing
6Quality Assurance
7Research and Development
8Sales and Marketing

5. WHERE - Lọc dữ liệu

5.1 Comparison Operators

SQL
1-- Products có giá > 1000
2SELECT
3 Name,
4 ListPrice
5FROM Production.Product
6WHERE ListPrice > 1000;
SQL
1-- Employees được thuê sau 2010
2SELECT
3 BusinessEntityID,
4 JobTitle,
5 HireDate
6FROM HumanResources.Employee
7WHERE HireDate >= '2010-01-01';

5.2 Logical Operators (AND, OR, NOT)

SQL
1-- Products là Bikes VÀ có giá > 1000
2SELECT
3 p.Name,
4 p.ListPrice,
5 pc.Name AS Category
6FROM Production.Product p
7JOIN Production.ProductSubcategory ps ON p.ProductSubcategoryID = ps.ProductSubcategoryID
8JOIN Production.ProductCategory pc ON ps.ProductCategoryID = pc.ProductCategoryID
9WHERE pc.Name = 'Bikes'
10 AND p.ListPrice > 1000;
SQL
1-- Employees là Manager HOẶC Engineer
2SELECT
3 BusinessEntityID,
4 JobTitle
5FROM HumanResources.Employee
6WHERE JobTitle LIKE '%Manager%'
7 OR JobTitle LIKE '%Engineer%';

5.3 IN, BETWEEN, LIKE

SQL
1-- Products trong các màu cụ thể
2SELECT Name, Color, ListPrice
3FROM Production.Product
4WHERE Color IN ('Black', 'Red', 'Silver');
SQL
1-- Products có giá trong khoảng
2SELECT Name, ListPrice
3FROM Production.Product
4WHERE ListPrice BETWEEN 500 AND 1500;
SQL
1-- Tìm Products có tên chứa 'Mountain'
2SELECT Name, ListPrice
3FROM Production.Product
4WHERE Name LIKE '%Mountain%';
5
6-- Tìm Products bắt đầu bằng 'Road'
7SELECT Name, ListPrice
8FROM Production.Product
9WHERE Name LIKE 'Road%';

5.4 NULL Handling

SQL
1-- Products KHÔNG có Color (NULL)
2SELECT Name, Color, ListPrice
3FROM Production.Product
4WHERE Color IS NULL;
5
6-- Products CÓ Color
7SELECT Name, Color, ListPrice
8FROM Production.Product
9WHERE Color IS NOT NULL;

6. ORDER BY - Sắp xếp kết quả

6.1 Single Column Sort

SQL
1-- Products sắp xếp theo giá (thấp → cao)
2SELECT Name, ListPrice
3FROM Production.Product
4WHERE ListPrice > 0
5ORDER BY ListPrice ASC;
6
7-- Products sắp xếp theo giá (cao → thấp)
8SELECT Name, ListPrice
9FROM Production.Product
10WHERE ListPrice > 0
11ORDER BY ListPrice DESC;

6.2 Multiple Column Sort

SQL
1-- Sắp xếp theo Color, rồi theo ListPrice
2SELECT Name, Color, ListPrice
3FROM Production.Product
4WHERE Color IS NOT NULL
5ORDER BY Color ASC, ListPrice DESC;

6.3 TOP - Giới hạn kết quả

SQL
1-- Top 10 Products đắt nhất
2SELECT TOP 10
3 Name,
4 ListPrice
5FROM Production.Product
6ORDER BY ListPrice DESC;
7
8-- Top 5% Orders lớn nhất
9SELECT TOP 5 PERCENT
10 SalesOrderID,
11 TotalDue
12FROM Sales.SalesOrderHeader
13ORDER BY TotalDue DESC;

7. Thực hành

Bài tập thực hành

Sử dụng AdventureWorks database, viết các truy vấn sau:

Exercise 1: Basic SELECT

SQL
1-- Liệt kê tất cả Departments (Name, GroupName)
2-- từ bảng HumanResources.Department
3
4-- YOUR CODE HERE
💡 Xem đáp án
SQL
1SELECT
2 Name,
3 GroupName
4FROM HumanResources.Department;

Exercise 2: WHERE with conditions

SQL
1-- Tìm Products có ListPrice > 2000
2-- Chỉ lấy Name và ListPrice
3-- Sắp xếp theo giá giảm dần
4
5-- YOUR CODE HERE
💡 Xem đáp án
SQL
1SELECT
2 Name,
3 ListPrice
4FROM Production.Product
5WHERE ListPrice > 2000
6ORDER BY ListPrice DESC;

Exercise 3: LIKE pattern matching

SQL
1-- Tìm tất cả Employees có JobTitle chứa 'Engineer'
2-- Hiển thị BusinessEntityID, JobTitle, HireDate
3
4-- YOUR CODE HERE
💡 Xem đáp án
SQL
1SELECT
2 BusinessEntityID,
3 JobTitle,
4 HireDate
5FROM HumanResources.Employee
6WHERE JobTitle LIKE '%Engineer%'
7ORDER BY HireDate;

Exercise 4: Combining conditions

SQL
1-- Tìm Products:
2-- - Có ListPrice từ 500 đến 1500
3-- - Color là 'Black' hoặc 'Red'
4-- - Hiển thị Name, Color, ListPrice
5-- - Sắp xếp theo Color, rồi ListPrice
6
7-- YOUR CODE HERE
💡 Xem đáp án
SQL
1SELECT
2 Name,
3 Color,
4 ListPrice
5FROM Production.Product
6WHERE ListPrice BETWEEN 500 AND 1500
7 AND Color IN ('Black', 'Red')
8ORDER BY Color, ListPrice;

8. Tổng kết

Trong bài này, bạn đã học:

ConceptSyntaxVí dụ
SELECTSELECT columns FROM schema.tableSELECT Name FROM Production.Product
WHEREWHERE conditionWHERE ListPrice > 100
Operators=, <>, >, <, >=, <=WHERE Qty >= 10
AND/ORWHERE cond1 AND cond2WHERE A = 1 AND B = 2
INWHERE col IN (...)WHERE Color IN ('Red','Blue')
BETWEENWHERE col BETWEEN a AND bWHERE Price BETWEEN 100 AND 500
LIKEWHERE col LIKE patternWHERE Name LIKE '%Bike%'
NULLIS NULL, IS NOT NULLWHERE Color IS NOT NULL
ORDER BY`ORDER BY col [ASCDESC]`
TOPTOP nSELECT TOP 10 *

Bài tiếp theo: Aggregate Functions (COUNT, SUM, AVG, GROUP BY)