Wednesday, December 18, 2024

SQL ADD Keyword

 The ADD keyword in SQL is used to add a new column to an existing table or to add constraints to a column in an existing table. It is used in the ALTER TABLE statement.

Here are two common uses:

1. Adding a New Column:

ALTER TABLE table_name
ADD column_name column_definition;
  • table_name: The name of the table to which you want to add a column.
  • column_name: The name of the new column.
  • column_definition: The definition of the column (data type, constraints, etc.).

Example:

ALTER TABLE employees
ADD email VARCHAR(255);

This adds a new column email of type VARCHAR(255) to the employees table.

2. Adding Constraints:

You can also use the ADD keyword to add constraints like PRIMARY KEY, FOREIGN KEY, UNIQUE, etc.

ALTER TABLE table_name
ADD CONSTRAINT constraint_name constraint_type (column_name);

Example:

ALTER TABLE employees
ADD CONSTRAINT pk_employee_id PRIMARY KEY (employee_id);

This adds a primary key constraint on the employee_id column in the employees table.

3. Adding Multiple Columns:

You can add multiple columns in a single ALTER TABLE statement.

ALTER TABLE table_name
ADD column1_name column1_definition,
    column2_name column2_definition;

Example:

ALTER TABLE employees
ADD phone_number VARCHAR(20),
    hire_date DATE;

This adds two new columns (phone_number and hire_date) to the employees table.

No comments:

Post a Comment