Skip to content

Instantly share code, notes, and snippets.

@jotafeldmann
Created March 9, 2022 23:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jotafeldmann/5eeca544c8e86afe546c794636d27ebf to your computer and use it in GitHub Desktop.
Save jotafeldmann/5eeca544c8e86afe546c794636d27ebf to your computer and use it in GitHub Desktop.
Generate query to sort cols (PostgreSQL)
-- 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