본문 바로가기
Database/PostgreSQL

[PostgreSQL] ALTER TABLE RENAME COLUMN IF EXISTS

by pcm9881 2023. 9. 4.

PostgreSQL에서 존재할 경우에 실행하기 위해 IF EXISTS를 사용하는데 

 

RENAME COLUMN에 경우 IF EXISTS를 지원하지 않는다. 

 

그래서 DO문법을 활용해서 비슷하게 동작하게 만들 수 있습니다.

 

DO $$
    BEGIN
      IF EXISTS(SELECT *
        FROM information_schema.columns
        WHERE table_name='테이블명' and column_name='존재 체크할 컬럼명')
      THEN
    ALTER TABLE "public"."테이블명" RENAME COLUMN "존재 체크할 컬럼명" TO "변경할 컬럼명";
    END IF;
END $$;

 

References

[postgresql tutorial]: https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-rename-column/

 

PostgreSQL RENAME COLUMN: Renaming One or More Columns of a Table

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

www.postgresqltutorial.com

 

728x90

댓글