Skip to content
Advertisement

Insert multiple rows in one table based on number in another table

I am creating a database for the first time using Postgres 9.3 on MacOSX.

Let’s say I have table A and B. A starts off as empty and B as filled. I would like the number of entries in column all_names in table B to equal the number for each names in table A like table B below. Thus names should contain each unique entry from all_names and number its count. I am not used to the syntax, yet, so I do not really know how to go about it. The birthday column is redundant.

Table A

Table B

Would this be the correct way to go about it?

Advertisement

Answer

Answer to original question

Postgres allows set-returning functions (SRF) to multiply rows. generate_series() is your friend:

Since the introduction of LATERAL in Postgres 9.3 you can do stick to standard SQL: the SRF moves from the SELECT to the FROM list:

LATERAL is implicit here, as explained in the manual:

LATERAL can also precede a function-call FROM item, but in this case it is a noise word, because the function expression can refer to earlier FROM items in any case.

Reverse operation

The above is the reverse operation (approximately) of a simple aggregate count():

… which fits your updated question.

Note a subtle difference between count(*) and count(all_names). The former counts all rows, no matter what, while the latter only counts rows where all_names IS NOT NULL. If your column all_names is defined as NOT NULL, both return the same, but count(*) is a bit shorter and faster.

About GROUP BY 1:

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement