1. 添加列:
ALTER TABLE table_name
ADD column_name datatype;
2. 删除列:
ALTER TABLE table_name
DROP COLUMN column_name;
3. 修改列的数据类型:
ALTER TABLE table_name
ALTER COLUMN column_name new_datatype;
4. 修改列名:
ALTER TABLE table_name
RENAME COLUMN old_column_name TO new_column_name;
5. 添加主键:
ALTER TABLE table_name
ADD PRIMARY KEY (column_name);
6. 删除主键:
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
7. 添加外键:
ALTER TABLE table_name
ADD FOREIGN KEY (column_name) REFERENCES referenced_table(referenced_column);
8. 删除外键:
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
示例:
1. 添加列:
ALTER TABLE employees
ADD email VARCHAR(100);
2. 删除列:
ALTER TABLE employees
DROP COLUMN email;
3. 修改列的数据类型:
ALTER TABLE employees
ALTER COLUMN hire_date DATE;
4. 修改列名:
ALTER TABLE employees
RENAME COLUMN employee_name TO full_name;
5. 添加主键:
ALTER TABLE employees
ADD PRIMARY KEY (employee_id);
6. 删除主键:
ALTER TABLE employees
DROP CONSTRAINT employees_pkey;
7. 添加外键:
ALTER TABLE orders
ADD FOREIGN KEY (customer_id) REFERENCES customers(customer_id);
8. 删除外键:
ALTER TABLE orders
DROP CONSTRAINT orders_customer_fk;
在执行 ALTER TABLE 语句之前,请确保你有足够的权限来修改表的结构,并谨慎操作,以免影响现有的数据。
转载请注明出处:http://www.pingtaimeng.com/article/detail/3335/SQL