0

LINKs: https://www.2ndquadrant.com/wp-content/uploads/2019/05/sumtest.sql_.txt https://www.2ndquadrant.com/en/blog/join-lateral/

CREATE TABLE co_books (
    dd  numeric references books(dd),
    pname text references persons(pname),
    checked_out timestamptz,
    checked_in timestamptz);
Do $$
    DECLARE
    i int;
    afew int;
    p record;
    BEGIN
        FOR p IN SELECT pname FROM persons LOOP
            afew := (random() * 10)::integer;
            FOR i in 0..afew LOOP
                INSERT INTO co_books (dd, pname, checked_out) 
                VALUES 
                    ( (SELECT dd FROM books ORDER BY random() LIMIT 1), 
                         p.pname, /* hint: fix bad random data here */
                         (SELECT xtime FROM X2018 ORDER BY random() LIMIT 1)
                    );

            END LOOP;
        END LOOP;
    RETURN;
END;
$$;

If you follow the link, you can see it clearly that table person, column pname have 24 unique rows. After I executed the code block, then test how many rows in table: co_books. first time is 129 rows, then i delete the co_books, execute the code again, the rows is 156 rows, third time is 154 rows. So In this case, I think i don't understand the following part.

FOR p IN SELECT pname FROM persons LOOP
            afew := (random() * 10)::integer;
            FOR i in 0..afew LOOP
Mark
  • 19
  • 6

1 Answers1

0

random() returns a random double precision number between 0 and 1.

(random() * 10)::integer

is a random integer between 0 and 10.

So the loop will perform somewhere between 1 and 11 INSERT statements on co_books.

So it is to be expected that the number of rows in the table varies every time the code is run.

Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263