Query which performs like and in operators - presto

I am trying to run a Athena query which will match multiple values for a column. So the query is like this. So here the event name will be 'n' number of events in string with comma seperated.
eventname = "ExecuteQuery, ErrorOccured, RunningStatus, AbortStatus"
SELECT * FROM "db_name"."table_name" where account='123456' and year='2010' and month='04' and day = '1'
and (eventname like '%Execute%' or eventname like'%Error%' or eventname like '%Running%' or eventname like '%...%')
So basically I want query to perform LIKE and IN operator
How can I write the sql query with operator which has n number of events.
I tried with 'IN' operator. But didnt get desired output.
SELECT * FROM "db_name"."table_name" where account='123456' and year='2010' and month='04' and day = '1'
and (eventname in ('Execute%', '%Error%', 'Running%')
Also tried with below query and it throws error as Function any not registered
SELECT * FROM "db_name"."table_name" where account='123456' and and year='2020' and month='04' and day = '1'
and eventname LIKE ANY (ARRAY['%Execute%', 'Error%']);

you could use regexp_like, for example
select * from table where regexp_like(eventname, 'Execute|Error|Running' )

Related

How to log parameters instead of placeholders using sqlx with Postgres?

I'm using sqlx for the first time today.
I'm having really hard time understanding my SQL errors because I cannot copy & paste logged queries in my IDE because the parameters are not converted from placeholders.
It prints:
SELECT * from players where team_id = $1 AND id = $2
but I would like the below instead:
SELECT * from players where team_id = 'ABC' AND id = '123'
How to do this?

Count distinct doesn't work when using OrderBy & join

I have the following query trying to get count of a query:
var testQuery = Db
.From<Blog>()
.LeftJoin<BlogToBlogCategory>()
.Where(x => x.IsDeleted == false)
.OrderBy(x => x.ConvertedPrice);
var testCount = Db.Scalar<int>(testQuery.Select<Blog>(x => Sql.CountDistinct(x.Id)));
var results = Db.LoadSelect(testQuery.SelectDistinct());
It gives error:
42803: column "blog.converted_price" must appear in the GROUP BY clause or be used in an aggregate function
Issue seems to be the orderby statement. If I remove it then the error goes away. Why does this stop count distinct working?
I am having to clear orderby on all queries I do like this. Is it supposed to work this way?
Also I just realised count is wrong. Results is 501 unique records and testCount is 538.
What am I doing wrong?
Whenever in doubt with what an OrmLite query is generating, you can use the BeforeExecFilter to inspect the DB command before its executed or to just output the query to the Console you can use:
OrmLiteUtils.PrintSql();
You shouldn't be using OrderBy with aggregate scalar functions like COUNT which is meaningless and will fail in your case because it needs to included the GROUP BY clause for joined table queries.
Your specifically querying for COUNT(DISTINCT Id) if you wanted the row count for the query you can instead use:
var testCount = Db.RowCount(testQuery);
If you wanted to use COUNT(*) instead, you can use:
var testCount = Db.Count(testQuery);

How to construct a `select ... in` SQL query in nim?

I'm using nim and db_sqlite to fetch some rows with certain _ids from a database table. For example:
for row in db.fastRows("SELECT * FROM t WHERE _id IN (?, ?)", #["1", "2"]):
echo row
This works as expected, however, the sequence at the end is constructed dynamically at runtime, which means I need a variable amount of ? in the query. I end up creating a sequence with question marks, joining them, interpolating the string and turning it into a database query:
var qs : seq[string]
for id in ids:
qs.add("?")
let query_string = """SELECT * FROM t WHERE _id IN ($1)""" % join(qs, ",")
let query = SqlQuery(query_string)
for row in db.fastRows(query, ids):
echo row
Is there a better way to construct a select ... in query in nim? Ideally one with just one ? in the SqlQuery.
(For what it's worth, the current behavior is similar to other languages I've used)
you could do the replacement manually, here's one way using strformat and map
import strformat,db_sqlite,sequtils,strutils
#assuming ids is a seq[string] here
let query = sql(&"SELECT * FROM t WHERE _id IN ({ids.map(dbQuote).join(\",\")})")
for row in db.fastRows(query):
echo row

Dynamic variable parameter in static mysql query using groovy soap ui

I would like to generate the query that results for the BeneficiaryID 'ABC123' along with some other inputs if they were also given. Suppose if the currency value is given, I would like to include the Currency condition as well in the JOIN query, so as well the Category. I have the following code snippet in the SOAP UI Groovy script.
query= " CORR.BeneficiaryID LIKE 'ABC123'"
if (currencyValue!=""){
query=query + " and CORR.Currency LIKE '${currencyValue}'"
}
if (CategoryValue!=""){
query=query + " and CORR.Category LIKE '${CategoryValue}'"
}
log.info("Query" + query)
Outputrows = sql.rows("select CORR.Preferred as preferred ,CORR.Category as category,CORR.Currency as currency\
from BENEFICIARY CORR \
JOIN LOCATION LOC on CORR.UID=LOC.UID and ${query}
log.info("Output rows size" + Outputrows.size())
When currency and category are not given, I would like to have the following query run and get me the results.
select CORR.Preferred as preferred ,CORR.Category as category,CORR.Currency as currency\
from BENEFICIARY CORR \
JOIN LOCATION LOC on CORR.UID=LOC.UID and CORR.BeneficiaryID LIKE 'ABC123'
and when the currency and category are given(say USD & Commercial), then the following query.
select CORR.Preferred as preferred ,CORR.Category as category,CORR.Currency as currency\
from BENEFICIARY CORR \
JOIN LOCATION LOC on CORR.UID=LOC.UID and CORR.BeneficiaryID LIKE 'ABC123' and CORR.Currency LIKE 'USD' and CORR.Category LIKE 'Commercial'
All I could see on the result for Outputrows.size() is zero(0).
Can you please correct me where am I doing wrong.
Thanks.
Here is changed script.
Since the issue to just build query, only putting that part remove sql execution part as that is not really the issue.
//Define the values or remove if you get those value from somewhere else
//Just put them here to demonstrate
//You may also try by empty value to make sure you are getting the right query
def currencyValue = 'USD'
def categoryValue = 'Commercial'
def query = 'select CORR.Preferred as preferred, CORR.Category as category,CORR.Currency as currency from BENEFICIARY CORR JOIN LOCATION LOC on CORR.UID = LOC.UID and CORR.BeneficiaryID LIKE \'ABC123\''
currencyValue ? (query += " and CORR.Currency LIKE '${currencyValue}'") : query
categoryValue ? (query += " and CORR.Category LIKE '${categoryValue}'") : query
log.info "Final query is \n ${query}"
You can just pass query to further where you need to run the sql, say sql.rows(query)
You may quickly try Demo

psql query not returning proper results?

var searchValue = 'shahid';
var query = ("select * from students where name ilike '%"+searchValue+"%'");
This is my psql query, but it is not returning any values. So that I just console the query to know the execution.
The query is executing as:
select * from students where name ilike 'hahid%'
When I capitalize the first letter of search value (Shahid), it's executing perfectly.
If you want to pass in the upper case you should convert the variable searchValue
eg.
var newSearchValue = (select initcatp(searchValue)) ;
This will convert 'shahid' to 'Shahid' Then use this in your query variable.
This, lacking a '%' on the left hand side, will only match thing that start with hahid
select * from students where name ilike 'hahid%'
It's not the same as this
select * from students where name ilike 'Shahid%'
which will match only things that start with Shahid. Now if you want something that will match anything with hahid then you want
select * from students where name ilike '%hahid%'
BTW, your example is extremely insecure if searchValue comes from I/O (user, file, network etc).

Resources