4

Description: I want to change column name and its data type. I have multiple columns and want to change all in one query along with their datatype.

What i tried

  1. Changing column type then renaming it.
ALTER TABLE customers  ALTER COLUMN phone TYPE numeric 
RENAME COLUMN phone TO contact_phone

and

ALTER TABLE customers  ALTER COLUMN phone TYPE numeric,
RENAME COLUMN phone TO contact_phone
  1. Changing multiple column type then renaming it.
ALTER TABLE customers  
  ALTER COLUMN phone TYPE numeric, 
  ALTER COLUMN address TYPE text, 
  RENAME COLUMN phone TO contact_phone,
  RENAME COLUMN address TO contact_address
  1. Tried to change all column data type then rename it
ALTER TABLE customers  
ALTER COLUMN phone TYPE numeric,ALTER COLUMN address TYPE text

and

ALTER TABLE customers 
 RENAME COLUMN phone TO contact_phone,RENAME COLUMN address TO contact_address

Issue: Each time I am getting an error in the RENAME clause which is SQL State : 42601

Can anyone tell me what is wrong with this query?

1 Answer 1

5

While you can change the data type of several columns in one ALTER TABLE statement, renaming a column can only be done one at a time. So you will have to use several ALTER TABLE statements.

I would recommend to run all statements in a single transaction, that way you have to acquire the ACCESS EXCLUSIVE lock only once.

Sign up to request clarification or add additional context in comments.

7 Comments

i tried this as well .. used two alter statements in first i changed datatypes and in second i renamed columns. but got issue in renaming. kindly look at third point in my question under what i tried heading
I see. I have adapted the answer.
i just tried in editor instead of query and i noticed i am getting error in renaming multiple column in one query. ALTER TABLE customers RENAME COLUMN phone TO contact_phone,RENAME COLUMN address TO contact_address RENAME multiple time is not acceptable by editor i think. i tried without putting comma before next RENAME clause still issue.
The tutorial is plain wrong. Look at the documentation instead.
Exactly! If you look at the syntax diagram for RENAME (of a column), you will see that there are no provisions for more than one such clause.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.