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?
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.
We can insert array elements in an array by mentioning them within curly braces {} with each element separated by commas.
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.
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.
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.
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