How do I synchronize parallel imports with COPY? I have ~20 tables that get built at the same time but using different psql processes (via bash script) at the first stage with something like:

create table foo_1 as (select ....); -- via psql process 1
create table foo_2 as (select ....); -- via psql process 2
create table foo_3 as (select ....); -- via psql process 3
...
create table foo_20 as (select ....); -- via psql process 20


Once they are built a new stage should start. Is there any good strategy to coordinate this multiple build? I mean, sync the two stages by discovering that all tables are built first from stage 1.
Parallel DB operations


  Is there any good strategy to coordinate this multiple build?


Well, the right way to run a task that requires multiple connections to the database is to use fork-exec (spawn on Windows). Then you wait in the parent for the children to return. For a good review check out this video on YouTube. It brings up fork-exec about 27 min in. That whole video is probably watching if you're new to Unix.

It's unlikely though that your loads are substantially faster in parallel, because it's not likely that the CPU is the bottleneck.

Loading from Files

If it really does matter though, and you're loading from file rather than query check out pg_bulkload rather than doing this yourself.

Materialized Views

In your case you're batching up CREATE TABLE AS SELECT (CTAS). A CTAS is useful for test data. If what you're doing is not test data, and you're dropping these tables and recreating them or the like then what I highly suggest you check out is MATERIALIZED VIEWS which can even be REFRESH MATERIALIZED VIEW CONCURRENTLY,


  REFRESH MATERIALIZED VIEW completely replaces the contents of a materialized view. The old contents are discarded. [...]
  
  CONCURRENTLY Refresh the materialized view without locking out concurrent selects on the materialized view. Without this option a refresh which affects a lot of rows will tend to use fewer resources and complete more quickly, but could block other connections which are trying to read from the materialized view. This option may be faster in cases where a small number of rows are affected.