Created
March 9, 2022 23:45
-
-
Save jotafeldmann/5eeca544c8e86afe546c794636d27ebf to your computer and use it in GitHub Desktop.
Generate query to sort cols (PostgreSQL)
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
-- Generate query to sort cols (PostgreSQL) | |
-- https://gist.github.com/jotafeldmann/5eeca544c8e86afe546c794636d27ebf | |
drop function if exists get_sorted_cols_from_table; | |
CREATE OR REPLACE FUNCTION get_sorted_cols_from_table(_tbl regclass, OUT result text) | |
LANGUAGE plpgsql AS | |
$func$ | |
BEGIN | |
EXECUTE format(' | |
select | |
string_agg(internal.column_name::text, '', '') | |
FROM ( | |
select column_name | |
FROM INFORMATION_SCHEMA.COLUMNS | |
WHERE TABLE_NAME = ''%s'' | |
ORDER BY column_name | |
) | |
AS internal; | |
', _tbl) | |
INTO result; | |
END | |
$func$; | |
drop function if exists select_all_sorted_cols_from_table; | |
CREATE OR REPLACE FUNCTION select_all_sorted_cols_from_table(_tbl regclass, OUT result text) | |
LANGUAGE plpgsql AS | |
$func$ | |
BEGIN | |
SELECT format( | |
'SELECT "id", %s FROM %s;' | |
, replace( | |
get_sorted_cols_from_table(_tbl)::text | |
, ' id, ', ' '), | |
_tbl) | |
INTO result; | |
END | |
$func$; | |
SELECT select_all_sorted_cols_from_table('table_name'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment