How To Rename Column Name In SQL?
![]()
It may often happen that, we see a requirement to change the name of the column in the database to serve their purpose. With the help of SQL or Structured Query Language, the Database Administrators store, update, manipulate, and retrieve data in relational databases. So, in this article let us understand how to rename a column name in SQL.
The following topics will be covered in this article:
- What is SQL?
- What is RENAME command in SQL?
- Rename column name in MySQL, MariaDB, Oracle, and PostgreSQL
- Rename column name in MS SQL Server
- Rename table name MySQL, MariaDB, Oracle
So let us get started then,
What is SQL?
SQL or most commonly known as SEQUEL is a Structured Query Language used for managing and accessing the databases. It is based on the English language and is designed in a way to easily retrieve, manipulate, and access the data. If you wish to know more about the basics of SQL in-depth, you can refer to the article on SQL Basics. In SQL, there are various statements/ commands used to manipulate data. One such manipulation, which is quite popular in databases is renaming the column name in SQL.
So, let us understand how to use the RENAME command in SQL.
What is RENAME command in SQL?
This command is used to change the name of a column to a new column name. It is also used to change the table to a new table name. Let us understand how to use this command in different databases. But, before that, let us consider the following table to understand all the examples:
How to Rename Column name in SQL?
Rename column name in MySQL, MariaDB, Oracle, and PostgreSQL
To rename a column name in MySQL, MariaDB, Oracle, and PostgreSQL, you can follow the below syntax:
Syntax
Example:
Write a query to rename the column name “BID” to “BooksID”.
On executing the above query, you will see the following output:
You can also use the CHANGE keyword to rename a column name as follows:
Syntax
Example:
Write a query to rename the column name “BID” to “BooksID”.
On executing this query, you will see the output the same as the above output.
Rename column name in MS SQL Server
The process of renaming column name is MS SQL Server is different when compared to the other databases. In MS SQL Server, you have to use the stored procedure called sp_rename.
Syntax
Example:
Write a query to rename the column name “BID” to “BooksID”.
The resulting output will be the same as that for the above queries. Now, that you have understood how to rename a column name in various databases, let us see how you can rename a table name.
Rename table name MySQL, MariaDB, Oracle
To rename a table name, you can use the RENAME command in SQL, in the following manner:
Syntax:
Example:
Now, if you execute the below query to see the details in the table ListOfBooks, you will see the following output:
Query:
Now with this, we come to an end of this comparison on SQL vs NoSQL. I hope you guys enjoyed this article and understood all the differences. If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.
Do look out for other articles in this series which will explain the various other aspects of SQL.
Псевдонимы
Также нам нужно разобраться с названиями колонок. А то у нас повторяются названия name и id, а ведь они содержат различные данные. С другой стороны, есть первая колонка id и колонка employee_id, которые содержат одни и те же данные.
Давай напишем запрос, где будут только нужные колонки, а также переименуем колонки с одинаковыми именами:
И результат такого запроса:
| task_id | task_desc | deadline | emploee_id | emp_name | emp_occupation |
|---|---|---|---|---|---|
| 1 | Исправить багу на фронтенде | 2022-06-01 | 1 | Иванов Иван | Программист |
| 2 | Исправить багу на бэкенде | 2022-06-15 | 2 | Петров Петр | Программист |
| 7 | Наслаждаться жизнью | (NULL) | 4 | Рабинович Мойша | Директор |
| 3 | Купить кофе | 2022-07-01 | 5 | Кириенко Анастасия | Офис-менеджер |
| 4 | Купить кофе | 2022-08-01 | 5 | Кириенко Анастасия | Офис-менеджер |
| 5 | Купить кофе | 2022-09-01 | 5 | Кириенко Анастасия | Офис-менеджер |
| 8 | Наслаждаться жизнью | (NULL) | 6 | Васька | кот |
Отлично, проблема с непонятными названиями колонок успешно решена. Запрос стал немного длинноватым, зато в результирующей таблице все понятно. И никаких лишних колонок.
Алиасы таблиц
Иногда названия таблиц бывают слишком длинными и занимают много места в запросе. Поэтому создатели SQL для повышения читабельности, как и в случае с колонками, предложили возможность указывать алиасы таблиц.
Общий вид алиасов (псевдонимов таблиц) такой:
Давай перепишем наш предыдущий запрос с использованием коротких псевдонимов:
Читабельность немного снизилось, но это потому, что названия таблиц изначально были простыми и понятными. Может ведь быть и так:
А в этом случае алиасы уже полезны, да? 😉
Первичный ключ
И еще одна важная информация про таблицы. Помните, что у нас в таблице task была колонка employee_id? С ее помощью мы ссылались на ID сотрудника из таблицы employee.
Если мы хотим ссылаться из одной таблицы на строки другой таблицы, то таблица, на которую ссылаются, должна иметь колонку с ID, которую еще называют первичным ключом — PRIMARY KEY .
Чаще всего это специально добавленная колонка, тип значений которой — int . При добавлении записей в таблицу SQL автоматически устанавливает значение этой колонки.
На эти ключи потом много чего завязывается:
- связывание разных таблиц друг с другом;
- быстрой поиск и фильтрация по id;
- целостность данных в базе данных (нет ссылок на несуществующие id);
- удаление данных, на которые никто не ссылается;
- и многое многое другое.
Кстати, бывают ситуации, когда у таблицы есть так называемый натуральный ключ. Это когда есть колонка, содержимое которой подразумевает уникальность. Например, мы решили в таблицу сотрудников добавить:
- Порядок их прихода в компанию;
- Налоговый номер;
- Номер и серию паспорта.
Иногда проектировщики баз данных используют натуральный ключ в качестве первичного ключа, но чаще всего их используют раздельно. Записи ведь можно удалять, изменять и тому подобное.
Читали небось истории в интернете, когда на человека приставы вешают долги его полного тезки? Это как раз связано с понятием уникального ключа. Банкам и приставам очень удобно искать человека по ФИО и году рождения. И в 99% случаев этого достаточно для того, чтобы идентифицировать человека.
SQL Псевдонимы
SQL псевдонимы используются для временного переименования таблицы или заголовок столбца.
Псевдонимы SQL
SQL псевдонимы используются для получения таблицы базы данных или столбец в таблице, временное имя.
В основном создаются псевдонимы, чтобы имена столбцов более удобным для чтения.
SQL Алиас Синтаксис для столбцов
SQL Синтаксис Алиас для таблиц
Демо-версия базы данных
В этом уроке мы будем использовать хорошо известную базу данных Борей.
Ниже приводится подборка из "Customers" таблицы:
| CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
|---|---|---|---|---|---|---|
| 2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitucion 2222 | Mexico D.F. | 05021 | Mexico |
| 3 | Antonio Moreno Taqueria | Antonio Moreno | Mataderos 2312 | Mexico D.F. | 05023 | Mexico |
| 4 | Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
И выбор из "Orders" таблицы:
| OrderID | CustomerID | EmployeeID | OrderDate | ShipperID |
|---|---|---|---|---|
| 10354 | 58 | 8 | 1996-11-14 | 3 |
| 10355 | 4 | 6 | 1996-11-15 | 1 |
| 10356 | 86 | 6 | 1996-11-18 | 2 |
Алиас Пример для столбцов таблицы
Следующий SQL оператор задает два псевдонима, один для столбца CustomerName и один для столбца ContactName. Совет: Это требует двойные кавычки или квадратные скобки , если имя столбца содержит пробелы:
пример
В следующем операторе SQL мы объединим четыре столбца (Address, City, PostalCode и Country ) и создать псевдоним с именем "Address" :
пример
Примечание: Чтобы получить заявление SQL выше , чтобы работать в MySQL использовать следующее:
Алиас Пример для таблиц
Следующий SQL — оператор выбирает все заказы от клиента с CustomerID=4 (вокруг Horn ). Мы используем "Customers" и "Orders" таблицы, и дать им таблицы псевдонимов "c" и "o" соответственно (Здесь мы использовали псевдонимы , чтобы сделать SQL короче):
PostgreSQL RENAME COLUMN: Renaming a column

