📜  sql alter column - SQL (1)

📅  最后修改于: 2023-12-03 15:05:16.971000             🧑  作者: Mango

SQL ALTER COLUMN

SQL ALTER COLUMN is a command used to modify the structure of an existing column in a table. This command can be used to change the data type, size or other attributes of a column in a table.

Syntax

The basic syntax for ALTER COLUMN is as follows:

ALTER TABLE table_name
ALTER COLUMN column_name new_data_type [new_size] [new_attributes];

In the above syntax,

  • table_name: is the name of the table that contains the column to be modified.
  • column_name: is the name of the column that needs to be changed.
  • new_data_type: is the new data type to be assigned to the column.
  • new_size: is the new size of the column. This parameter is optional and is only used for certain data types like VARCHAR, CHAR or TEXT.
  • new_attributes: are the new attributes to be assigned to the column. This parameter is optional and is used to specify any additional constraints, defaults or rules for the column.
Example

Let us consider the following table customer:

CREATE TABLE customer (
  id INT,
  name VARCHAR(50),
  age INT,
  email VARCHAR(100),
  phone VARCHAR(20)
);

Suppose we want to modify the column email to have a maximum length of 150 characters, we can use the following command:

ALTER TABLE customer
ALTER COLUMN email VARCHAR(150);

Similarly, if we want to add a NOT NULL constraint to the column phone, we can use the following command:

ALTER TABLE customer
ALTER COLUMN phone VARCHAR(20) NOT NULL;
Conclusion

SQL ALTER COLUMN is a useful command that allows programmers to modify the structure of an existing column in a table. It is a powerful tool that can be used to change the data type, size, and other attributes of a column as required. By understanding how to use ALTER COLUMN, programmers can easily customize their database schema to meet their application requirements.