Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create and store array of objects in postgresql

Tags:

postgresql

In postgresql allowed array types or integer and text.But i need to create array of objects.how can i do that.

myarray text[];   //for text ['a','b','c']
myarray integer[];  //for integer[1,2,3]

I need to create the array like below

[{'dsad':1},{'sdsad':34.6},{'sdsad':23}] 

I dont want to use JSON type.Using array type i need to store the array of objects.

like image 287
sachin Avatar asked Nov 20 '13 12:11

sachin


People also ask

Can you store array of objects in PostgreSQL?

An array is a single data object that holds multiple values. In PostgreSQL, you can create an array for any built-in or user-defined data type.

How do I store objects in PostgreSQL?

PostgreSQL provides two distinct ways to store binary data. Binary data can be stored in a table using the data type bytea or by using the Large Object feature which stores the binary data in a separate table in a special format and refers to that table by storing a value of type oid in your table.

How do I create an array of text in PostgreSQL?

In this operation, we can insert a String Array into the table using the following syntax. In the above syntax where insert into is a keyword, column name1, column name2 is a specified column name in the table, and values mean actual string array values which we need to insert into the table.

What is [] in PostgreSQL?

Array Type. PostgreSQL gives the opportunity to define a column of a table as a variable length single or multidimensional array. Arrays of any built-in or user-defined base type, enum type, or composite type can be created. We will focus on one data type in particular, the Array of text, text[].


1 Answers

If you're running Postgres 9.2+, you can use the JSON type.

For example, we could do

create table jsontest (id serial primary key, data json);
insert into jsontest (data) values ('[{"dsad":1},{"sdsad":34.6},{"sdsad":23}]');

And query the data with

select data->1 from jsontest;
{"sdsad":34.6}
like image 52
Daniel Lubarov Avatar answered Sep 17 '22 15:09

Daniel Lubarov