I created a field name is result and type is text. I just want to update 'lat' in column. When I use this query I get syntax error. How can I do?
The column data is
"{"lat":"48.00855","lng":"58.97342","referer":"https:\/\/abc.com\/index.php"}"
Query is
update public.log set (result::json)->>'lat'=123 where id=6848202
Syntax error is
ERROR: syntax error at or near "::"
Use the jsonb concatenation operator (Postgres 9.5+):
update log
set result = result::jsonb || '{"lat":"123"}'
where id = 6848202
In Postgres 9.4 use json_each() and json_object_agg() (because jsonb_object_agg() does not exists in 9.4).
update log
set result = (
select json_object_agg(key, case key when 'lat' then '123' else value end)
from json_each(result)
)
where id = 6848202
Both solutions assume that the json column is not null. If it does not contain the lat key, the first query will create it but the second will not.
In PostgreSQL 13, You can:
update public.log set result = jsonb_set(result,'{lat}','"123"') where id=6848202;
In case the column is still null, you can use coalesce. The answer is provided here: PostgreSQL 9.5 - update doesn't work when merging NULL with JSON
I also tried to update json value in json type field, but couldn't find appropriate example. So I've connected to postgres DB using PgAdmin4, opened desired table and changed desired field's value, then looked at Query History to see what command it uses to change it.
So, finally, I've got the next simple python code for own purposes to update json field in postgres db:
import psycopg2
conn = psycopg2.connect(host='localhost', dbname='mydbname', user='myusername', password='mypass', port='5432')
cur = conn.cursor()
cur.execute("UPDATE public.mytable SET options = '{\"credentials\": \"required\", \"users\": [{\"name\": \"user1\", \"type\": \"string\"}]}'::json WHERE id = 8;")
cur.execute("COMMIT")
Related
I have json column inside my PostgreSQL table that looks something similar to this:
{"example--4--":"test 1","another example--6--":"test 2","final example--e35b172a-af71-4207-91be-d1dc357fe8f3--Equipment":"ticked"}
{"example--4--":"test 4","another example--6--":"test 5","final example--e35b172a-af71-4207-91be-d1dc357fe8f3--Equipment":"ticked"}
Each key contains a map which is separated by --. The prefix is unique, ie: "example", "another example" and "final example".
I need to query on the unique prefix and so far, nothing I'm trying is even close.
select some_table.json_column from some_table
left join lateral (select array(select * from json_object_keys(some_table.json_column) as keys) k on true
where (select SPLIT_PART(k::text, '--', 1) as part_name) = 'example'
and some_table.json_column->>k = 'test 1'
The above is resulting in the following error (last line):
operator does not exist: json -> record
My expected output would be any records where "example--4--":"test 1" is present (in my above example, the only result would be)
{"example--4--":"test 1","another example--6--":"test 2","final example--e35b172a-af71-4207-91be-d1dc357fe8f3--Equipment":"ticked"}
Any help appreciated. After debugging around for a while, I can see the main issue resolves in the implicit cast to ::text. k seems to be a "record" of the keys that I need to loop and split to compare, currently, I'm casting a record to text which is causing the issue.
One way to do it, is to use an EXIST condition together with jsonb_each_text()
select *
from the_table
where exists (select *
from jsonb_each_text(data) as x(key,value)
where x.key like 'example%'
and x.value = 'test 1')
If your column isn't a jsonb (which it should be), you need to use json_each_text() instead
Another option is to use a JSON path expression:
select *
from the_table
where data #? '$.keyvalue() ? (#.key like_regex "^example" && #.value == "test 1")'
How to write the update query by using Arduino code in order to update (overwrite) the previous data in MYSQL.
Below is the example for FIXED VALUE QUERY. Its work well but how to change to variable value?
char UPDATE_SQL[] = "update [tableName] set [column_name] = [new_fixed_value] where [column_name] = [previous value] ;
update[database] it's wrong. It should be update[tableName]. For an example If I want to change in students table student sam's marks to 90 I can write as below
UPDATE students SET marks=90
WHERE name='sam'
Use sprintf to put your value into the string like this:
sprintf(UPDATE_SQL,"UPDATE students SET marks=%d WHERE name='%s'",
yourval,yourstrin);
I have a PGSQL database with a table that contains column containingJSON data along the lines of
{"kind":2,"msgid":102}
{"kind":99,"pid":"39s-8KeH306vhjzNta3Yrg,,","msgid":101}
...
Is it possible to write and execute DELETE statement along the lines of
DELETE FROM table WHERE data.kind = '99' AND data.pid = '39s-8KeH306vhjzNta3Yrg,,'?
where data happens to be the name of that particular column. I tried the above and got the error
missing FROM-clause entry for table "data"
i.e. PGSQL is interpreting that as being the table data. Clearly, the require syntax is different. I'd be grateful to anyone who might be able to tell me what to do here.
assuming you have:
t=# with c(j) as (values('{"kind":99,"pid":"39s-8KeH306vhjzNta3Yrg,,","msgid":101}'::json))
select * from c where j->>'kind' = '99' and j->>'pid' = '39s-8KeH306vhjzNta3Yrg,,';
j
----------------------------------------------------------
{"kind":99,"pid":"39s-8KeH306vhjzNta3Yrg,,","msgid":101}
(1 row)
then your statement will be:
delete from table where data->>'kind' = '99' and data->>'pid' = '39s-8KeH306vhjzNta3Yrg,,';
check json operators here: https://www.postgresql.org/docs/current/static/functions-json.html
I am using Postgres 9.6 and I have a JSONB column in which some rows have NULL value and some have dict values like {"notify": false}.
I want to update the column values with more dictionary key/value pairs.
UPDATE accounts SET notifications = jsonb_set(notifications, '{"alerts"}', 'false');
Does work for the cases where I already have values like {"notify": false}. The end result becomes as expected {"alerts": false, "notifications": false}.
But the value I'm trying to update us NULL, nothing is updated in the db.
Can you give me any ideas how I can update the NULL values as well, so the end result for them will be values like {"notify": false}. The end result becomes as expected {"alerts": false}
Use coalesce():
UPDATE accounts
SET notifications = jsonb_set(coalesce(notifications, '{}'), '{"alerts"}', 'false')
or even simpler:
UPDATE accounts
SET notifications = coalesce(notifications, '{}') || '{"alerts": false}'
Note that some versions of Postgres have coalesce() functions that don't support jsonb, and will give an error like this when trying to use the accepted answer:
ERROR: function coalsece(jsonb, unknown) does not exist
You can work around that by using a case statement instead. Ugly, but it works.
UPDATE accounts
SET notifications =
jsonb_set(
case
when notifications is null then '{}'
else notifications
end,
'{"alerts"}','false')
I am getting error that json_each function does not exist. I am using postgresql 9.3. I dont know whats wrong. Please assist me here.
select *
from json_each((
select ed.result
from externaldata ed
inner join
application a
on a.id = ed.application_id
))
limit 1;
The inside looped query returns :
" { "RespuestaSVC89":{
"Header":{
"Transaccion":"EXPE",
"Servicio":"92",
"CodigoRetorno":"00",
"NumeroOperacion":"201409147001616",
"CodigoModelo":"13852901"
},
"meta":{
"billa":"EXPE",
"numo":"52",
"Retorno":"01",
"Operacion":"2014091470",
}
}
}"
so it should work but somehow does not work
Exact error message is :
ERROR: function json_each(text) does not exist
LINE 2: from json_each((
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
********** Error **********
ERROR: function json_each(text) does not exist
SQL state: 42883
Hint: No function matches the given name and argument types. You might need to add explicit type casts.
Character: 15
the error message states that no json_each(text) function exists, however I know that a json_each(json) function exists. The key is casting ed.result to json data type like so:
select *
from json_each((
select ed.result::json
from externaldata ed
inner join
application a
on a.id = ed.application_id
))
limit 1;
You might consider making ed.result column be of type json (in the actual table) instead of type text if your data truly is all valid json. When 9.4 comes out, you'll almost certainly want to use the jsonb data type to take advantage of the performance and space benefits that come with that datatype.
It might be one more possible reason:
A type of the column which contains a json is not of json type, but jsonb.
In this case you should use not json_each function, but jsonb_each.
Example:
create table metric
(
user_id bigint not null,
created_at timestamp with time zone not null,
data jsonb not null,
constraint metric_pk
primary key (user_id, created_at)
);
Query:
select metric.created_at, jsb.key, jsb.value
from metric,
json_each(data) as jsb
where user_id = <user_id>;
results in:
[42883] ERROR: function json_each(jsonb) does not exist
No function matches the given name and argument types. You might need
to add explicit type casts.
Query
select metric.created_at, jsb.key, jsb.value
from metric,
jsonb_each(data) as jsb
where user_id = <user_id>;
leads to the correct result: