Skip to content

Instantly share code, notes, and snippets.

@limitedeternity
Last active January 25, 2024 18:50
Show Gist options
  • Save limitedeternity/b004593ff4736749586a08f44c90d722 to your computer and use it in GitHub Desktop.
Save limitedeternity/b004593ff4736749586a08f44c90d722 to your computer and use it in GitHub Desktop.
Field value in a random PostgreSQL table record
create table if not exists scientist (id integer primary key, firstname varchar(100), lastname varchar(100));
insert into scientist (id, firstname, lastname) values (1, 'albert', 'einstein') on conflict DO NOTHING;
insert into scientist (id, firstname, lastname) values (2, 'isaac', 'newton') on conflict DO NOTHING;
insert into scientist (id, firstname, lastname) values (3, 'marie', 'curie') on conflict DO NOTHING;
CREATE OR REPLACE FUNCTION random_record(
table_name anycompatible
)
RETURNS SETOF anycompatible
LANGUAGE plpgsql
AS
'
DECLARE
sql text := format($$
SELECT * FROM %1$I
ORDER BY random() LIMIT 1
$$, pg_typeof(table_name));
BEGIN
RETURN QUERY EXECUTE sql;
END
';
SELECT firstname FROM random_record(NULL::scientist);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment