Home > Database > SQL > body text

Statements to modify table structure in sql

下次还敢
Release: 2024-04-29 13:51:15
Original
505 people have browsed it

The statements in SQL that modify the table structure include: ALTER TABLE table_name ADD column_name data_type Add column ALTER TABLE table_name ALTER COLUMN column_name data_type Modify column data type ALTER TABLE table_name DROP COLUMN column_name Delete column ALTER TABLE table_name RENAME COLUMN old_column_name TO new_column_

Statements to modify table structure in sql

Statements to modify table structure in SQL

Modifying table structure is a common operation in SQL, which allows you to Change a table's columns, data types, and constraints. The following are some commonly used statements:

1. Add columns

ALTER TABLE table_name ADD column_name data_type

For example:

<code>ALTER TABLE employees ADD salary INT</code>
Copy after login

2. Modify columns

ALTER TABLE table_name ALTER COLUMN column_name data_type

For example:

<code>ALTER TABLE employees ALTER COLUMN salary DECIMAL(10,2)</code>
Copy after login

3. Delete column

ALTER TABLE table_name DROP COLUMN column_name

For example:

<code>ALTER TABLE employees DROP COLUMN bonus</code>
Copy after login

4. Change column Name

ALTER TABLE table_name RENAME COLUMN old_column_name TO new_column_name

For example:

<code>ALTER TABLE employees RENAME COLUMN first_name TO name</code>
Copy after login

5. Add constraints

Primary key:

##ALTER TABLE table_name ADD PRIMARY KEY (column_name)

For example:

<code>ALTER TABLE employees ADD PRIMARY KEY (employee_id)</code>
Copy after login

Foreign key:

ALTER TABLE table_name ADD FOREIGN KEY (column_name) REFERENCES referenced_table(column_name)

For example:

<code>ALTER TABLE orders ADD FOREIGN KEY (customer_id) REFERENCES customers(customer_id)</code>
Copy after login

Unique constraints:

ALTER TABLE table_name ADD UNIQUE (column_name)

For example:

<code>ALTER TABLE employees ADD UNIQUE (email)</code>
Copy after login

6. Delete constraints

Primary key:

ALTER TABLE table_name DROP PRIMARY KEY

Foreign key:

ALTER TABLE table_name DROP FOREIGN KEY column_name

Unique constraint:

ALTER TABLE table_name DROP INDEX index_name (where index_name is the name of the unique constraint)

The above is the detailed content of Statements to modify table structure in sql. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!