DBAtlas · データベース運用アトラス

テーブル間/環境間でデータをコピー

Oracle

-- Into an existing table
INSERT INTO target_tbl (id, name) SELECT id, name FROM source_tbl WHERE status = 'ACTIVE';

-- By creating a new table (CTAS)
CREATE TABLE target_tbl AS SELECT * FROM source_tbl;

-- From a remote database via a database link
INSERT INTO target_tbl SELECT * FROM source_tbl@remote_db;

同一データベース内では INSERT ... SELECT または CREATE TABLE AS SELECT(CTAS)を使用する。環境間のコピーにはデータベースリンク(@remote_db)または Data Pump が推奨される。APPEND ヒントはダイレクトパスで高速化する。

PostgreSQL

-- Same database
INSERT INTO target_tbl (id, name) SELECT id, name FROM source_tbl;
CREATE TABLE target_tbl AS SELECT * FROM source_tbl;

-- Between environments (psql pipe)
-- pg_dump -t source_tbl sourcedb | psql targetdb
-- or read the remote table with postgres_fdw and INSERT

同一 DB 内では INSERT ... SELECT / CTAS を使用する。サーバー間では pg_dump | psql のパイプライン、または postgres_fdw の外部テーブル経由でコピーする。

MySQL

-- Same database
INSERT INTO target_tbl (id, name) SELECT id, name FROM source_tbl;
CREATE TABLE target_tbl AS SELECT * FROM source_tbl;

-- Between servers (mysqldump pipe)
-- mysqldump sourcedb source_tbl | mysql -h targethost targetdb

同一 DB 内では INSERT ... SELECT または CREATE TABLE ... AS SELECT。異なるサーバー間では mysqldump の出力を mysql クライアントにパイプする方法が一般的。CTAS はインデックスと制約をコピーしない。

SQL Server

-- Into an existing table
INSERT INTO target_tbl (id, name) SELECT id, name FROM source_tbl;

-- By creating a new table
SELECT * INTO target_tbl FROM source_tbl;

-- Between servers: linked server
INSERT INTO target_tbl SELECT * FROM [REMOTE_SRV].shop.dbo.source_tbl;

SQL Server では新しいテーブルへのコピーは SELECT ... INTO(CTAS 相当)で行う。サーバー間ではリンクサーバー(4 部構成名)、bcp out/in または SSIS を使用する。

MongoDB

// Write an aggregation result to another collection
db.source_tbl.aggregate([
  { $match: { status: "ACTIVE" } },
  { $out: "target_tbl" }
]);

// Merge into an existing collection (upsert)
db.source_tbl.aggregate([ { $merge: { into: "target_tbl", whenMatched: "merge", whenNotMatched: "insert" } } ]);

$out はターゲットコレクションを完全に置き換える。$merge は既存ドキュメントにマージ/挿入する(同じ DB または別の DB)。サーバー間の移動には mongodump | mongorestore または mongoexport/mongoimport を使用する。

Redis

# Move a single key to another server (deleted from the source)
MIGRATE target_host 6379 customer:1 0 5000

# To copy (without deleting): DUMP + RESTORE
DUMP customer:1          # returns the serialized value
RESTORE customer:1new 0 "<dump-data>"

MIGRATE はキーをターゲットインスタンスにアトミックに移動し、ソースから削除する(COPY オプションでは削除しない)。同一インスタンス内でコピーするには COPY コマンド(6.0+)または DUMP+RESTORE を使用する。

Elasticsearch

# Within the same cluster
POST _reindex
{ "source": { "index": "source_tbl" }, "dest": { "index": "target_tbl" } }

# From a remote cluster (remote reindex; requires the whitelist setting)
POST _reindex
{ "source": { "remote": { "host": "http://remote:9200" }, "index": "source_tbl" },
  "dest": { "index": "target_tbl" } }

_reindex はインデックス間でコピーする。クエリで絞り込み、スクリプトで変換できる。クラスタ間ではリモート reindex を使用する(ターゲットに reindex.remote.whitelist の定義が必要)。大規模なジョブは slices で並列化する。

DBAtlas で開く →