LoginSignup
9
7

More than 5 years have passed since last update.

テーブルに連番の値をINSERTする方法

Last updated at Posted at 2016-03-27

再帰ありのWITH句で実現できます。
テスト用テーブルの作成などに便利です。

コード

create_table.sql
create table A (
 id bigint,
 name text,
 primary key(id)
 );
insert_data.sql
/* 1~100の連番テーブル */
 WITH RECURSIVE serical_table(n) AS /* 変数n */
(
 SELECT 1 /* 初期値1 */
 UNION ALL
 SELECT n + 1 FROM serical_table
 WHERE n < 100 /* n+1なので条件に100を含まない */
)
INSERT INTO A(id, name)
  SELECT n, 'test'||n 
  FROM serical_table
 ;

感想

今まではExcelを使って、以下のようにデータを作っていました。
1. オートフィルで連番の列を作成
2. INSERT文を文字列結合で生成
でも、単純な連番データならこっちの方が便利です。

もう少し複雑な場合は、ストアドプロシージャでのループの方が便利かもしれませんね。

参考サイト

https://www.postgresql.jp/document/9.5/html/queries-with.html
http://kagamihoge.hatenablog.com/entry/20131111/1384160073
http://stackoverflow.com/questions/3764001/how-to-use-a-sql-for-loop-to-insert-rows-into-database

9
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
7