0

I need to insert k random numbers (in the range 1:n) concatenated by | into a column of a table 'X', where n is the number of rows in table 'Y', in a PostgreSQL procedure.

To find the number of rows in the table 'Y'

select count(*) into n from Y

This will generate k random numbers in the range 1:n

SELECT num FROM GENERATE_SERIES (1, n) AS s(num) ORDER BY RANDOM() LIMIT k;

How do I concatenate the k integers with | and insert them into 'X'?

6
  • 1
    Try string_agg Commented Oct 17, 2020 at 12:28
  • You claim that "n" is the number of columns in table y - but select count(*) into n from Y returns the number of rows in that table. Two very different things. Also: storing delimited values in a column is almost always a really bad idea. A properly normalized model is much easier to maintain and to work with Commented Oct 17, 2020 at 12:31
  • @Bergi with string_agg I need to pass the output of the query as the first argument, would I have to use a temporary table to hold the results of the query for generating the k random numbers or is there any other optimal way? Commented Oct 17, 2020 at 12:32
  • @a_horse_with_no_name Thanks for pointing that out, my bad, I corrected it to the number of rows. My use case is that I need to assign a random set of rows from multiple tables to a user for a task and need to maintain the assignments in a table. Commented Oct 17, 2020 at 12:35
  • Still: you shouldn't store delimited values in a single column. Commented Oct 17, 2020 at 12:59

1 Answer 1

1

You can use insert ... select and string aggregation function string_agg():

insert into y (x)
select string_agg(num::text, '|')
from (select num from generate_series (1, n) as s(num) order by random() limit k) s

Note that you need n to be equal to or greater than k for this technique to make sense.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.