How to add new column to existing table in sql
To add a new column to an existing table in SQL, you can use the ALTER TABLE
statement. The syntax is as follows:
ALTER TABLE table_name
ADD column_name data_type;
Here:
table_name
is the name of the table you want to modify.column_name
is the name of the new column you want to add.data_type
is the data type of the new column.
For example, to add a new column named age
with a data type of int
to a table named employees
, you would use the following SQL statement:
ALTER TABLE employees
ADD age int;
If you want to add a column with a default value, you can use the following syntax:
ALTER TABLE table_name
ADD column_name data_type DEFAULT default_value;
For example, to add a new column named salary
with a data type of float
and a default value of 0.0
to a table named employees
, you would use the following SQL statement:
ALTER TABLE employees
ADD salary float DEFAULT 0.0;
If you want to add a column with a constraint, such as a primary key or foreign key, you can use the following syntax:
ALTER TABLE table_name
ADD column_name data_type PRIMARY KEY;
For example, to add a new column named employee_id
with a data type of int
and set it as the primary key to a table named employees
, you would use the following SQL statement:
ALTER TABLE employees
ADD employee_id int PRIMARY KEY;
Note that you can only add a column to the end of the table. If you want to add a column in a specific position, you can use the ADD COLUMN
statement with the AFTER
or BEFORE
clause.
For example, to add a new column named department
with a data type of varchar(50)
after the name
column in a table named employees
, you would use the following SQL statement:
ALTER TABLE employees
ADD COLUMN department varchar(50) AFTER name;
Similarly, to add a new column named job_title
with a data type of varchar(50)
before the name
column in a table named employees
, you would use the following SQL statement:
ALTER TABLE employees
ADD COLUMN job_title varchar(50) BEFORE name;
Remember to replace table_name
, column_name
, and data_type
with your actual table and column names, and default_value
with the default value you want to set for the column.