How to change a table name using an SQL query?
How can you change the name of a table using an SQL query? What is the correct syntax to rename a table in different SQL databases?
Renaming a table in SQL is a common task when you want to update your database schema without losing data. Most SQL databases provide a straightforward way to change a table name using a specific query.
Basic Syntax to Rename a Table:
The most widely supported command is:
ALTER TABLE old_table_name RENAME TO new_table_name;
- This works in many SQL databases such as PostgreSQL, SQLite, and Oracle.
- It changes the table name while keeping all the data, indexes, and constraints intact.
Examples:
ALTER TABLE employees RENAME TO staff;
This renames the employees table to staff.
Database-specific Notes:
MySQL:
MySQL uses a different syntax:
RENAME TABLE old_table_name TO new_table_name;
Or you can use ALTER TABLE in newer versions:
ALTER TABLE old_table_name RENAME new_table_name;
SQL Server:
SQL Server doesn’t have a simple rename command. Instead, you use:
EXEC sp_rename 'old_table_name', 'new_table_name';
Things to Keep in Mind:
- Make sure no other database objects (like foreign keys or views) depend on the old table name, or you may need to update them manually.
- Renaming a table doesn’t affect the data inside it.
- Always back up your database before making structural changes.
Summary:
Use ALTER TABLE ... RENAME TO ... in most SQL databases.
- Use RENAME TABLE in MySQL.
- Use sp_rename in SQL Server.
- Check dependencies to avoid breaking your schema.
Renaming tables can be done safely and efficiently with these commands depending on the SQL database you use!