ALTER TABLE
Introduction to SQL
Database
SQL Basics
Creating a Database
Using a Database
Creating a Table
Common Data Types
Inserting Data
Selecting Data
WHERE Clause
Comparison Operators
AND, OR, and NOT
ORDER BY Clause
LIMIT Clause
DISTINCT
LIKE Operator
IN, BETWEEN, and IS NULL
Updating Data
Deleting Data
ALTER TABLE
DROP TABLE
PRIMARY KEY and NOT NULL
FOREIGN KEY and Relationships
Aggregate Functions
GROUP BY Clause
HAVING Clause
JOIN Basics
INNER JOIN
LEFT JOIN
Aliases
Subqueries
Indexes
User Permissions and Security
Common Mistakes Beginners Make
Practice Ideas
ALTER TABLE
Altering a Table
Definition: The ALTER TABLE statement is used to add, delete, or modify columns in an existing table. It allows you to change the structure of your database without having to delete and recreate the entire table.
Why: Requirements for software projects often change over time. Adding a new column to an existing table is considered a core database operation, as it allows your data structure to grow and adapt alongside your application.
Syntax: Adding a Column
To add a new category of data to your table, you use the ADD keyword followed by the new column name and its data type.
ALTER TABLE table_name ADD column_name datatype;
Example: Adding Student Marks
If you decide you now need to track exam scores in your students table, you can add a marks column like this:
ALTER TABLE students ADD marks INT;
Explanation
- Structural Change: This command changes the blueprint of the table. Every existing row in the table will now have a new "marks" field.
- Existing Data: When you add a new column to a table that already has data, the new column will initially be filled with
NULL(empty) values for all existing rows.
Other Common ALTER Operations
| Action | Syntax Example |
|---|---|
| Drop a Column | ALTER TABLE students DROP COLUMN city; |
| Modify Datatype | ALTER TABLE students MODIFY COLUMN name VARCHAR(100); |
Key Notes
- Data Loss Warning: Using
DROP COLUMNwill permanently delete all data stored in that column. Always back up your data before making structural changes. - Constraints: You can also use
ALTER TABLEto add constraints likeUNIQUEorPRIMARY KEYto columns that were created previously. - Performance: On extremely large tables (millions of rows), altering a table can take some time as the database needs to rewrite the underlying file structure.
🏋️ Test Yourself With Exercises
Take our quiz on ALTER TABLE to test your knowledge.
Browse Quizzes »