psql query not returning proper results? - node.js

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).

Related

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

Query which performs like and in operators

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' )

How to LOWER elements in postgresql array in SELECT statement to do case insensitive search

Can I lower the elements in an array column like I can a varchar or text column?
SELECT * FROM a_tbl a
WHERE LOWER(%(uw)s) = ANY (a.n_lst) -- how to lower?
OR LOWER(a.x) = LOWER(%(uw)s)
I saw in the documentation that I could use citext as my datatype. I might try to alter my table if there isn't a way to use LOWER
a_tbl
-----
id SERIAL PRIMARY KEY
n_lst TEXT[]
x VARCHAR(50)
You can do like below:
select lower('Jonh') = any(lower(n_lst::text)::text[]) from a_tbl;
How to lowercase postgresql array?
SELECT * FROM a_tbl a
WHERE LOWER(%(uw)s) ILIKE ANY (a.n_lst) -- how to lower?
OR LOWER(a.x) = LOWER(%(uw)s)

How do I properly escape the single quote in node-postgres queries?

I need to execute the following query:
db.query("SELECT * FROM items WHERE name ILIKE '%$1%';", [ query ])
It seems like node-postgres doesn't replace the $1 parameter and I don't know why. My query works if I change the line to:
db.query(`SELECT * FROM items WHERE name ILIKE '%${query}%';`)
But now I have problems when the query contains single quotes (').
Should I replace all single quotes using regex (as in query.replace(/'/g, "''")) (I don't think that's recommended)?
Otherwise, how can I get node-postgres to accept my parameter? I think it has something to do with the encapsulating % symbols. I keep running into the same problem with this issue.
Your placeholder isn't replaced because '%$1%' is an SQL string literal that just happens to look like it contains a $1 placeholder. You can add the percents in JavaScript using string operations:
db.query("SELECT * FROM items WHERE name ILIKE $1", [ `%${query}%` ])
// ---------------------------------------------------^^^^^^^^^^^^
or in SQL using SQL's string operations:
db.query("SELECT * FROM items WHERE name ILIKE '%' || $1 || '%'", [ query ])
// --------------------------------------------^^^^^^----^^^^^^

How to configure Presto searches to be case-insensitive?

In my case, Presto connects to a MySQL database which has been configured to be case-insensitive. But any search through Presto seems to be case-sensitive.
Questions:
1) Is there a way to configure Presto searches to be case-insensitive? If not, can something be changed in the Presto-MySQL connector to make the searches case-insensitive?
2) If underlying DB is case-insensitive, shouldn't Presto searches also be case-insensitive? (I presume that Presto only generates the query plan and the actual execution happens on the underlying database)
Example: Consider the below table on MySQL.
name
____
adam
Alan
select * from table where name like '%a%'
// returns adam, Alan on MySQL
// returns only adam on Presto
select * from table where name = 'Adam'
// returns adam on MySQL
// returns NIL on Presto
You have to explicitly ask for case-insensitive comparison by normalizing compared values either to-lower, or to-upper, like this:
select * from table where lower(name) like '%a%';
select * from table where lower(name) = lower('Adam');
You can use regexp_like(), and prepend the regexp with (?i) for case insensitivity
select
*
from table_name
where
regexp_like(column_name, '(?i)fOO'); -- column contains fOO or FOO
or
select
*
from table_name
where
regexp_like(column_name, '(?i)^Foo'); -- column starts with fOO or FOO

Resources