SQL Tutorial
SQL Clauses / Operators
SQL-Injection
SQL Functions
SQL Queries
PL/SQL
MySQL
SQL Server
Misc
The ALTER
statement in SQL is used to modify the structure of an existing table. With this statement, you can perform various operations, including adding new columns, modifying existing columns, or deleting columns. The specific syntax might slightly vary based on the database system you're using, but the general concepts remain consistent.
You can use the ADD
clause with the ALTER
statement to add new columns to a table.
Syntax:
ALTER TABLE table_name ADD column_name datatype;
Example:
To add a new column named email
of type VARCHAR(100)
to an employees
table:
ALTER TABLE employees ADD email VARCHAR(100);
The DROP
clause allows you to remove a column from a table.
Syntax:
ALTER TABLE table_name DROP COLUMN column_name;
Example:
To remove the email
column from the employees
table:
ALTER TABLE employees DROP COLUMN email;
Note: Dropping a column will permanently remove that column and all the data stored in it.
The MODIFY
clause (or ALTER COLUMN
in some databases) is used to change the datatype or size of an existing column.
Syntax (for databases like Oracle):
ALTER TABLE table_name MODIFY column_name new_datatype;
Syntax (for databases like SQL Server):
ALTER TABLE table_name ALTER COLUMN column_name new_datatype;
Example:
To modify the data type of the email
column in the employees
table to VARCHAR(200)
:
Oracle:
ALTER TABLE employees MODIFY email VARCHAR(200);
SQL Server:
ALTER TABLE employees ALTER COLUMN email VARCHAR(200);
Lastly, since SQL syntax can vary across different database systems, it's a good practice to consult the documentation for your specific database when using the ALTER
statement.
Dropping columns with ALTER TABLE in SQL:
ALTER TABLE
to drop columns.ALTER TABLE your_table DROP COLUMN column_to_drop;
Modifying column datatype using ALTER TABLE in SQL:
ALTER TABLE your_table MODIFY column_name new_datatype;
Adding constraints with ALTER TABLE in SQL:
ALTER TABLE
.ALTER TABLE your_table ADD CONSTRAINT constraint_name CHECK (column_name > 0);
How to add a primary key using ALTER TABLE in SQL:
ALTER TABLE your_table ADD PRIMARY KEY (column_name);
Dropping indexes with ALTER TABLE in SQL:
ALTER TABLE
.ALTER TABLE your_table DROP INDEX index_name;
Changing column properties with ALTER TABLE in SQL:
ALTER TABLE your_table ALTER COLUMN column_name SET DEFAULT default_value;
SQL ALTER TABLE MODIFY column example:
ALTER TABLE your_table MODIFY column_name new_datatype;
Renaming columns using ALTER TABLE in SQL:
ALTER TABLE your_table RENAME COLUMN old_column_name TO new_column_name;