In SQL, the ALTER COLUMN keyword is used to modify the definition of an existing column in a table. This is typically used to change the column's data type, rename the column, or adjust other attributes such as its size, default value, or nullability.
Here’s the basic syntax for using ALTER COLUMN:
1. Change Data Type
ALTER TABLE table_name
ALTER COLUMN column_name TYPE new_data_type;
2. Rename a Column
ALTER TABLE table_name
RENAME COLUMN old_column_name TO new_column_name;
3. Set Default Value
ALTER TABLE table_name
ALTER COLUMN column_name SET DEFAULT default_value;
4. Remove Default Value
ALTER TABLE table_name
ALTER COLUMN column_name DROP DEFAULT;
5. Set or Remove Nullable Constraints
-- To allow null values
ALTER TABLE table_name
ALTER COLUMN column_name DROP NOT NULL;
-- To disallow null values
ALTER TABLE table_name
ALTER COLUMN column_name SET NOT NULL;
Example:
- Change data type:
ALTER TABLE employees
ALTER COLUMN salary TYPE DECIMAL(10, 2);
- Rename column:
ALTER TABLE employees
RENAME COLUMN address TO home_address;
- Set default value:
ALTER TABLE employees
ALTER COLUMN status SET DEFAULT 'Active';
Notes:
- Not all changes are supported in every SQL database. The syntax and behavior may vary slightly across different systems such as MySQL, PostgreSQL, or SQL Server.
- When altering column types or constraints, you may need to ensure that the existing data is compatible with the new definition.
Let me know if you need a specific example!
No comments:
Post a Comment