1. 添加列:
ALTER TABLE table_name
ADD COLUMN new_column_name data_type;
例如:
ALTER TABLE employees
ADD COLUMN email VARCHAR(100);
2. 删除列:
ALTER TABLE table_name
DROP COLUMN column_name;
例如:
ALTER TABLE employees
DROP COLUMN email;
3. 修改列的数据类型:
ALTER TABLE table_name
ALTER COLUMN column_name TYPE new_data_type;
例如:
ALTER TABLE employees
ALTER COLUMN salary TYPE NUMERIC;
4. 重命名列:
ALTER TABLE table_name
RENAME COLUMN old_column_name TO new_column_name;
例如:
ALTER TABLE employees
RENAME COLUMN emp_name TO employee_name;
5. 添加主键约束:
ALTER TABLE table_name
ADD CONSTRAINT pk_constraint_name PRIMARY KEY (column_name);
例如:
ALTER TABLE employees
ADD CONSTRAINT pk_employee_id PRIMARY KEY (employee_id);
6. 删除主键约束:
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
例如:
ALTER TABLE employees
DROP CONSTRAINT pk_employee_id;
7. 添加外键约束:
ALTER TABLE table_name
ADD CONSTRAINT fk_constraint_name
FOREIGN KEY (column_name) REFERENCES referenced_table (referenced_column);
例如:
ALTER TABLE orders
ADD CONSTRAINT fk_customer_id
FOREIGN KEY (customer_id) REFERENCES customers (customer_id);
8. 删除外键约束:
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
例如:
ALTER TABLE orders
DROP CONSTRAINT fk_customer_id;
9. 修改列的默认值:
ALTER TABLE table_name
ALTER COLUMN column_name SET DEFAULT new_default_value;
例如:
ALTER TABLE employees
ALTER COLUMN salary SET DEFAULT 50000;
这些是 ALTER TABLE 命令的一些常见用法,可以根据实际需求进行相应的修改操作。在进行任何结构修改之前,请确保备份数据库以防万一,并谨慎操作,以免影响数据完整性。
转载请注明出处:http://www.zyzy.cn/article/detail/14147/PostgreSQL