Carregando...
Banco de DadosPostgreSQL

Gerando dados aleatórios no PostgreSQL

Como gerar dados aleatórios randomicos no PostgreSQL?

Dados do tipo INT, BIGINT (número sem vírgula)

-- Generally, to generate a random number between two integers l and h, you use the following statement:

SELECT floor(random() * (h-l+1) + l)::int;

Dados do tipo REAL, DOUBLE, NUMERIC (número com vírgula)

SELECT random();
-- 0.867320362944156

--To generate a random number between 1 and 11, you use the following statement:
SELECT random() * 10 + 1 AS RAND_1_11;
-- 7.75778411421925

Dados do tipo TEXT (texto)

CREATE OR REPLACE FUNCTION random_string(length INTEGER) RETURNS TEXT AS
$$
DECLARE
  chars TEXT[] := '{0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}';
  result TEXT:= '';
  i INTEGER:= 0;
BEGIN
  IF length < 0 then
    RAISE EXCEPTION 'Given length cannot be less than 0';
  END IF;
  FOR i IN 1..length LOOP
    result := result || chars[1+random()*(array_length(chars, 1)-1)];
  END LOOP;
  RETURN result;
END;
$$ LANGUAGE plpgsql;

Referência https://stackoverflow.com/a/3972983/2789895

Gerando uma lista com vários números aleatórios

SELECT random()
FROM generate_series(1,50);

INSERT

INSERT INTO tabela_destino
SELECT 'hello' AS name, random() AS value
FROM generate_series(1,50);

Referência

PostgreSQL Tutorial
https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-random-range/

How to create lots of sample timeseries data
https://www.timescale.com/blog/how-to-create-lots-of-sample-time-series-data-with-postgresql-generate_series/

How to INSERT from SELECT
https://dba.stackexchange.com/questions/2973/how-to-insert-values-into-a-table-from-a-select-query-in-postgresql

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *