1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
create database testdb;
create user user_name with password 'your_pwsd';
create schema my_schema;
create table user(
id serial primary key,
name text not null,
email text not null,
age integer check (age >= 0 and age <=150),
is_active BOOLEAN default true,
created_at timestamp default current_timestamp,
updated_at timestamp default current_timestamp
);
# 在sales schema 中直接创建表
create TABLE sales.orders (
id SERIAL PRIMARY KEY,
amount DECIMAL(10,2)
);
# 创建一个带约束的表
CREATE TABLE products (
id SERIAL PRIMARY KEY,
sku TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
price DECIMAL(10,2) NOT NULL CHECK (price > 0),
category_id INTEGER REFERENCES categories(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ DEFAULT NOW()
);
PRIMARY KEY (user_id, role_id),
UNIQUE (student_id, course_code),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE
ON UPDATE(一般不用)
1. CASCADE → 父删子随删(适合从属强依赖数据)
2. SET NULL → 父删子设空(字段必须可 NULL)
3. RESTRICT → 父删若子存在则报错(默认,最安全)
-- 普通索引
CREATE INDEX idx_users_email ON users(email);
-- 唯一索引
CREATE UNIQUE INDEX idx_users_lower_email ON users(LOWER(email));
-- 多列索引
CREATE INDEX idx_orders_user_date ON orders(user_id, created_at DESC);
-- 针对 JSONB 字段的索引(GIN)
CREATE INDEX idx_products_tags ON products USING GIN(tags); -- tags 是 jsonb
|