Summary: in this tutorial, you will learn how to use the PostgreSQL RENAME COLUMN clause in the ALTER TABLE statement to rename one or more columns of a table.
Introduction to PostgreSQL RENAME COLUMN clause
To rename a column of a table, you use the ALTER TABLE statement with RENAME COLUMN clause as follows:
In this statement:
- First, specify the name of the table that contains the column which you want to rename after the ALTER TABLE clause.
- Second, provide name of the column that you want to rename after the RENAME COLUMN keywords.
- Third, specify the new name for the column after the TO keyword.
The COLUMN keyword in the statement is optional therefore you can omit it like this:
For some reason, if you try to rename a column that does not exist, PostgreSQL will issue an error. Unfortunately that PostgreSQL does not provide the IF EXISTS option for the RENAME clause.
To rename multiple columns, you need to execute the ALTER TABLE RENAME COLUMN statement multiple times, one column at a time:
If you rename a column referenced by other database objects such as views, foreign key constraints, triggers, and stored procedures, PostgreSQL will automatically change the column name in the dependent objects.
PostgreSQL RENAME COLUMN examples
Let’s take some examples of using the ALTER TABLE RENAME COLUMN to get a better understanding.
Setting the sample tables
First, create two new tables customers and customer_groups .
Then, create a new view named customer_data based on the customers and customer_groups tables.
1) Using RENAME COLUMN to rename one column example
The following statement uses the ALTER TABLE RENAME COLUMN statement to rename the email column of the customers table to contact_email :
2) Using RENAME COLUMN to rename a column that has dependent objects example
This example uses the ALTER TABLE RENAME COLUMN statement to rename the name column of the customer_groups table to group_name . The name column is used in the customer_data view.
Now, you can check whether the change of the name column was cascaded to the customer_data view:
As you can see in the view definition, the name column has been changed to group_name .
3) Using multiple RENAME COLUMN to rename multiple columns example
These statements rename two columns name and phone of the customers table to customer_name and contact_phone respectively:
In this tutorial, you have learned how to use the PostgreSQL RENAME COLUMN clause in the ALTER TABLE statement to rename a column.