Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append a new item into the array-type column in PostgreSQL

Im using PostgreSQL for my application,

The task will be like this

There are users who use my app, and I need to maintain notification for each of them based on their activity so I get lots and lots of notifications for each user.

so in general we just put all the notifications in a seperate table and we do map with user ID, so we can just fetch them, but now Im thinking to use either json/array datatype, so I can just put the entire notification set as array/json into the cell of each user row.

Which one is better, storing json or array?( Im using PHP at server side)

and if we pick any one among the two, lets say we have some 10 notifications, and I got the 11th one, how do we append the new item into the array/json object in single execution(may be UPDATE statement)? I dont want to go in basic way like select the row, get the existing array/json add the new item in the end(process with PHP) and UPDATE it back- here it takes two executions where another change may occur and that brings dataloss

so is there a way to do UPDATE query that just adds a new element or alters the existing element/node in array/json obejct types in PostgreSQL?

like image 473
CodeRows Avatar asked Mar 28 '15 16:03

CodeRows


People also ask

How do you update an array field in SQL?

Replace all elements in an Array You can easily replace all elements of an array using UPDATE … SET statement. In the above UPDATE statement, we provide array values within curly braces enclosed in single quotes. Postgres will replace the entire array for rows that match the WHERE condition.

How do you add to an array in SQL?

We can insert array elements in an array by mentioning them within curly braces {} with each element separated by commas.

How do I create an array in PostgreSQL?

Declaration of Array Types. To illustrate the use of array types, we create this table: CREATE TABLE sal_emp ( name text, pay_by_quarter integer[], schedule text[][] ); As shown, an array data type is named by appending square brackets ( [] ) to the data type name of the array elements.

How do you update an array in a database?

You can use the update_batch function of codeigniter for the desired result as you are sending a multi dimension array to the update function it will through a error.


1 Answers

To append an item to an array in PostgreSQL you can use the || operator or the array_append function.

With || operator

UPDATE table SET array_field = array_field || '{"new item"}' WHERE ...

With array_append function

UPDATE table SET array_field = array_append(array_field,'new item') WHERE ...

Also, you can visit this page for array, http://www.postgresql.org/docs/current/interactive/functions-array.html

I don't know how to do it with JSON data type.

like image 143
samed.yildirim Avatar answered Oct 11 '22 01:10

samed.yildirim