Last active
January 25, 2024 18:50
-
-
Save limitedeternity/b004593ff4736749586a08f44c90d722 to your computer and use it in GitHub Desktop.
Field value in a random PostgreSQL table record
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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