1. Home
SQL

SQL Tutorial: Learn Structured Query Language Basics

Learn all SQL tutorial concepts in detail and master your career today.

  • 59
  • 9 Hours
right-top-arrow

Tutorial Playlist

81 Lessons
81

ALTER Command in SQL

Updated on 22/07/2024477 Views

SQL serves as the backbone for managing relational databases, offering a rich set of commands to manipulate and query data. Among these commands, the ALTER command in SQL is a powerful tool for making structural changes to the database schema. From adding and modifying columns to altering indexes and triggers, This empowers database administrators and developers to adapt databases to evolving requirements seamlessly.

In this guide, we delve into the intricacies of the ALTER command in SQL, exploring its syntax, types of alterations, practical examples, best practices, and considerations. Whether you're a seasoned database professional wanting to enhance your skills or a beginner looking to unlock the potential of database management, this comprehensive exploration of the ALTER command will equip you with the knowledge and confidence to wield SQL effectively in your projects.

Overview

ALTER command in SQL is a vital tool in the arsenal of any database administrator or developer. It enables the modification of database structures with precision and flexibility, allowing for seamless adaptation to changing requirements.

In this comprehensive exploration, we will delve into the various facets of it.By the end of this guide, you will have gained a comprehensive understanding of the ALTER command in SQL, empowering you to wield this powerful tool with proficiency and finesse in your database management endeavors.

Whether you're a seasoned professional or a newcomer to the world of SQL, this exploration promises to build your skills and deepen your appreciation for the art of database manipulation.

Syntax of ALTER command

A. Basic syntax:The basic syntax of the ALTER command / ALTER SYNTAX in SQL / alter table syntax in SQL varies slightly depending on the specific alteration being performed. However, the general structure follows a similar pattern:

ALTER object_type object_name

action;

Where:

  • object_type: Specifies the type of database object being altered, such as TABLE, DATABASE, INDEX, VIEW, or TRIGGER.
  • object_name: The name of the object being altered.
  • action: Describes the alteration being performed, which could include adding, modifying, dropping, or renaming components of the object.Let's illustrate the basic syntax with an example of adding a column to an existing table:

-- Adding a column to the 'employees' tableALTER TABLE employeesADD COLUMN birth_date DATE;

This SQL statement adds a new column named 'birth_date' of type DATE to the 'employees' table.B. Examples of syntax variations for different alterations:The ALTER command offers various syntax variations to accommodate different types of alterations. Here are some examples:1. Modifying a column's data type (ALTER MODIFY command in SQL):

-- Modifying the data type of the 'salary' column in the 'employees' table

ALTER TABLE employees

MODIFY COLUMN salary DECIMAL(10,2);

2. Dropping a column:

-- Dropping the 'address' column from the 'employees' table

ALTER TABLE employees

DROP COLUMN address;

3. Renaming a table:

-- Renaming the 'old_table' to 'new_table'

ALTER TABLE old_table

RENAME TO new_table;

4. Adding an index:

-- Adding an index named 'idx_lastname' on the 'lastname' column of the 'employees' table

ALTER TABLE employees

ADD INDEX idx_lastname (lastname);

5. Modifying a trigger:

-- Modifying the trigger named 'trg_update_salary' to change its action

ALTER TRIGGER trg_update_salary

UPDATE OF salary;

These examples showcase the versatility of the ALTER command, allowing for a wide range of alterations to database objects with precision and ease.

Types of alterations using the ALTER command

A. Table alterations:

1. Adding columns: Adding a column to an existing table is a common operation in database management. You can be achieve this by using ALTER TABLE statement with ADD COLUMN clause. Let's illustrate this with an example of "alter table add column SQL Server":

-- Adding a new column named 'email' to the 'employees' table

ALTER TABLE employees

ADD COLUMN email VARCHAR(100);

This SQL statement adds a new column named 'email' with a VARCHAR data type and almost 100 characters to the 'employees' table. This is an example of an ALTER TABLE command in SQL.

2. Modifying columns: Modifying the properties of an existing column, such as its data type or constraints, is another important aspect of table alteration. This can be done using the MODIFY COLUMN clause within the ALTER TABLE statement. Here's an example:

-- Modifying the data type of the 'salary' column in the 'employees' table

ALTER TABLE employees

MODIFY COLUMN salary DECIMAL(10,2);

This SQL statement modifies the data type of the 'salary' column in the 'employees' table to DECIMAL, with precision of 10 and scale of 2. This is an example of the MODIFY SQL command or ALTER TABLE modify column.

3. Dropping columns: Removing unnecessary columns from a table helps streamline the database structure. ALTER TABLE statement with DROP COLUMN clause facilitates this operation. Example:

-- Dropping the 'address' column from the 'employees' table

ALTER TABLE employees

DROP COLUMN address;

This SQL statement removes the 'address' column from the 'employees' table.

4. Renaming columns:Renaming a column provides a way to improve clarity or adhere to naming conventions. This can be accomplished using the RENAME COLUMN clause within the ALTER TABLE statement. Example:

-- Renaming the 'old_column' to 'new_column' in the 'employees' table

ALTER TABLE employees

RENAME COLUMN old_column TO new_column;

This SQL statement renames the 'old_column' to 'new_column' in the 'employees' table.

5. Adding constraints:Constraints ensure data integrity by enforcing rules on the values stored in a column. The ALTER TABLE statement with the ADD CONSTRAINT clause allows for the addition of constraints to existing tables. Example:

-- Adding a NOT NULL constraint to the 'email' column in the 'employees' table

ALTER TABLE employees

MODIFY COLUMN email VARCHAR(100) NOT NULL;

This SQL statement adds a NOT NULL constraint to the 'email' column in the 'employees' table, ensuring that it cannot contain NULL values.

6. Dropping constraints:Removing constraints from a table can be necessary to relax data validation rules or accommodate changing requirements. The ALTER TABLE statement with the DROP CONSTRAINT clause facilitates this operation. Example:

-- Dropping the UNIQUE constraint named 'uk_email' from the 'employees' table

ALTER TABLE employees

DROP CONSTRAINT uk_email;

This SQL statement removes the UNIQUE constraint named 'uk_email' from the 'employees' table.

7. Renaming tables:Renaming a table provides a straightforward way to update its name without altering its structure or data. This can be achieved using the RENAME TO clause within the ALTER TABLE statement. Example:

-- Renaming the 'old_table' to 'new_table'

ALTER TABLE old_table

RENAME TO new_table;

This SQL statement renames the 'old_table' to 'new_table'.

B. Database alterations:

1. Modifying database schema:Modifying the schema of a database involves changes to its overall structure, such as adding or removing tables, altering table relationships, or adjusting database options. This can be accomplished using various SQL commands, including ALTER DATABASE. Example:

-- Modifying the character set of the 'sample_database' to UTF-8

ALTER DATABASE sample_database

CHARACTER SET utf8;

This SQL statement modifies the character set of the 'sample_database' to UTF-8, ensuring compatibility with a wider range of languages and characters.

2. Changing database options:Altering database options allows for customization of its behavior and settings. The ALTER DATABASE statement with appropriate clauses enables changes to options such as collation, encryption, or storage engine. Example:

-- Changing the collation of the 'sample_database' to case-insensitive

ALTER DATABASE sample_database

COLLATE utf8_general_ci;

This SQL statement changes the collation of the 'sample_database' to utf8_general_ci, making string comparisons case-insensitive within the database.

C. Index alterations:

1. Adding indexes:Indexes improve query performance by facilitating faster data retrieval based on specific columns. The ALTER TABLE statement with the ADD INDEX clause allows for the addition of indexes to existing tables. Example:

-- Adding an index named 'idx_lastname' on the 'lastname' column of the 'employees' table

ALTER TABLE employees

ADD INDEX idx_lastname (lastname);

This SQL statement adds an index named 'idx_lastname' on the 'lastname' column of the 'employees' table, speeding up queries that involve searching or sorting by last name.

2. Dropping indexes:Removing unnecessary indexes from a table can improve write performance and reduce storage overhead. The ALTER TABLE statement with the DROP INDEX clause facilitates the removal of indexes. Example:

-- Dropping the index named 'idx_lastname' from the 'employees' table

ALTER TABLE employees

DROP INDEX idx_lastname;

This SQL statement removes the index named 'idx_lastname' from the 'employees' table.

3. Modifying indexes:Modifying existing indexes allows for adjustments to their properties or scope. The ALTER TABLE statement with the MODIFY INDEX clause enables modifications to index definitions. Example:

-- Modifying the type of the index named 'idx_lastname' on the 'employees' table to UNIQUE

ALTER TABLE employees

MODIFY INDEX idx_lastname UNIQUE;

This SQL statement modifies the index named 'idx_lastname' on the 'employees' table to be UNIQUE, ensuring that values in the indexed column are unique.

D. View alterations:

1. Modifying view definitions:Views provide virtual representations of data stored in tables, allowing for simplified querying and data manipulation. Modifying view definitions involves adjusting the underlying SQL query to reflect changes in requirements or data sources. This can be achieved using the CREATE OR REPLACE VIEW statement. Example:

-- Modifying the definition of the 'customer_view' to include additional columns

CREATE OR REPLACE VIEW customer_view AS

SELECT customer_id, first_name, last_name, email

FROM customers;

This SQL statement modifies the definition of the 'customer_view' to include additional columns from the 'customers' table.

2. Dropping views:Removing unnecessary views from the database streamlines its structure and improves manageability. The DROP VIEW statement enables the deletion of views. Example:

-- Dropping the 'customer_view' from the database

DROP VIEW customer_view;

This SQL statement removes the 'customer_view' from the database.

E. Trigger alterations:

1. Adding triggers:Triggers are database objects that automatically execute in response to specified events, such as INSERT, UPDATE, or DELETE operations on tables. Adding triggers involves defining their behavior and associating them with specific tables and events. This can be done using the CREATE TRIGGER statement. Example:

-- Adding a trigger named 'trg_update_salary' to update the 'last_updated' column

