I have a composite type like
CREATE TYPE example AS (id integer, some_stuff integer[]);
Thought I can use an array of this type as an argument of a function. The only problem is I couldn't find a way to build an array literal for that... If I try obtain it from PostgreSQL:
WITH elements AS (
SELECT (12, '{1,2}')::example AS e UNION
SELECT (3, '{3,1}')::example
)
SELECT array_agg(e) FROM elements;
I get the following:
{"(3,\"{3,1}\")","(12,\"{1,2}\")"}
But look:
SELECT E'{"(3,\"{3,1}\")","(12,\"{1,2}\")"}'::example[];
ERROR: malformed array literal: "{"(3,"{3,1}")","(12,"{1,2}")"}"
LINE 1: select E'{"(3,\"{3,1}\")","(12,\"{1,2}\")"}'::example[]
Is there a way to do this?
Array literals An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ( [] ). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified.
You can easily create arrays in PostgreSQL by adding square brackets [] immediately after the data type for the column. create table employees ( first_name varchar, last_name varchar, phone_numbers integer[] ); In the above example, we have created column phone_numbers as an array of integers.
Syntax. In the above syntax, we can declare a String Array data type at the time of table creation. Where table name is the specified table name that we need to create and column 1, column 2, and column n declared with the data type of array and it separated by using a comma.
Try using ARRAY
and ROW
constructors:
Select array[row(3, array[3,1]), row(12, array[1,2])]::example[];
array
------------------------------------
{"(3,\"{3,1}\")","(12,\"{1,2}\")"}
(1 row)
If you want solution without using constructors, then use following example:
Select E'{"(3,\\"{3,1}\\")","(12,\\"{1,2}\\")"}'::example[];
example
------------------------------------
{"(3,\"{3,1}\")","(12,\"{1,2}\")"}
(1 row)
As you see main issue here is that you need to write \\"
, because this effectively means \"
(using "escape" string syntax) that you saw as output of your first select.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With