Update data to array column Postgres - postgresql

I wouldike to send some data to my column (type array)
But the syntax doesn't work...
UPDATE car
SET ctn_color = array_cat(ctn_color, '{red,blue}');
WHERE ctn_identifiant_car='CONT_ABC';
Thanks for your help !

Related

How to delete all data leaving a pair of values ​in hstore PostgreSQL?

I am having the data of the name column as below :
"name:en"=>"Mường Tè district", "name:ko"=>"므엉떼", "name:vi"=>"TT. Mường Tè", "name:zh"=>"芒齐市镇", "official_name"=>"Thị trấn Mường Tè", "official_name:en"=>"Muong Te Town"
name column has data type hstore in postgresql.
Is there a way to keep a pair of values ​​eg leaving only the value pair "name:vi"=>"TT.Mường Tè" ? (delete all value pairs leaving the value pair "name:vi"=>"TT.Mường Tè" ). I want to make 1 query to solve the above problem, thanks !
The slice function does just that:
UPDATE the_table
SET name = slice(name, ARRAY['name:vi'])

Text and jsonb concatenation in a single postgresql query

How can I concatenate a string inside of a concatenated jsonb object in postgresql? In other words, I am using the JSONb concatenate operator as well as the text concatenate operator in the same query and running into trouble.
Or... if there is a totally different query I should be executing, I'd appreciate hearing suggestions. The goal is to update a row containing a jsonb column. We don't want to overwrite existing key value pairs in the jsonb column that are not provided in the query and we also want to update multiple rows at once.
My query:
update contacts as c set data = data || '{"geomatch": "MATCH","latitude":'||v.latitude||'}'
from (values (16247746,40.814140),
(16247747,20.900840),
(16247748,20.890570)) as v(contact_id,latitude) where c.contact_id = v.contact_id
The Error:
ERROR: invalid input syntax for type json
LINE 85: update contacts as c set data = data || '{"geomatch": "MATCH...
^
DETAIL: The input string ended unexpectedly.
CONTEXT: JSON data, line 1: {"geomatch": "MATCH","latitude":
SQL state: 22P02
Character: 4573
You might be looking for
SET data = data || ('{"geomatch": "MATCH","latitude":'||v.latitude||'}')::jsonb
-- ^^ jsonb ^^ text ^^ text
but that's not how one should build JSON objects - that v.latitude might not be a valid JSON literal, or even contain some injection like "", "otherKey": "oops". (Admittedly, in your example you control the values, and they're numbers so it might be fine, but it's still a bad practice). Instead, use jsonb_build_object:
SET data = data || jsonb_build_object('geomatch', 'MATCH', 'latitude', v.latitude)
There are two problems. The first is operator precedence preventing your concatenation of a jsonb object to what is read a text object. The second is that the concatenation of text pieces requires a cast to jsonb.
This should work:
update contacts as c
set data = data || ('{"geomatch": "MATCH","latitude":'||v.latitude||'}')::jsonb
from (values (16247746,40.814140),
(16247747,20.900840),
(16247748,20.890570)) as v(contact_id,latitude)
where c.contact_id = v.contact_id
;

Postgres update first record in JSON column for all records

I'm using postgres 9.6.1.
I have an "orders" table that has a column "orderData" that is type JSON.
What each record in the orderData column currently looks like:
[{"orderId":1}, {"orderId":2}, {"orderId":3}]
I'm trying to write a sql query that adds a key to the first order object in each array.
What each record in the orderData column should look like after query:
[{"orderId":1, "isFirstOrder": true}, {"orderId":2}, {"orderId":3}]
NOT WORKING ATTEMPT:
WITH order AS (
SELECT orderData
FROM orders
CROSS APPLY OPENJSON(c) s
WHERE i = 1
)
UPDATE order
SET c = JSON_MODIFY(c, 'isFirstOrder', 'true');
Any help would be greatly appreciated.
demo:db<>fiddle
UPDATE orders
SET c = jsonb_set(c, '{0}', c -> 0 || '{"isFirstOrder": true}');
c -> 0 gets the first element of your array
|| adds the new attribute
jsonb_set rewrites the elements if they exists whereas {0} locates the rewriting position within the array
Postgres JSON functions
For type json there's no function json_set. So you have to do a bit of casting around your json data into jsonb and the final result back into json:
UPDATE orders
SET c = jsonb_set(c::jsonb, '{0}', c::jsonb -> 0 || '{"isFirstOrder": true}')::json
demo:db<>fiddle

Adding values to a newly inserted column in an existing table in PostgreSQL 9.3

created a table named "collegetable":
create table collegetable (stid integer primary key not null,stname
varchar(50),department varchar(10),dateofjoin date);
provided values for each column:collegetable data
inserted a new column in it named "cgpa" and tried to add values for this column in one shot using the code:
WITH col(stid, cgpa) as
( VALUES((1121,8.01),
(1131,7.12),
(1141,9.86))
)
UPDATE collegetable as colldata
SET cgpa = col.cgpa
FROM col
WHERE colldata.stid = col.stid;
and got error :
ERROR:operator does not exist:integer=record
LINE9:where colldata.stid=col.stid;
HINT:No operator matches the given name and arguement type.you might need to add explicit type casts.
pls help in solving.thanks in advance.
The with clause only defines the names of the columns, not the data types:
with col (stid, cgpa) as (
...
)
update ...;
For details see the tutorial and the full reference

SQLAlchemy ORM Query encoding

Folks,
Can you please advise on following.
I am trying to display values in native format - Cyrillic.
Below is my query
db.session.query(items.item_name).join(item_ship, item_ship.item_id == items.id).join(house_shipment, house_shipment.id == item_ship.shipment_id).first();
Result: (u'\u041c\u0443\u0436\u0441\u043a\u0430\u044f \u043e\u0431\u0443\u0432\u044c',)
Default collation for table items is set to utf8_general_ci and my connection string is following.
mysql://root:Abc123#localhost/test?charset=utf8
Please help.
Thanks,
Your encoding is right:
>>> print(u'\u041c\u0443\u0436\u0441\u043a\u0430\u044f \u043e\u0431\u0443\u0432\u044c')
Мужская обувь
>>> print(repr(u'Мужская обувь'))
u'\u041c\u0443\u0436\u0441\u043a\u0430\u044f \u043e\u0431\u0443\u0432\u044c'
Your main problem that you are getting not a string but object that contains first result row. So you are getting repr of object.
Change .first() at the end of query to .scalar(). Scalar will return first column of first row.
As another variant you may access to row object and extract string from it.