CREATE TRIGGER trg_update_salary

AFTER UPDATE ON employees

FOR EACH ROW

SET last_updated = CURRENT_TIMESTAMP;

This SQL statement adds a trigger named 'trg_update_salary' to the 'employees' table, which updates the 'last_updated' column with the current timestamp after each UPDATE operation on the table.

2. Modifying triggers:Modifying existing triggers allows for adjustments to their behavior or associated events. You can be achieve this by using the ALTER TRIGGER statement. Example:

-- Modifying the action of the trigger named 'trg_update_salary' to include logging

ALTER TRIGGER trg_update_salary

AFTER UPDATE ON employees

FOR EACH ROW

BEGIN

-- Log the salary update to the 'salary_log' table

INSERT INTO salary_log (employee_id, old_salary, new_salary, updated_at)

VALUES (OLD.employee_id, OLD.salary, NEW.salary, CURRENT_TIMESTAMP);

END;

This SQL statement modifies the action of the 'trg_update_salary' trigger to include logging salary updates to a separate 'salary_log' table.

3. Dropping triggers:Removing triggers from the database can be necessary to eliminate unnecessary or obsolete functionality. The DROP TRIGGER statement facilitates the deletion of triggers. Example:

-- Dropping the trigger named 'trg_update_salary' from the 'employees' table

DROP TRIGGER trg_update_salary;

This SQL statement removes the 'trg_update_salary' trigger from the 'employees' table.

ALTER command for modifying table constraints

Using the ALTER command in SQL to modify table constraints is a fundamental aspect of database schema management. This command allows you to make changes to the structure of existing database objects, including adding, dropping, or altering constraints like primary keys, foreign keys, or unique constraints. Let's delve into a brief discussion on how the ALTER command facilitates these modifications:

1. Adding Constraints:

- To add a constraint using ALTER, you specify the constraint type (e.g., PRIMARY KEY, FOREIGN KEY, UNIQUE) followed by the column(s) to which the constraint applies.

- For example, like adding a primary key constraint to an existing table:

ALTER TABLE table_name

ADD CONSTRAINT pk_constraint_name PRIMARY KEY (column_name);

2. Dropping Constraints:

- Similarly, if you need to remove a constraint, you can use ALTER with the DROP CONSTRAINT clause.

- For instance, to drop a primary key constraint:

ALTER TABLE table_name

DROP CONSTRAINT pk_constraint_name;

3. Modifying Constraints:

- While certain database systems might allow direct modification of constraints using ALTER, in many cases, you may need to drop and recreate the constraint.

- For instance, to modify the definition of a primary key (e.g., add another column), you might first drop the existing primary key constraint and then add a new one.

4. Handling Foreign Key Constraints:

- Foreign key constraints are crucial for maintaining referential integrity between tables. You can use ALTER to add or drop foreign key constraints.

- For instance, to add a foreign key constraint:

ALTER TABLE child_table

ADD CONSTRAINT fk_constraint_name

FOREIGN KEY (child_column)

REFERENCES parent_table(parent_column);

5. Checking Existing Constraints:

- Before altering constraints, it's essential to check the existing constraints to avoid conflicts or errors.

- You can query system tables or views specific to your database management system to retrieve information about existing constraints.

Conclusion

Finally, the ALTER command in SQL stands as a cornerstone of database management, offering a versatile toolkit for modifying table structures, database schemas, indexes, views, and triggers. Through the diverse range of alterations it enables, SQL developers and administrators can adapt databases to evolving requirements, optimize performance, and ensure data integrity.

In conclusion, it represents not just a set of syntax rules but a gateway to dynamic and responsive database management. Its flexibility and breadth of capabilities make it an indispensable tool in the SQL developer's toolkit, facilitating efficient and effective management of relational databases.

FAQs

1. What is the ALTER command in SQL?

A. It is used to make changes to the structure of existing database objects, such as tables, indexes, views, or triggers. It allows for modifications like adding, modifying, or dropping columns, as well as adding or dropping constraints.

2. Is ALTER command a DDL or DML?

A. It is a part of the Data Definition Language (DDL).

3. What is the ALTER and DELETE command in SQL?

A. It modifies the structure of existing database objects like tables, indexes, or views. The DELETE command in SQL removes records from a table based on specified conditions.

4. How do I add a new column to an existing table using ALTER?

A. You can use the following syntax:

ALTER TABLE table_name

ADD COLUMN column_name datatype;

Replace 'table_name' with the name of the existing table to which you want to add the column. Replace 'column_name' with the name of the new column and 'datatype' with the data type of the new column.

5. Can I rename a table using ALTER?

A. Yes, you can rename a table using the ALTER command. The syntax typically varies depending on the database system you are using, but here's a general example:

ALTER TABLE old_table_name

RENAME TO new_table_name;

Replace 'old_table_name' with the current name of the table you want to rename and 'new_table_name' with the new desired name for the table.

image

Devesh

Passionate about Transforming Data into Actionable Insights through Analytics, with over 3+ years of experience working in Data Analytics, Data V…Read More

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...