- Published on
Create Random String Function and Populate Table in PostgreSQL
566 words3 min read
-- Step 1: Create a table 'employees' to store employee data with an auto-incrementing 'id' and 'name' as text.
CREATE TABLE employees(
id serial primary key, -- 'id' will automatically increment with each new row.
name text -- 'name' stores the employee's name as a text field.
);
-- Step 2: Create a function to generate random strings of a specified length.
CREATE OR REPLACE FUNCTION random_string(length integer) RETURNS text AS
$$
DECLARE
-- Step 2.1: Define an array 'chars' containing characters (digits and letters) to choose from.
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}';
-- Step 2.2: Initialize a variable 'result' to store the generated random string.
result text := '';
-- Step 2.3: Variable 'i' will be used in the loop to generate each character of the string.
i integer := 0;
-- Step 2.4: 'length2' is calculated randomly, determining the length of the generated string.
length2 integer := (SELECT trunc(random() * length + 1));
BEGIN
-- Step 2.5: Raise an exception if the calculated string length is negative (should not happen).
IF length2 < 0 THEN
RAISE EXCEPTION 'Given length cannot be less than 0';
END IF;
-- Step 2.6: Loop through and generate the random string by appending random characters from the 'chars' array.
FOR i IN 1..length2 LOOP
result := result || chars[1 + random() * (array_length(chars, 1) - 1)]; -- Append a random character.
END LOOP;
-- Step 2.7: Return the generated random string.
RETURN result;
END;
$$ LANGUAGE plpgsql; -- Define the function using the PL/pgSQL procedural language.
-- Step 3: Insert 100000 random names into the 'employees' table.
INSERT INTO employees (name)
SELECT random_string(10)
FROM generate_series(1, 100000);
Sample Output:
After running the random_string
function to insert data into the employees
table, the name
column will contain randomly generated strings. Here’s an example of a few records that might be inserted:
id | name |
---|---|
1 | a4B2eG |
2 | 7yWqZ1 |
3 | j2kQ8wL |
4 | F9dK0zP |
5 | xC1sV8T |
Each time you run the random_string
function, you will get a different random string with a length between 1 and the specified length
.