Add new column in sql
To add a new column in SQL, you can use the ALTER TABLE
statement with the ADD COLUMN
clause. The syntax is as follows:
ALTER TABLE table_name
ADD COLUMN new_column_name data_type;
Here:
table_name
is the name of the table you want to modify.new_column_name
is the name of the new column you want to add.data_type
is the data type of the new column (e.g.INT
,VARCHAR
,DATE
, etc.).
For example, to add a new column called age
with a data type of INT
to a table called employees
, you would use the following SQL statement:
ALTER TABLE employees
ADD COLUMN age INT;
This will add a new column called age
with a data type of INT
to the employees
table.
You can also specify additional options, such as:
NULL
orNOT NULL
to specify whether the column can contain null values.DEFAULT
to specify a default value for the column.UNIQUE
orPRIMARY KEY
to specify that the column is unique or a primary key.
For example:
ALTER TABLE employees
ADD COLUMN age INT NOT NULL DEFAULT 0;
This will add a new column called age
with a data type of INT
, not null, and a default value of 0.
Note that you can only add a new column to a table that is not currently being used by a query or transaction. If you try to add a new column to a table that is being used, you will get an error.
Also, some databases like MySQL, PostgreSQL, and SQLite support adding a new column with a default value using the ALTER TABLE
statement with the ADD COLUMN
clause, but some databases like Oracle and Microsoft SQL Server require you to use the ALTER TABLE
statement with the MODIFY
clause instead.