Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

text[] in postgresql?

I saw a field text[] (text array) in Postgresql.

As far as I understood,it can store multiple text data in a single column.

I tried to read more about it the manual: http://www.postgresql.org/docs/current/static/datatype-character.html but unfortunately nothing much was there about text[] column type.

So can anyone help me to understand

  • How to add a new value to text[] column?
  • What will be the resultset when we query to retrieve the values of text[] column?

    EDIT
    I have a table containing 2 columns group_name and members. Each time a new person join the group,the new person's id should be inserted in the column members for that group_name. This is my requirement.A Group can contain 'n' number of members

    EDIT 2
    Pablo is asking me to use two tables instead. May I know how this could be solved by using two different tables? Right now I am using comma(,) to store multiple values separated by comma. Is this method wrong?

like image 962
suraj Avatar asked Oct 23 '22 22:10

suraj


1 Answers

To insert new values just do:

insert into foo values (ARRAY['a', 'b']);

Assuming you have this table:

create table foo (a text[]);

Every time you do a select a from foo you will have a column of type array:

db1=> select a from foo;
   a   
-------
 {a,b}
(1 row)

If you want a specific element from the array, you need to use subscripts (arrays in PostgreSQL are 1-based):

db=> select a[1] from foo;
 a 
---
 a
(1 row)

Be careful when choosing an array datatype for your PostgreSQL tables. Make sure you don't need a child table instead.

like image 157
Pablo Santa Cruz Avatar answered Nov 04 '22 20:11

Pablo Santa Cruz