SQL Populate table with random data

前端 未结 4 1562
无人及你
无人及你 2020-12-01 05:20

I have a table with two fields:

  1. id(UUID) that is primary Key and
  2. description (var255)

I want to insert random data with SQ

4条回答
  •  天涯浪人
    2020-12-01 05:31

    Here it is a more elegant way using the latest features. I will use the Unix dictionary (/usr/share/dict/words) and copy it into my PostgreSQL data:

    cp /usr/share/dict/words data/pg95/words.list
    

    Then, you can easily create a ton of no sense description BUT searchable using dictionary words with the following steps:

    1) Create table and function. getNArrayS gets all the elements in an array and teh number of times it needs to concatenate.

    CREATE TABLE randomTable(id serial PRIMARY KEY, description text);
    
    CREATE OR REPLACE FUNCTION getNArrayS(el text[], count int) RETURNS text AS $$
      SELECT string_agg(el[random()*(array_length(el,1)-1)+1], ' ') FROM generate_series(1,count) g(i)
    $$
    VOLATILE
    LANGUAGE SQL;
    

    Once you have all in place, run the insert using CTE:

    WITH t(ray) AS(
      SELECT (string_to_array(pg_read_file('words.list')::text,E'\n')) 
    ) 
    INSERT INTO randomTable(description)
    SELECT getNArrayS(T.ray, 3) FROM T, generate_series(1,10000);
    

    And now, select as usual:

    postgres=# select * from randomtable limit 3;
     id |                 description                 
    ----+---------------------------------------------
      1 | ultracentenarian splenodiagnosis manurially
      2 | insequent monopolarity funipendulous
      3 | ruminate geodic unconcludable
    (3 rows)
    

提交回复
热议问题