Adding a new column to an exisiting tbale sql
To add a new column to an existing table in SQL, you can use the ALTER TABLE
statement. The basic syntax is:
ALTER TABLE table_name
ADD COLUMN new_column_name data_type;
Here:
table_name
is the name of the existing 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, let's say you have a table called employees
with the following columns:
+----+----------+--------+
| id | name | salary |
+----+----------+--------+
| 1 | John | 50000 |
| 2 | Jane | 60000 |
| 3 | Joe | 70000 |
+----+----------+--------+
You want to add a new column called department
with a data type of VARCHAR(50)
. You can use the following SQL statement:
ALTER TABLE employees
ADD COLUMN department VARCHAR(50);
After running this statement, the employees
table will have the new column:
+----+----------+--------+--------------+
| id | name | salary | department |
+----+----------+--------+--------------+
| 1 | John | 50000 | Sales |
| 2 | Jane | 60000 | Marketing |
| 3 | Joe | 70000 | IT |
+----+----------+--------+--------------+
Note that you can also specify additional options when adding a new column, such as:
DEFAULT
value: sets a default value for the new column.NULL
orNOT NULL
: specifies whether the new column can contain null values.UNIQUE
orPRIMARY KEY
: specifies whether the new column is unique or a primary key.
For example:
ALTER TABLE employees
ADD COLUMN department VARCHAR(50) DEFAULT 'Unknown';
This would set the default value of the department
column to 'Unknown'
for any new rows inserted into the table.