Search code examples
arrayspostgresqlplpgsqlddluser-defined-data-types

How to create TYPE in PostgreSQL?


How do I create a datatype in plpgsql? I'm new to PostgreSQL, i'm converting oracle procedures into postgresql functions. They have created a type in oracle something like:

TYPE t_array IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER;

Then declared & used it in the procedure like:

strings t_array;
strings(1) := lv_str;

I want to create t_array type in plpgsql and use it in functions, how can I create such type or is there any inbuilt type to achieve this functionality in plpgsql?


Solution

  • You don't need to create a type for that in PL/pgSQL, just declare an array variable:

    declare
      l_strings text[];
    begin
      l_string[1] := 'This is the first string';
      l_string[2] := 'This is the second string';
    end;
    

    Arrays can be used as parameters as well:

    create function do_something(p_some_number integer, p_strings text[])
      returns ..
    as
    ...
    

    Call it using do_something(42, array['one', 'two'])