How to check if array contains an item in JSON column using Sqlite? - sql

I'm using sqlite to store JSON data that I have no control over. I have a logs table that looks like this.
id
value
s8i13s85e8f34zm8vikkcv5n
{"key":["a","b"]}
m2abxfn2n9pkyc9kjmko5462
{"key": "sometext"}
Then I use the following query to get the rows where value.key contains a:
SELECT * FROM logs WHERE EXISTS (SELECT * FROM json_each(json_extract(logs.value,'$.key')) WHERE json_each.value = 'a')
The query works fine if key is an array or if it doesn't exist. But it fails if is a string (like the second row of the table)
The error I get is:
SQL error or missing database (malformed JSON)
And it is because json_each throws if the parameter is an string.
Because of the requirements I can't control the user data or the queries.
Ideally I would like to figure out a query that either doesn't fail or that detects that the value is a string instead of an array and uses LIKE to see if the string contains 'a'.
Any help would be appreciated. Happy holidays :)

Use a CASE expression in the WHERE clause which checks if the value is an array or not:
SELECT *
FROM logs
WHERE CASE
WHEN value LIKE '{"key":[%]}' THEN
EXISTS (
SELECT *
FROM json_each(json_extract(logs.value,'$.key'))
WHERE json_each.value = 'a'
)
ELSE json_extract(value,'$.key') = 'a'
END;
See the demo.

Related

json_remove is removing the wrong value from array on second run

I am trying to remove a value from a json array, however I am having issues.
First I insert the array into into the table like so:
INSERT into demo (hint) VALUES ('["Hello","World"]');
Next when I run this query, the World value gets removed which is what is supposed to happen. However if I run it a second time, then the Hello value gets removed which is not supposed to happen. What am I doing wrong, or what is a better way to remove items from a json array?
UPDATE demo SET hint = json_remove(
hint,
(SELECT json_each.fullkey FROM demo, json_each(demo.hint) WHERE json_each.value = 'World')
);
select * from demo;
The subquery that you use as the path argument of json_remove() returns null the 2nd time that you execute the update statement because there is no "World" in the json array.
In this case json_remove() also returns null.
If your version of SQLite is 3.33.0+ you can use the UPDATE...FROM syntax:
UPDATE demo AS d
SET hint = json_remove(d.hint, j.fullkey)
FROM json_each(d.hint) AS j
WHERE j.value = 'Hello';

How do I use the SQL Comparison Condition ANY/SOME with the DATATYPE Char

I'm new to SQL and I can't figure out how to use the ANY Operator with two Strings.
I want to get the results that match one of two strings.
I know that the result can be easily achieved by using IN/OR which I already did, but we were asked to do the same with ANY.
My Code looks like this:
SELECT * FROM table WHERE column = ANY ('ASD 357','GHJ 680')
I always get this error message:
SQL0104N An unexpected token "'ASD 357'" was found following
"column = ANY(". Expected tokens may include: "".
SQLSTATE=42601
What do I have to do to get this working?
The issue is not the ANY, it is the list. You want IN:
SELECT *
FROM table
WHERE column IN ('ASD 357', 'GHJ 680');
That is, this would also fail for an integer column:
WHERE column = ANY (1, 2, 3)
ANY would be fine if you had a subquery:
WHERE column = ANY (SELECT x FROM y)

How can I compare two columns for similarity in SQL Server?

I have one column that called 'message' and includes several data such as fund_no, detail, keywords. This column is in table called 'trackemails'.
I have another table, called 'sendemails' that has a column called 'Fund_no'.
I want to retrieve all data from 'trackemail' table that the column 'message' contains characters same as 'Fund_no' in 'trackemails' Table.
I think If I want to check the equality, I would write this code:
select
case when t.message=ts.fund_no then 1 else 0 end
from trackemails t, sendemails s
But, I do want something like below code:
select
case when t.message LIKE ts.fund_no then 1 else 0 end
from trackemails t, sendemails s
I would be appreciate any advice to how to do this:
SELECT *
FROM trackemails tr
INNER JOIN sendemail se on tr.Message like '%' + se.Fund_No + '%'
Dear Check SQL CHARINDEX() Function. This function finds a string in another string and returns int for the position they match. Like
SELECT CHARINDEX('ha','Elham')
-- Returns: 3
And as you need:
SELECT *
,(SELECT *
FROM sendemail
WHERE CHARINDEX(trackemails.Message,sendemail.Fund_No)>0 )
FROM trackemails
For more information, If you want something much better for greater purposes, you can use Fuzzy Lookup Component in SSDT SSIS. This Component gives you a new column in the output which shows the Percentages of similarity of two values in two columns.

String input matched against a binary field in SQL WHERE

Here is the scenario:
I have a SQL select statement that returns a binary data object as a string. This cannot be changed it is outside the area of what I can modify.
So for example it would return '1628258DB0DD2F4D9D6BC0BF91D78652'.
If I manually add a 0x in front of this string in a query I will retrieve the results I'm looking for so for example:
SELECT a, b FROM mytable WHERE uuid = 0x1628258DB0DD2F4D9D6BC0BF91D78652
My result set is correct.
However I need to find a Microsoft SQL Server 2008 compatible means to do this programatically. Simply concatenating 0x to the string variable does not work. Obvious, but I did try it.
Help please :)
Thank you
Mark
My understanding of your question is that you have a column uuid, which is binary.
You are trying to select rows with a particular value in uuid, but you are trying to use a string like so:
SELECT a, b FROM mytable WHERE uuid = '0x1628258DB0DD2F4D9D6BC0BF91D78652'
which does not work. If this is correct, you can use the CONVERT function with a style of 2 to have SQL Server treat the string as hex and not require a '0x' as the first characters:
SELECT a, b
FROM mytable
WHERE uuid = CONVERT(binary(16), '1628258DB0DD2F4D9D6BC0BF91D78652', 2)

Implement an IN Query using XQuery in MSSQLServer 2005

I'm trying to query an xml column using an IN expression. I have not found a native XQuery way of doing such a query so I have tried two work-arounds:
Implement the IN query as a concatenation of ORs like this:
WHERE Data.exist('/Document/ParentKTMNode[text() = sql:variable("#Param1368320145") or
text() = sql:variable("#Param2043685301") or ...
Implement the IN query with the String fn:contains(...) method like this:
WHERE Data.exist('/Document/Field2[fn:contains(sql:variable("#Param1412022317"), .)]') = 1
Where the given parameter is a (long) string with the values separated by "|"
The problem is that Version 1. doesn't work for more than about 50 arguments. The server throws an out of memory exception. Version 2. works, but is very, very slow.
Has anyone a 3. idea? To phrase the problem more complete: Given a list of values, of any sql native type, select all rows whose xml column has one of the given values at a specific field in the xml.
Try to insert all your parameters in a table and query using sql:column clause:
SELECT Mytable.Column FROM MyTable
CROSS JOIN (SELECT '#Param1' T UNION ALL SELECT '#Param2') B
WHERE Data.exist('/Document/ParentKTMNode[text() = sql:column("T")