Nội dung bài họcLesson content
Database và SQL là gì?What are databases and SQL?
Database lưu dữ liệu có cấu trúc. SQL (Structured Query Language) là ngôn ngữ giao tiếp với database quan hệ. SQLite là database nhẹ, miễn phí, lưu trong 1 file — lý tưởng cho người mới bắt đầu. Cài: npm install sqlite3.A database stores structured data. SQL (Structured Query Language) is the language for communicating with relational databases. SQLite is a lightweight, free database stored in a single file — ideal for beginners. Install: npm install sqlite3.
CREATE TABLE: tạo bảngCREATE TABLE: creating tables
Bảng (table) là cấu trúc lưu dữ liệu dạng hàng-cột. CREATE TABLE định nghĩa tên bảng, các cột, kiểu dữ liệu. PRIMARY KEY là cột định danh duy nhất. AUTOINCREMENT tự tăng. NOT NULL yêu cầu có giá trị.A table is a structure that stores data in rows and columns. CREATE TABLE defines the table name, columns, and data types. PRIMARY KEY is a unique identifier column. AUTOINCREMENT auto-increments. NOT NULL requires a value.
CREATE TABLE students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER,
score REAL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
-- Các kiểu dữ liệu phổ biến:
-- INTEGER: số nguyên
-- TEXT: chuỗi văn bản
-- REAL: số thập phân
-- DATETIME: ngày giờ
INSERT, SELECT, WHEREINSERT, SELECT, WHERE
INSERT INTO thêm hàng mới. SELECT truy vấn dữ liệu. WHERE lọc điều kiện. ORDER BY sắp xếp. LIMIT giới hạn số hàng. Đây là 4 lệnh SQL dùng nhiều nhất.INSERT INTO adds a new row. SELECT queries data. WHERE filters by condition. ORDER BY sorts. LIMIT restricts row count. These are the 4 most-used SQL commands.
-- Thêm dữ liệu
INSERT INTO students (name, age, score)
VALUES ('Hà Mi', 18, 9.5);
INSERT INTO students (name, age, score)
VALUES ('An', 17, 8.0);
-- Truy vấn tất cả
SELECT * FROM students;
-- Truy vấn có điều kiện
SELECT name, score FROM students
WHERE score >= 8.0
ORDER BY score DESC
LIMIT 10;
JOIN: nối nhiều bảngJOIN: linking multiple tables
JOIN nối 2 bảng theo cột chung. INNER JOIN chỉ lấy hàng khớp ở cả 2 bảng. LEFT JOIN lấy tất cả hàng bên trái + hàng khớp bên phải. Ví dụ: JOIN students với classes qua class_id để xem học sinh thuộc lớp nào.JOIN links 2 tables by a common column. INNER JOIN only takes matching rows from both tables. LEFT JOIN takes all left rows + matching right rows. Example: JOIN students with classes via class_id to see which class each student belongs to.
-- Tạo bảng classes
CREATE TABLE classes (
id INTEGER PRIMARY KEY,
name TEXT
);
-- Thêm cột class_id vào students
ALTER TABLE students ADD COLUMN class_id INTEGER;
-- JOIN: xem học sinh cùng tên lớp
SELECT students.name, students.score, classes.name AS class_name
FROM students
INNER JOIN classes ON students.class_id = classes.id
WHERE students.score >= 8.0;