How to replace all null with empty String on mysql - mysql

Good day,
is there a way to do a coalesce once and replace all posible null column with empty string or the one you set.
suppose to be the way its done is like
select coalesce(col1,'') as col1, coalesce(col2,'') as col2, coalesce(col3,'') as col3 from table1
is there a way to do this more easily as I have to convert most of my queries into this to replace null fields with " " empty string..
something like
select coalesce(*,'') from tablename where col1=1
it really looks wrong though. but you'll get the idea
currently Im using laravel query
eg.
$data = DB::table('table_name)->where('col1',1)->get();
this converts to "select * from table_name where col1=1";
and result is an array of object:
[{
"id": 319,
"owner": 830,
"name": "new items22",
"date_added": "2017-10-05 22:12:59",
"last_modified": null,
"schedule": 54,
"day_index": 0,
"day": "Sunday",
"type": null,
"open": null,
"close": null,
"special": "closed"
},
{
"id": 320,
"owner": 830,
"name": "another ITEM",
"date_added": "2017-10-05 22:12:59",
"last_modified": null,
"schedule": 54,
"day_index": 1,
"day": "Monday",
"type": null,
"open": "09:00:00",
"close": "17:00:00",
"special": "open"
}]
but what I want to achieve is instead of having a null value, replace it with "" or emptry string.

I suggest that you set your default value on your database or make your custom default value.
I hope this will help.

Related

Oracle JSON api - update single record in json collection

I have CLOB field with JSON data :
[
{
"name": "Rahul",
"LName": "Sharma",
"salary": "20000",
"Age": "35"
},
{
"name": "Kunal",
"LName": "Vohra",
"salary": "10000",
"Age": "25"
}
]
and I need update value in only one element of that array, for example in record with name: Kunal I need change salary.
I try json_transform() but with this I transform every field salary to new value.
json_transform(json_field_in_table, SET '$.salary' = 15000)
You may use filter expression in JSON path of json_transform function to update specific objects:
with a(col) as (
select q'$[
{
"name": "Rahul",
"LName": "Sharma",
"salary": "20000",
"Age": "35"
},
{
"name": "Kunal",
"LName": "Vohra",
"salary": "10000",
"Age": "25"
}
]$' from dual
)
select
json_transform(
col,
set '$[*]?(#.name == "Kunal").salary' = '100'
) as res
from a
RES
[{"name":"Rahul","LName":"Sharma","salary":"20000","Age":"35"},{"name":"Kunal","LName":"Vohra","salary":"100","Age":"25"}]
fiddle
Note that "10000" is a string in JSON, numbers should be used without quotes: {"salary: 10000}
You can't use json_transform because json_transform, json_exists... evaluate on the whole JSON document not on pieces of it,
even a json_exists with "'$?(#.name == "Kunal")'" will consider that the whole document matches and then update all "salary" fields.
(https://docs.oracle.com/en/database/oracle/oracle-database/12.2/adjsn/condition-JSON_EXISTS.html#GUID-8A0043D5-95F8-4918-9126-F86FB0E203F0)
but you can:
select json_arrayagg(json_object (
'name' value name,
'LName' value lname,
'salary' value case when name = 'Kunal' then 15000 else salary end,
'Age' value age)) as js
from
json_table(q'~[
{
"name": "Rahul",
"LName": "Sharma",
"salary": "20000",
"Age": "35"
},
{
"name": "Kunal",
"LName": "Vohra",
"salary": "10000",
"Age": "25"
}
]~','$[*]'
columns (
name VARCHAR2(64) path '$.name',
LName VARCHAR2(64) path '$.LName',
salary NUMBER path '$.salary',
age NUMBER path '$.Age'
));

How to write JSON to Mysql?

sorry for my bad english.
I am inserting a json into mysql like this:
set #json = '[{"name":"ivan","city":"london","kurs":"1", },{"name":"lena","city":"tokio","kurs":"5"},{"name":"misha","city":"kazan","kurs":"3"}]';
select * from json_table(#json,'$[*]' columns(name varchar(20) path '$.name',
city varchar(20) path '$.city',
kurs varchar(20) path '$.kurs')) as jsontable;
But now there is a task to insert an unknown number of additional properties:
set #json = '[{"name":"ivan","city":"london","kurs":"1","options": [{
"ao_id": 90630,
"name": "Высота предмета",
"value": "3.7 см"
}, {
"ao_id": 90673,
"name": "Ширина предмета",
"value": "4 см"
}, {
"ao_id": 90745,
"name": "Ширина упаковки",
"value": "4 см"
}]},{"name":"lena","city":"tokio","kurs":"5", "options": [{
"ao_id": 90630,
"name": "Высота предмета",
"value": "9.7 см"
}]},{"name":"misha","city":"kazan","kurs":"3", "options": [{
"ao_id": 90999,
"name": "Высота",
"value": "5.7 см"
}]}]';
How can I best do this so that I can access the table in the future (search, index, output)?

