Trying to filter a SQL query on a JSON field - sql

I have 4 tables in PostgreSQL:
HomeSearch(id, client_id, name)
HomeSearchNote(id, homesearch_id, text)
Client(id, user_id)
User(id)
I'm trying to query HomeSearch and return a JSON as follows but only for those entries in HomeSearch for which the Client.user_id is equal to a certain value (say, 100):
HomeSearch {
id:
name:
client: {
id:
user: {
id
}
}
notes: [{
id:
homesearch_id:
text:
},
...]
}
My SQL statement is:
SELECT
*,
( SELECT row_to_json(client) from client where homeSearch.client_id=client.id ) client,
( SELECT json_agg(row_to_json(homeSearchNote)) from homeSearchNote where homeSearchNote.homesearch_id=homeSearch.id) notes
FROM homeSearch
WHERE client->>'user_id'=100
LIMIT 5;
However, this returns:
ERROR: column "client" does not exist
LINE 19: WHERE client->>user_id=100
If I run the query without the WHERE clause in PGAdmin, I can clearly see a table with a 'client' column of type JSON.
Can anyone comment what would be the right way to place / write the WHERE clause ?
Much appreciated!

On way you can re-write the sql is as
With a as
(SELECT *,
( SELECT row_to_json(client) from client where homeSearch.client_id=client.id ) client,
( SELECT json_agg(row_to_json(homeSearchNote)) from homeSearchNote where homeSearchNote.homesearch_id=homeSearch.id) notes
FROM homeSearch
)
Select * from a WHERE client->>'user_id'=100
LIMIT 5;

Related

Parse Json - CTE & filtering

I need to remove a few records (that contain t) in order to parse/flatten the data column. The query in the CTE that creates 'tab', works independent but when inside the CTE i get the same error while trying to parse json, if I were not have tried to filter out the culprit.
with tab as (
select * from table
where data like '%t%')
select b.value::string, a.* from tab a,
lateral flatten( input => PARSE_JSON( a.data) ) b ;
;
error:
Error parsing JSON: unknown keyword "test123", pos 8
example data:
Date Data
1-12-12 {id: 13-43}
1-12-14 {id: 43-43}
1-11-14 {test12}
1-11-14 {test2}
1-02-14 {id: 44-43}
It is possible to replace PARSE_JSON(a.data) with TRY_PARSE_JSON(a.data) which will produce NULL instead of error for invalid input.
More at: TRY_PARSE_JSON

How To Query an array of JSONB

I have table (orders) with jsonb[] column named steps in Postgres db.
I need create SQL query to select records where Step1 and Step2 and Step3 has success status
[
{
"step_name"=>"Step1",
"status"=>"success",
"timestamp"=>1636120240
},
{
"step_name"=>"Step2",
"status"=>"success",
"timestamp"=>1636120275
},
{
"step_name"=>"Step3",
"status"=>"success",
"timestamp"=>1636120279
},
{
"step_name"=>"Step4",
"timestamp"=>1636120236
"status"=>"success"
}
]
table structure
id | name | steps (jsonb)
'Normalize' steps into a list of JSON items and check whether every one of them has "status":"success". BTW your example is not valid JSON. All => need to be replaced with : and a comma is missing.
select id, name from orders
where
(
select bool_and(j->>'status' = 'success')
from jsonb_array_elements(steps) j
where j->>'step_name' in ('Step1','Step2','Step3') -- if not all steps but only these are needed
);
You can use JSON value contain operation for check condition exist or not
Demo
select
*
from
test
where
steps #> '[{"step_name":"Step1","status":"success"},{"step_name":"Step2","status":"success"},{"step_name":"Step3","status":"success"}]'

How To Query A Repeated String Field With Empty Value [] in BigQuery?

New to the BigQuery, I have a repeated field in BigQuery, like this
myTable
{
"id": 12345
"myNestedStringArrayField": []
}
How can I query all rows with the myNestedStringArrayField value is empty?
I tried using myNestedStringArrayField is null, but return no results, I know I have rows that have [] as the value. I also tried using the = '[]' , but the query edit throws an error.
Thank you in advance.
You can try using ARRAY_LENGTH, all rows you are seeking have a myNestedStringArrayField with a length of zero:
WITH sample AS(
SELECT STRUCT("12345" AS id, [] AS myNestedStringArrayField) AS myTable
)
SELECT *
FROM sample
WHERE ARRAY_LENGTH(myTable.myNestedStringArrayField) = 0
This returns:

SQL to retrieve userid's from a json from a column in a table

I have a table with columns dep_id and dep_value.
dep_value has the data which is JsonData and it looks like this :
{
"users": [{
"uid": "0"
}, {
"uid": "1"
}, {
"uid": "2"
}]
}
I need a sql which can extract all the values .. 0,1,2
I tried using regex in SQL but I am not sure how to pattern match in SQL.
SELECT
REGEXP_count(dep_value,'uid') as user_count
FROM (
select dep_value from users where dep_id = '123'
)
;
I used this SQL to get the count of uid, similarly I need to get what uid's they are.
Prior to 12c, the module apex_json is useful to parse JSONs without relying on Regular expressions. Please refer to this answer to find a good example of the APEX_JSON module in action .
If your requirement is limited to only parse all the available uids from the json string regardless of what depth they reside within the JSON, a Regex solution like this may be used.
SELECT
REGEXP_SUBSTR(dep_value,'"uid" *?: *?"(\d+)"',1,level,null,1) as user_count
from users where dep_id = 123
connect by level <= REGEXP_COUNT(dep_value,'"uid" *?: *?"(\d+)"')
and prior dep_id = dep_id -- You may skip these 2 lines while
and prior sys_guid() is not null; --running for single, unique dep_id
Demo

how to specify literal value in linq union

I have the following SQL query, note I want the literal value '0' in the second
field in the second SELECT statement from the ItemSale table.
How do I express this in LINQ?
I get the error message 'Invalid anonymous type member declarator'.
SELECT BranchNumber,QuantitySold
FROM Department
UNION
SELECT BranchNumber,0
FROM ItemSale
How to express the '0' in LINQ?
var unionQuery = (from dept in Department
select new
{
dept.BranchNumber,
dept.QuantitySold,
})
.Concat(from item in ItemSale
select new
{
item.BranchNumber,
0
});
In LINQ, the field has to have a name that matches the corresponding field in the other anonymous type.
select new
{
item.BranchNumber,
QuantitySold=0
});