Howtodojo logo
  • Home 
  • About 
  • Certifications 
  • Sample Database 
  • Cheatsheet 
  • Glossary 
  • Blog 
  • Tags 
  1.   Blog
  1. Home
  2. Blog
  3. How to Generate Random Data in PostgreSQL

How to Generate Random Data in PostgreSQL

Share via
Howtodojo
Link copied to clipboard

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.

On this page
Overview   Generate Random Data using md5 function in PostgreSQL   Generate data from random words in words.list file  
How to Generate Random Data in PostgreSQL

Overview  

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.

Generate Random Data using md5 function in PostgreSQL  

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;

Generate data from random words in words.list file  

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
 How To Install PostgreSQL 9.6 on Ubuntu 20.04
How To Get Public IP From Command Line 
On this page:
Overview   Generate Random Data using md5 function in PostgreSQL   Generate data from random words in words.list file  
Follow me

We publish tutorials, tips and tricks about Linux, open source, cloud computing, and infrastructure

     
Copyright © 2012 - 2025 howtodojo.com. |
Howtodojo
Code copied to clipboard