How to add new key inside json blob in a column in SQL - sql

I have a SQL table MYTABLE similar to the below example
id. config
123. {"location":zxc, 'zip_code':1234}
143. {"location":zxc, 'zip_code':1222}
I need to do a database migration where I add a key name inside the config JSON so the config becomes. {"name": "abc", "location":zxc, 'zip_code':1234}
I am not sure how to do this. I can do ALTER TABLE, ADD COLUMN but this is different than adding/removing a column.
Please suggest.
EDIT:
This is in Postgres

The jsonb_set() function can be used to add properties to the current JSON object in PostgreSql (details). So, for example, you can use the following to set the name property to a value of abc:
UPDATE mytable
SET config = jsonb_set(config, '{name}','"abc"', TRUE)
Where id=1

This can be done using an UPDATE statement:
update mytable
set config = config || '{"name": "abc"}' ;
The above assumes that config is defined as jsonb (which it should be). If it's a json column, you need to cast it: set config = config::jsonb || '{"name": "abc"}'

Since you say it's a migration, I am guessing you are copying rows from an old table to a new table. So, you can modify the value as you are inserting each row. (If you are keeping the same table, change the INSERT statement into an UPDATE statement.) If your JSON is really simple like in your example, then some simple string manipulation should be good enough.
insert NewTable (id, config)
select id,
'{"name": "' + name + '", ' + SUBSTRING(config, 2, DATALENGTH(config) - 1)
from OldTable;
I'm guessing name is another column in this table. If not, modify it to find the name from the right place.

Related

Is it possible to run a query to rename the fieldnames of each field?

I have like 20 datasets, each with 28 fields without the first row having fieldnames. So MS Access assigned 'Field1', 'Field2'.... 'Field28' as fieldnames for each column. I'd like to know if it is possible to run a query to rename them? I couldn't find any information online and I tried manually entering the names but it is taking too long.
Access SQL does not support changing the name of an existing field.
You could create a SELECT query and alias the field name:
SELECT Field1 AS FieldA FROM YourTable;
Then you would use the query instead of the table whenever you want to display the aliased name.
Or you could use a "make table" query to create a new table with the new field name:
SELECT Field1 AS FieldA INTO NewTable FROM YourTable;
Or you could execute an ALTER TABLE statement to add the new field, then an UPDATE to populate the new field with the old field data, and finally DROP the old field. But that seems like too much work.
Instead of SQL, consider using VBA to rename the field:
CurrentDb.TableDefs("YourTable").Fields("Field1").Name = "FieldA"

update a column using values from a different column of the same table

Given the DB table:
CREATE TABLE stuff (
id text not null,
other text
);
That has lots of id values but has all other set to NULL, is there an elegant way to update the table so that all other rows get updated to OTHER-{id} (where {id} is the value of the id column)?
(It must work in Postgresql)
Only a simple update statement is needed with some string concatenation (||):
update stuff
set other = 'OTHER-' || id
You'll want to use the following:
UPDATE stuff
SET other = 'OTHER-' || id;
UPDATE is the keyword used to identify which table you'd like to update.
SET is the keyword used to identify which column you'd like to update, and this is where you choose to assign the column to:
'OTHER-' || id
'OTHER-' being a string
|| a shorthand way to concatenate
id the value you want.
Another way of writing this would be
other = concat('OTHER-',id);
I along with many others will find the || method to be much cleaner, but it's worth knowing about the dedicated function as well.

update column with comma separated value

In my SQL table, I have a column named "user_id" with comma separated value like this: a,b,c,d and I just wonder how can I update this column without removing old values. I want to update this column to a,b,c,d,e and in other step to a,b,c,d,e,f.
I wrote this query, but it removes old values and does not not update values with comma separated list:
UPDATE multiusers SET user_id = '" . $userID . "' WHERE hwid = '" . $hwid."'
If you want to update a column and append a value just do :-
UPDATE multiusers
SET user_id = user_id + "new user"
WHERE hwid = $hwid
This just appends a value to the existing value in SQL SERVER db at least, other databases may have different concatenation methods. I think your questions points to a fundamental design issue in your database and I would suggest rethinking this.
You are treating a field as a table. Even when you can do, it's a very bad approach. You should have as many records on multiusers table as userid's you have. But if you insist in your approach then you will have to create a quite complex query to retrieve the value of userid field, move to an array and compare it with the new value to make sure you doesn't insert duplicates in the field. Something like a cursor may work for you.

How to write pgsql update query with string aggregate?

I have update query that will manually change the field value as a unique string, the table already have a lost of data and the id as unique Pkey.
So I need the names should look like
mayname-id-1,
mayname-id-2,
mayname-id-3, etc
I tried to update with string_agg, but that doesn't work in update queries
UPDATE mytable
SET name = string_agg('mayname-id-', id);
How to construct string dynamically in an update query?
How about the following:
UPDATE mytable
SET name = 'mayname-id-' || CAST(id AS text)
Typically, you should not add such a completely redundant column at all. It's cleaner and cheaper to generate it as functionally dependent value on the fly. You can use a view or a "generated column" for that. Details:
Store common query as column?
You can even have a unique index on such a functional value if needed.
Use string concatenation
UPDATE mytable SET name = 'nayname-id-' || (id :: text);

In sqlite How to add column in table if same column is not exists in table

How can I add a column in an SQLite table if and only if the same column does not exist in the table?
Using ALTER TABLE I am able to create a new column but want to know how to check whether that column already exists in the table or not?
SQLite returns an error like "no such column: foo" if the table doesn't contain the column:
select foo from yourTable limit 1
Also you can get the create-table statement:
select sql from sqlite_master where tbl_name = 'YourTableName'
and then parse the result, looking for the column-name. I don't know of an elegant way to query the list of columns for a specified table, though one may exist.
Also if you attempt to do this:
alter table YourTable add column foo {column-def whatever it is}
you get an error from SQLite if the column already exists. You could trap that error too.
Finally you could do this:
select sql from sqlite_master
where tbl_name = 'YOURTABLE' and sql like '%"foo" CHAR%'; -- or whatever type
and if the specified table contains the column which is surrounded by double-quotes in the query, and with the type you have specified, you will get a result, otherwise an empty set. Specifying the datatype ensures that your LIKE substring match occurs on a column-name.
There's no way (that I know of) to do it all in a single SQLite query. You must use application code to manage the If/Elseness.
Check if table exists or not:
select count(*) from sqlite_master where type = 'table' and name = MyTable';
Check if column exists in table or now
pragma table_info(thumbnail);
However, a better approach may be explicit database schema updates based on schema versions your application maintains (e.g. specific alter table statement to go from schema version 1 to 2):
pragma user_version;
It seems like that it is impossible to do checking if the column not exists and addindg the new column in one command, because Sqlite don't support "IF NOT EXISTS" for column. "IF NOT EXISTS" works only on table.
Here is what I will do:
rev = ExecuteStatement("SELECT columnNamexx FROM tableNamexx limit 1;");
if(rev != SQLITE_OK){ // add col to table
ExecuteStatement("ALTER TABLE tableNamexx ADD COLUMN columnNamexx INTEGER DEFAULT 0;");
}
You can view the table columns by using '.schema tableName'