0

On PostgreSQL, I need to see the table's columns in alphabetical order, so I'm using the query:

SELECT column_name, data_type FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'organizations' ORDER BY column_name ASC;
          

I use it a lot every day, so I want to create a function:

 CREATE OR REPLACE FUNCTION seecols(table_name text)
 RETURNS TABLE (column_name varchar, data_type varchar)
AS $func$
 DECLARE
 _query varchar;
 BEGIN
  -- Displays columns by alphabetic order
   _query := 'SELECT column_name, data_type FROM information_schema.columns WHERE table_name = '''||table_name||''' ';

  RETURN QUERY EXECUTE _query;
 END;
$func$ LANGUAGE plpgsql;

But when I try:

SELECT seecols('organizations');

I'm getting:

 **structure of query does not match function result type** 

I guess the line "RETURNS TABLE (column_name varchar, data_type varchar)" is wrongly defined. But since this is my first time using plpgsql, I don't know how to make it more dynamic.

3
  • 2
    Look at the data types for [information_schema.columns])postgresql.org/docs/current/infoschema-columns.html). They are not varchar. Probably easiest thing to do is : SELECT column_name::varchar, data_type::varchar FROM .... Otherwise: RETURNS TABLE (column_name information_schema.sql_identifier, data_type information_schema.sql_identifier) . Commented Jan 7, 2023 at 21:01
  • 1
    postgresql.org/docs/15/infoschema-datatypes.html Commented Jan 8, 2023 at 0:08
  • 1
    Btw, no need for dynamic sql and building a string for the query. just use RETURN SELECT column_name, data_type FROM information_schema.columns WHERE column.table_name = seecols.table_name; Commented Jan 8, 2023 at 0:09

1 Answer 1

1

You don't need neither dynamic sql nor plpgsql here. Just embed your sql query into a sql function :

CREATE OR REPLACE FUNCTION seecols (IN t_name text, OUT column_name varchar, OUT data_type varchar)
  RETURNS setof record LANGUAGE sql AS $$
  SELECT column_name, data_type 
    FROM INFORMATION_SCHEMA.COLUMNS 
   WHERE TABLE_NAME = t_name 
   ORDER BY column_name ASC ;
$$ ;

see dbfiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.