How do you use JSON_QUERY with null json array inside of json object?

SELECT JSON_query([json], '$') from mytable
Returns fine the contents of [json] field
SELECT JSON_query([json], '$.Guid') from mytable
Returns null
SELECT JSON_query([json], '$.Guid[1]') from mytable
Returns null
I've also now tried:
SELECT JSON_query([json], '$[1].Guid')
SELECT JSON_query([json], '$[2].Guid')
SELECT JSON_query([json], '$[3].Guid')
SELECT JSON_query([json], '$[4].Guid')
and they all return null
So I'm stuck as to figuring out how create the path to get to the info. Maybe SQL Server json_query can't handle the null as the first array?
Below is the string that is stored inside of the [json] field in the database.
[
null,
{
"Round": 1,
"Guid": "15f4fe9d-403c-4820-8e35-8a8c8d78c33b",
"Team": "2",
"PlayerNumber": "78"
},
{
"Round": 1,
"Guid": "8e91596b-cc33-4ce7-bfc0-ac3d1dc5eb67",
"Team": "2",
"PlayerNumber": "54"
},
{
"Round": 1,
"Guid": "f53cd74b-ed5f-47b3-aab5-2f3790f3cd34",
"Team": "1",
"PlayerNumber": "23"
},
{
"Round": 1,
"Guid": "30297678-f2cf-4b95-a789-a25947a4d4e6",
"Team": "1",
"PlayerNumber": "11"
}
]
You need to follow the comments below your question. I'll just summarize them:
Probably the most appropriate approach in your case is to use OPENJSON() with explicit schema (the WITH clause).
JSON_QUERY() extracts a JSON object or a JSON array from a JSON string and returns NULL. If the path points to a scalar JSON value, the function returns NULL in lax mode and an error in strictmode. The stored JSON doesn't have a $.Guid key, so NULL is the actual result from the SELECT JSON_query([json], '$.Guid') FROM mytable statement.
The following statements provide a working solution to your problem:
Table:
SELECT *
INTO Data
FROM (VALUES
(N'[
null,
{
"Round": 1,
"Guid": "15f4fe9d-403c-4820-8e35-8a8c8d78c33b",
"Team": "2",
"PlayerNumber": "78",
"TheProblem": "doesn''t"
},
{
"Round": 1,
"Guid": "8e91596b-cc33-4ce7-bfc0-ac3d1dc5eb67",
"Team": "2",
"PlayerNumber": "54"
},
{
"Round": 1,
"Guid": "f53cd74b-ed5f-47b3-aab5-2f3790f3cd34",
"Team": "1",
"PlayerNumber": "23"
},
{
"Round": 1,
"Guid": "30297678-f2cf-4b95-a789-a25947a4d4e6",
"Team": "1",
"PlayerNumber": "11"
}
]')
) v (Json)
Statements:
SELECT j.Guid
FROM Data d
OUTER APPLY OPENJSON(d.Json) WITH (
Guid uniqueidentifier '$.Guid',
Round int '$.Round',
Team nvarchar(1) '$.Team',
PlayerNumber nvarchar(2) '$.PlayerNumber'
) j
SELECT JSON_VALUE(j.[value], '$.Guid')
FROM Data d
OUTER APPLY OPENJSON(d.Json) j
Result:
Guid
------------------------------------
15f4fe9d-403c-4820-8e35-8a8c8d78c33b
8e91596b-cc33-4ce7-bfc0-ac3d1dc5eb67
f53cd74b-ed5f-47b3-aab5-2f3790f3cd34
30297678-f2cf-4b95-a789-a25947a4d4e6

SQL OPENJSON is not returning the values from sub-arrays

