09 การออกแบบ Table, Constraint และ Index
การออกแบบ Table, Constraint และ Index
การเขียน query ได้เป็นเรื่องสำคัญ แต่การเข้าใจ table design จะช่วยให้ใช้ database ได้ถูกต้องขึ้น
CREATE TABLE
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE,
created_at TIMESTAMP
);
Data Type
ชนิดข้อมูลที่เจอบ่อย:
INTEGERจำนวนเต็มDECIMALหรือNUMERICตัวเลขที่ต้องการความแม่นยำTEXTข้อความDATEวันที่TIMESTAMPวันที่และเวลาBOOLEANจริงหรือเท็จ
Primary Key
Primary key คือ column ที่ระบุ row แบบไม่ซ้ำ
customer_id INTEGER PRIMARY KEY
Foreign Key
Foreign key ใช้เชื่อมความสัมพันธ์กับ table อื่น
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER,
amount DECIMAL(10, 2),
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);
NOT NULL และ UNIQUE
email TEXT UNIQUE,
name TEXT NOT NULL
NOT NULLบังคับว่าต้องมีค่าUNIQUEห้ามค่าซ้ำ
Index
Index ช่วยให้ค้นหาข้อมูลเร็วขึ้น แต่ทำให้การเขียนข้อมูลมีต้นทุนเพิ่ม จึงควรสร้างบน column ที่ใช้ filter หรือ join บ่อย
CREATE INDEX idx_orders_customer_id
ON orders(customer_id);
หลักคิดในการออกแบบเบื้องต้น
- หนึ่ง table ควรแทน entity หนึ่งอย่าง เช่น customers, orders, products
- ไม่เก็บข้อมูลซ้ำโดยไม่จำเป็น
- ตั้ง primary key ให้ชัดเจน
- ใช้ foreign key เมื่อมีความสัมพันธ์
- เลือก data type ให้เหมาะกับข้อมูล
แบบฝึกหัด
ออกแบบ table สำหรับระบบขายของง่าย ๆ
customersproductsordersorder_items
ระบุ primary key และ foreign key ของแต่ละ table