Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting array values

How do I write and execute a query which inserts array values using libpqxx?

INSERT INTO exampleTable(exampleArray[3]) VALUES('{1, 2, 3}'); 

This example code gives me:

ERROR:  syntax error at or near "'" 

What is wrong? In PostgreSQL documentation I found that:

CREATE TABLE sal_emp ( name            text, pay_by_quarter  integer[], schedule        text[][] );  

...

INSERT INTO sal_emp VALUES ('Bill', '{10000, 10000, 10000, 10000}', '{{"meeting", "lunch"}, {"training", "presentation"}}'); 
like image 242
ktoś tam Avatar asked Oct 25 '15 21:10

ktoś tam


People also ask

Can we insert data in array?

We can insert the elements wherever we want, which means we can insert either at starting position or at the middle or at last or anywhere in the array. After inserting the element in the array, the positions or index location is increased but it does not mean the size of the array is increasing.

How can you insert an element at a specific index in an array?

There is no method available in the Array object to add an element to a specific index, but we can use the already available splice method to achieve this. An array starts from index 0 , so if we want to add an element as the first element of the array, then the index of the element is 0.

Can you insert array into SQL?

How to insert Array elements in SQL? We can insert array elements in an array by mentioning them within curly braces {} with each element separated by commas. Here is an example to illustrate the method for element addition in an array in SQL. Let us insert details into the above mentioned “product_details” table.


1 Answers

You should use a column name without an index to insert an array:

create table example(arr smallint[]); insert into example(arr) values('{1, 2, 3}'); -- alternative syntax -- insert into example(arr) values(array[1, 2, 3]);  select * from example;     arr    ---------  {1,2,3} (1 row)  

Use the column name with an index to access a single element of the array:

select arr[2] as "arr[2]" from example;   arr[2]  --------       2 (1 row)  update example set arr[2] = 10; select * from example;     arr     ----------  {1,10,3} (1 row)  

You can use arr[n] in INSERT but this has special meaning. With this syntax you can create an array with one element indexed from the given number:

delete from example; insert into example(arr[3]) values (1); select * from example;      arr     -----------  [3:3]={1} (1 row)  

As a result you have an array which lower bound is 3:

select arr[3] from example;  arr  -----    1 (1 row) 
like image 104
klin Avatar answered Sep 20 '22 13:09

klin