I have a JSON file that is properly formatted according to the Microsoft ISJSON function. However, it refuses to return a value from the nested array.
Here is an excerpt from the JSON file.
I want to return the following fields: id, symbol, name, and price.
I can get the first three, but the price always shows up null in the SQL query results.
JSON FILE SNIPPET:
{
"status": {
"timestamp": "2021-01-06T07:14:42.132Z",
"error_code": 0,
"error_message": null,
"elapsed": 14,
"credit_count": 1,
"notice": null,
"total_count": 4180
},
"data": [
{
"id": 1,
"name": "Bitcoin",
"symbol": "BTC",
"slug": "bitcoin",
"num_market_pairs": 9772,
"date_added": "2013-04-28T00:00:00.000Z",
"tags": [
"mineable",
"pow",
"sha-256",
"store-of-value",
"state-channels"
],
"max_supply": 21000000,
"circulating_supply": 18592156,
"total_supply": 18592156,
"platform": null,
"cmc_rank": 1,
"last_updated": "2021-01-06T07:13:02.000Z",
"quote": {
"USD": {
"price": 36248.609255662224,
"volume_24h": 225452557837159.16,
"percent_change_1h": 2.74047145,
"percent_change_24h": 19.54362963,
"percent_change_7d": 29.31750604,
"market_cap": 673939798064.3159,
"last_updated": "2021-01-06T07:13:02.000Z"
}
}
}
Here is the SQL Query that I'm using:
DECLARE #JSON VARCHAR(MAX)
SELECT #JSON = BulkColumn
FROM OPENROWSET
(BULK 'C:\TSP\output.json', SINGLE_CLOB) AS j
Select iif(ISJSON(#JSON)=1,'YES','NO') JSON_OK
Select * FROM OPENJSON (#JSON, '$.data')
WITH (
id int
,symbol varchar(20)
,[name] varchar(50)
,price float '$.data.quote.USD[0]'
)
I've tried everything I can think of to get the price to appear, but I'm missing something as it's not cooperating. Also, I set the database compatibility level to 130 as I read that could be the problem.... Still no luck.
Any help would be much appreciated.
$.data.quote.USD is not an array, it's a set of properties. It's also already inside the $.data context so should not include data in its path. Try the following instead:
select *
from openjson(#JSON, '$.data') with
(
id int
,symbol varchar(20)
,[name] varchar(50)
,price float '$.quote.USD.price'
)

Postgres get search and get multiple array json to each row

I wants to get all subscriptions with interval "1 WEEK" from the following 'data' column
[
{
"id": "tran_6ac25129951962e99f28fa488993",
"amount": 1200,
"client": {
"id": "client_622bdf4cce2351f28243",
"subscription": [
{
"id": "sub_a67d59efb2bcbf73485a",
"amount": 3900,
"currency": "USD",
"interval": "1 WEEK"
},
{
"id": "sub_a67d59efb2bcbf73485a",
"amount": 3900,
"currency": "USD",
"interval": "1 WEEK"
}
]
},
"currency": "USD"
},
{
"id": "tran_xxxxxxx",
"amount": 1200,
"client": {
"id": "client_xxxxxx8243",
"subscription": [
{
"id": "sub_xxefb2bcbf73485a",
"amount": 3900,
"currency": "USD",
"interval": "1 Year"
},
{
"id": "sub_yyyyyb2bcbf73485a",
"amount": 3900,
"currency": "USD",
"interval": "1 WEEK"
}
]
},
"currency": "USD"
}
]
My table structure:
CREATE TABLE transactions
(
data json,
id bigserial NOT NULL,
created_date time without time zone,
CONSTRAINT transactions_pkey PRIMARY KEY (id)
)
In output I wants to get all "1 WEEk" subscription as rows. Above data should give 3 rows
I am using Postgres 9.3+
Its a nested query and I have tried writing it in as readable form as I can. I hope you can understand it -
select subscriptions from
(
select
cast
(
json_array_elements
(
json_array_elements(data)->'client'->'subscription'
)
as text
)
as subscriptions,
json_array_elements
(
json_array_elements(data)->'client'->'subscription'
)
->>'interval'
as intervals
from
transactions
)
as
xyz
where
intervals = '1 WEEK';
For information regarding these functions, you can refer to -
http://www.postgresql.org/docs/9.3/static/functions-json.html
Edit:-
As per performance requirements, I guess this will work better than the previous one -
select * from (
select cast (
json_array_elements (
json_array_elements(data)->'client'->'subscription'
) as text
) as subscription from transactions
) as temp
where subscription LIKE '%"interval":"1 WEEK"%';