SQL statement that checks if a table value is contained within a string I send it - sql

I know about the LIKE operator, but for what im trying to do, I would need to swap the column with the value, which didn't work.
Im using this in a discord bot that is connected to a database with a table. The table has two columns, keyword and response. I need a query that could give me the response when a given string contains the keyword.
SELECT response FROM Reply WHERE (insert something here to see if provided string
contains table value)

Use of the SQL tag indicates your question relates to standard SQL (hover over the tag and read it).
LIKE cannot be used for your purpose because the standard is quite clear on what you can specify :
<character like predicate> ::=
<row value predicand> <character like predicate part 2>
<character like predicate part 2> ::=
[ NOT ] LIKE <character pattern> [ ESCAPE <escape character> ]
Therefore you can't WHERE 'myliteral' LIKE colname.
So you'd need a scalar function, but I am not aware of any scalar function defined in the standard that you can use for this purpose.
So you are confined to scalar functions offered by your particular DBMS. E.g. in DB2, there is POSSTR(source_string, search_string) that you could use as POSSTR('myliteral', colname).

Select top 1 response
from Reply t
where concat('%',keyword,'%') like '<user provided text>'
--using % let check if the keyword is 'contained' in user's text
PS CONCAT used this way works on SQLSERVER check the correspondence for the dbms you're using, also top1 stops the query once it finds the first keyword

Related

In a Rails WHERE LIKE query, what does the percent sign mean?

In a simple search like this:
find.where('name LIKE ?', "%#{search}%")
I understand that #{search} is just string interpolation. What do the % symbols do?
The percent sign % is a wildcard in SQL that matches zero or more characters. Thus, if search is "hello", it would match strings in the database such as "hello", "hello world", "well hello world", etc.
Note that this is a part of SQL and is not specific to Rails/ActiveRecord. The queries it can be used with, and the precise behavior of LIKE, differ based on SQL dialect (MySQL, PostgreSQL, etc.).
search = 'something'
find.where('name LIKE ?', "%#{search}%")
In your DB it will be interpreted as
SELECT <fields> FROM finds WHERE name LIKE '%something%';
The percent sign in a like query is a wildcard. So, your query is saying "anything, followed by whatever is in the search variable, followed by anything".
Note that this use of the percent sign is part of the SQL standard and not specific to Rails or ActiveRecord. Also be aware that this kind of search does note scale well -- your SQL db will be forced to scan through every row in the table trying to find matches rather than being able to rely on an index.

DB2 complex like

I have to write a select statement following the following pattern:
[A-Z][0-9][0-9][0-9][0-9][A-Z][0-9][0-9][0-9][0-9][0-9]
The only thing I'm sure of is that the first A-Z WILL be there. All the rest is optional and the optional part is the problem. I don't really know how I could do that.
Some example data:
B/0765/E 3
B/0765/E3
B/0764/A /02
B/0749/K
B/0768/
B/0784//02
B/0807/
My guess is that I best remove al the white spaces and the / in the data and then execute the select statement. But I'm having some problems writing the like pattern actually.. Anyone that could help me out?
The underlying reason for this is that I'm migrating a database. In the old database the values are just in 1 field but in the new one they are splitted into several fields but I first have to write a "control script" to know what records in the old database are not correct.
Even the following isn't working:
where someColumn LIKE '[a-zA-Z]%';
You can use Regular Expression via xQuery to define this pattern. There are many question in StackOverFlow that talk about patterns in DB2, and they have been solved with Regular Expressions.
DB2: find field value where first character is a lower case letter
Emulate REGEXP like behaviour in SQL

SQLite: reuse quoted alias

I'd like to reuse an alias that contains a non-alphabetic character in a query, something like:
SELECT 42 AS "the#answer", "the#answer"+8 AS "fifty";
Output I want: 42|50; output I get: 42|8.
I've tried almost every possible combination of quote types, and looked for documentation, but I can't seem to find a working solution.
Any idea?
SQL cannot refer to an alias from the same output clause in which it was introduced. (It has nothing to do with quoting, which only allows otherwise invalid identifiers; some SQL vendors would have thrown an error, but SQLite appears "more relaxed" in the handling of this case.)
You could use a nested query (sqlfiddle).
SELECT fortytwo, fortytwo + 8 as fifty
FROM (
SELECT 42 AS fortytwo)
This works because the referenced identifier, fortytwo, was introduced in a "previous" output clause.

String matching in Peewee (SQL)

I am trying to query in Peewee with results that should have a specific substring in them.
For instance, if I want only activities with "Physics" in the name:
schedule = Session.select().join(Activity).where(Activity.name % "%Physics%").join(Course).join(StuCouRel).join(Student).where(Student.id == current_user.id)
The above example doesn't give any errors, but doesn't work correctly.
In python, I would just do if "Physics" in Activity.name, so I'm looking for an equivalent which I can use in a query.
You could also use these query methods: .contains(substring), .startswith(prefix), .endswith(suffix).
For example, your where clause could be:
.where(Activity.name.contains("Physics"))
I believe this is case-insensitive and behaves the same as LIKE '%Physics%'.
Quick answer:
just use Activity.name.contains('Physics')
Depending on the database backend you're using you'll want to pick the right "wildcard". Postgresql and MySQL use "%", but for Sqlite if you're performing a LIKE query you will actually want to use "*" (although for ILIKE it is "%", confusing).
I'm going to guess you're using SQLite since the above query is failing, so to recap, with SQLite if you want case-sensitive partial-string matching: Activity.name % "*Physics*", and for case-insensitive: Activity.name ** "%Physics%".
http://www.sqlite.org/lang_expr.html#like

How to implement "like" in BigQuery?

I am trying to run a simple query making a restriction of like % in BigQuery, but LIKE is not in their syntax, so how can it be implemented?
You can use the REGEXP_MATCH function (see the query reference page):
REGEXP_MATCH('str', 'reg_exp')
Instead of using the % syntax used by LIKE, you should use regular expressions (detailed syntax definition here)
LIKE is officially supported in BigQuery Standard SQL -
https://cloud.google.com/bigquery/docs/reference/standard-sql/functions-and-operators#comparison_operators
And I think it also works in Legacy SQL!
REGEXP_MATCH returns true if str matches the regular expression. For string matching without regular expressions, use CONTAINS instead of REGEXP_MATCH.
https://developers.google.com/bigquery/docs/query-reference#stringfunctions
REGEXP_MATCH is great if you know how to use it, but for those who aren't sure there won't be any commonly used special characters such as '.','$' or '?' in the lookup string, you can use LEFT('str', numeric_expr) or RIGHT('str', numeric_expr).
ie if you had a list of names and wanted to return all those that are LIKE 'sa%'
you'd use:
select name from list where LEFT(name,2)='sa'; (with 2 being the length of 'sa')
Additionally, if you wanted to say where one column's values are LIKE another's, you could swap out the 2 for LENGTH(column_with_lookup_strings) and ='sa' for =column_with_lookup_strings, leaving it looking something like this:
select name from list where LEFT(name,LENGTH(column_with_lookup_strings))= column_with_lookup_strings;
https://cloud.google.com/bigquery/query-reference