How to Generate Random Data in PostgreSQL
Posted on July 1, 2021 • 1 min read • 135 wordsIn this tutorial we learn how to generate random data in PostgreSQL. This method is sometimes needed to test the functionality of a PostgreSQL installation whether locally or remotely.
In this tutorial we learn how to generate random data in PostgreSQL. This method is sometimes needed to test the functionality of a PostgreSQL installation whether locally or remotely.
To generate
SELECT generate_series(1,10) AS id, md5(random()::text) AS descr;
```bash
## Generate data using generate_series function {#h-generate-data-using-generate_series-function}
```bash
CREATE TABLE t_random as select s, md5(random()::text) from generate_Series(1,5) s;
Create table
CREATE TABLE randomTable(id serial PRIMARY KEY, description text);
```bash
Create function
```bash
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;
Insert data
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);
```bash
source: [stackoverflow][1]
[1]: https://stackoverflow.com/questions/3371503/sql-populate-table-with-random-data