Last active
July 14, 2016 11:28
-
-
Save kfeoktistoff/7a22c83f6544591c8134933cd96dbe82 to your computer and use it in GitHub Desktop.
PL/PgSQL function shuffles all values in a column. A table must have unique 'id' field.
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 OR REPLACE FUNCTION shuffle(table_name TEXT, field_name TEXT) RETURNS void AS $$ | |
DECLARE entry RECORD; | |
DECLARE entry_to_swap RECORD; | |
BEGIN | |
FOR entry IN execute format('select * from %s', table_name) LOOP | |
drop table if exists tmp_entry_to_swap; | |
execute format('create temp table tmp_entry_to_swap as (select * from %s order by random() limit 1)', table_name); | |
select * into entry_to_swap from tmp_entry_to_swap; | |
if entry.id <> entry_to_swap.id then | |
execute format( | |
'UPDATE %1$s dst set %2$s = src.%2$s | |
FROM %1$s src | |
WHERE dst.id IN (' || entry.id || ', ' || entry_to_swap.id || ') | |
AND src.id in (' || entry.id || ', ' || entry_to_swap.id || ') AND dst.id <> src.id', table_name, field_name | |
); | |
end if; | |
END LOOP; | |
END; | |
$$ LANGUAGE plpgsql; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment