在創建表時,可以使用約束來定義表中數據的規則和限制。以下是SQL中一些常見的約束類型:
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(50)
);
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customers(cust_id)
);
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(50) NOT NULL
);
CREATE TABLE products (
product_id INT PRIMARY KEY,
product_name VARCHAR(50) UNIQUE
);
CREATE TABLE students (
id INT PRIMARY KEY,
age INT CHECK (age >= 18)
);
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(50),
emp_salary INT DEFAULT 0
);
通過使用這些約束,可以有效地保證表中數據的完整性和一致性。