기술공부/DB

[PostgreSQL] Insert 쿼리에서 Serial 컬럼 값 삽입하기

봉두두 2023. 8. 22. 18:10
728x90

일반적으로 Auto Increment column일 경우 컬럼값이 자동증가하게 되는데

Insert query를 활용하려고 할 때 귀찮아지는 경우가 있다.

INSERT INTO tmptable(column1, column2, ....) values(value1, value2, ...);

 

이런 귀찮은 상황을 모면하게 해 줄 방법 중 신박한 방법을 알게 되어 포스팅으로 기록하려고 한다.

 

아래와 같이 해주면 되는건 알고있었지만,

INSERT INTO problem VALUES (
   nextval('problem_id_seq'), 
   'Hello World',
   'unknown', 
   '/var/www/files/problems/' || lastval(), 
   'Python'
);

이는 sequance 명을 넣어주어야 해서 이 나름대로 또 귀찮음.

 

그런데

이 대신 default를 넣어도 되는줄은 몰랐다.

INSERT INTO problem VALUES (
   DEFAULT, 
   'Hello World',
   'unknown', 
   '/var/www/files/problems/' || lastval(), 
   'Python'
);

 

완전 간편... 앞으로는 요걸 써야지.

 

 

[출처] https://stackoverflow.com/questions/25445319/insert-into-a-table-with-a-serial-field-and-using-its-future-value

728x90
728x90