Run Code
|
Code Wall
|
Users
|
Misc
|
Feedback
|
About
|
Login
|
Theme
|
Privacy
deep copy
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Editor:
CodeMirror
EditArea
Simple
Layout:
Vertical
Horizontal
drop table if exists table_a, table_b, table_c cascade; create table table_a ( id serial primary key, some_data text ); create table table_b ( id serial primary key, a_id integer not null references table_a, some_data integer ); create table table_c ( id serial primary key, b_id integer not null references table_b, some_data integer ); insert into table_a (id, some_data) values (1, 'one'); insert into table_b (id, a_id, some_data) values (1, 1, 10), (2,1,20); insert into table_c (id, b_id, some_data) values (1, 1, 100), (2, 1, 200), (3, 2, 300), (4, 2, 400); -- the above used hardcoded PK values, we need to adjust the sequence -- to avoid duplicate values. It also makes it easier to spot (and validate) the -- newly created rows as all copied IDs start with 100 select setval('table_a_id_seq', 100); select setval('table_b_id_seq', 100); select setval('table_c_id_seq', 100); with new_a_values as ( select a.id as old_a_id, nextval(pg_get_serial_sequence('table_a', 'id')) as new_a_id, 'Copy of '||a.some_data as some_data -- other columns from table_a a where a.id = 1 ), new_b_values as ( select a.old_a_id, a.new_a_id, b.id as old_b_id, nextval(pg_get_serial_sequence('table_b', 'id')) as new_b_id, b.some_data -- other columns from new_a_values a join table_b b on a.old_a_id = b.a_id ), new_c_values as ( select b.old_b_id, b.new_b_id, c.id as old_c_id, nextval(pg_get_serial_sequence('table_c', 'id')) as new_c_id, c.some_data -- other columns from new_b_values b join table_c c on c.b_id = b.old_b_id ), new_a as ( insert into table_a (id, some_data) select new_a_id, some_data from new_a_values ), new_b as ( insert into table_b (id, a_id, some_data) select new_b_id, new_a_id, some_data from new_b_values ) insert into table_c (id, b_id, some_data) select new_c_id, new_b_id, some_data from new_c_values; select * from table_a; select * from table_b; select * from table_c;
absolute service time: 0,58 sec
edit mode
|
history
setval
1
100
setval
1
100
setval
1
100
id
some_data
1
1
one
2
101
Copy of one
id
a_id
some_data
1
1
1
10
2
2
1
20
3
101
101
10
4
102
101
20
id
b_id
some_data
1
1
1
100
2
2
1
200
3
3
2
300
4
4
2
400
5
101
101
100
6
102
101
200
7
103
102
300
8
104
102
400