Creating tables · Tạo bảng
Two kinds of SQL command
SQL has two halves:
- DDL (Data Definition Language) changes the structure — the tables themselves.
- DML (Data Manipulation Language) works with the data inside the tables — reading it with
SELECT, and adding, changing, or removing it withINSERT/UPDATE/DELETE. Everything so far (SELECT) is DML.
CREATE TABLE is the main DDL command. It lists each column with a data type and marks the primary key:
Hai loại lệnh SQL
SQL có hai phần chính:
- DDL (Ngôn ngữ Định nghĩa Dữ liệu) thay đổi cấu trúc — bản thân các bảng.
- DML (Ngôn ngữ Thao tác Dữ liệu) làm việc với dữ liệu bên trong các bảng — đọc dữ liệu bằng
SELECT, và thêm, sửa hoặc xóa dữ liệu bằngINSERT/UPDATE/DELETE. Tất cả những gì đã trình bày trước đây (SELECT) đều thuộc DML.
CREATE TABLE là lệnh DDL chính. Nó liệt kê từng cột kèm kiểu dữ liệu và đánh dấu khóa chính:
CREATE TABLE customer (
id INTEGER PRIMARY KEY,
name VARCHAR(20),
city VARCHAR(15)
);
Data types and foreign keys
Common data types:
INTEGER— whole numbersVARCHAR(n)/CHAR(n)— text, up to / exactlyncharactersDECIMAL(p, s)— a number withsdecimal placesDATE,BOOLEAN
To link to another table, add a FOREIGN KEY:
The checker reads back your table's structure to see which columns you created.
Kiểu dữ liệu và khóa ngoại
Các kiểu dữ liệu phổ biến:
INTEGER— số nguyênVARCHAR(n)/CHAR(n)— văn bản, tối đa / đúngnký tựDECIMAL(p, s)— số cóschữ số thập phânDATE,BOOLEAN
Để liên kết với bảng khác, hãy thêm một FOREIGN KEY:
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER,
FOREIGN KEY (customer_id) REFERENCES customer(id)
);
Trình kiểm tra sẽ đọc lại cấu trúc bảng của bạn để xem các cột nào bạn đã tạo.
Common mistakes
- Every column needs a data type (e.g.
INTEGER,TEXT). - Declare the PRIMARY KEY when you create the table.
Những lỗi thường gặp
- Mỗi cột cần một kiểu dữ liệu (ví dụ:
INTEGER,TEXT). - Khai báo PRIMARY KEY khi tạo bảng.
Create a table called teacher with three columns: id (INTEGER, the primary key), name (VARCHAR(20)), and subject (VARCHAR(15)). · Tạo một bảng có tên gọi là teacher với ba cột: id (kiểu dữ liệu INTEGER, khóa chính), name (kiểu dữ liệu VARCHAR(20)), và subject (kiểu dữ liệu VARCHAR(15)).
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.
Design another table. Create event with id (INTEGER PRIMARY KEY), title (VARCHAR(30)), and price (DECIMAL(6,2) — a money column with 2 decimal places). · Thiết kế một bảng khác. Tạo event với id (INTEGER PRIMARY KEY), title (VARCHAR(30)), và price (DECIMAL(6,2) — một cột tiền tệ với 2 chữ số thập phân).
Click Run to see the output here. · Nhấn Chạy để xem kết quả ở đây.