SQL: cut a field, then search - sql

I would like to perform a "on the fly" modification of a field of a sqlite database, before doing a SELECT statement.
The field is called 'topic_simple', and it contains some text. Somewhere in the text, there is a kind of separator I included: 4 spaces: " ".
Here is one of my typical SELECT statement:
SELECT * FROM papers WHERE (topic_simple LIKE '% 3D print%')
I would like something like that:
SELECT * FROM papers WHERE ((topic_simple_before_4_spaces) LIKE '% 3D print%')
I DO NOT WANT to modify topic_simple in the database, I just want to make a select statement on a substring of this field.
How can I do that ?

LIKE is quite powerful. Why don't you just add the four spaces to your LIKE expression:
SELECT *
FROM papers
WHERE topic_simple LIKE '% 3D print% %';
Be aware that the text after your delimiter shouldn't contain the delimiter because then you'd possibly get unwanted lines. If your SQLite supports it, you can also use a regular expression.
In MYSQL you can directly "select" (or "extract") the text before your four spaces in the WHERE clause:
SELECT *
FROM papers
WHERE SUBSTRING(topic_simple, 1, LOCATE(' ', topic_simple) - 1) ...;

Related

Making a query which selects the news that contain a specific word

CREATE TABLE IF NOT EXISTS news (
title TEXT PRIMARY KEY,
newsletter_description TEXT NOT NULL
);
I need to write a query which selects all the news that contain the word "apple" or "watermelon"(or both) in their title or in their newsletter_description and I am not very sure about how I can do that. (case insensitive, it can also be "AppLe" or "WaterMelon")
SELECT * FROM NEWS
WHERE title LIKE "%apple%" OR
title LIKE "%watermelon%" OR
newsletter_description LIKE "%apple%" OR
newsletter_description LIKE "%watermelon%
SQlite implemented LIKE operator case insensitive for ASCII characters by default. Unless you use unicode characters in your text you can use above query.
However if you use unicode chars, using lower or upper functions doesn't work either. So there is no point in using lower or upper functions at all.
https://www.sqlite.org/c3ref/strlike.html
You can use « lower(title) like '%apple%' »
In fact the lower put all the field in minuscule, that help you to find the word needed without knowing how he is written
You can use like operator and to have case insensitive search you can either use lower or upper on the actual column and also have to convert the input to lower/upper before passing to the query accordingly,
select *
from news
where lower(newsletter_description) like '%watermelon%'
or lower(newsletter_description) like '%apple%'
or lower(title) like '%watermelon%'
or lower(title) like '%apple%';
Use a CTE that returns all the words that you search for and join it to the table:
with cte(word) as (values ('apple'), ('watermelon'))
select n.*
from news n inner join (select '%' || word || '%' word from cte) c
on n.title like c.word or n.newsletter_description like c.word
Naive way will be select * from new where lower(title) like ‘%apple%’ or lower(title) like ‘%watermelon%’ or lower(newsletter_description) like ‘%apple%’ or lower(newsletter_description) like ‘%watermelon%’;

Oracle sql queries

I am working on a small relational database for school and having trouble with a simple query. I am supposed to find all records in a table that have a field with the word 'OMG' somewhere in the text.
I have tried a few other and I can't figure it out. I am getting an invalid relational operator error.
my attempts:
select * from comments where contains('omg');
select * from comments where text contains('omg');
select * from comments where about('omg');
and several more variations of the above. As you can see I am brand spanking new to SQL.
text is the name of the field in the comments table.
Thanks for any help.
Assuming that the column name is text:
select * from comments where text like '%omg%';
The percentage % is a wild-card which means that any text can come before/after omg
Pay attention, if you don't want the results to contain words in which omg` is a substring - you might want to consider adding whitespaces:
select * from comments where text like '% omg %';
Of course that it doesn't cover cases like:
omg is at the end of the sentence (followed by a ".")
omg has "!" right afterwards
etc
You may want to use the LIKE operator with wildcards (%):
SELECT * FROM comments WHERE text LIKE '%omg%';

Search for “whole word match” with SQL Server LIKE pattern

Does anyone have a LIKE pattern that matches whole words only?
It needs to account for spaces, punctuation, and start/end of string as word boundaries.
I am not using SQL Full Text Search as that is not available. I don't think it would be necessary for a simple keyword search when LIKE should be able to do the trick. However if anyone has tested performance of Full Text Search against LIKE patterns, I would be interested to hear.
Edit:
I got it to this stage, but it does not match start/end of string as a word boundary.
where DealTitle like '%[^a-zA-Z]pit[^a-zA-Z]%'
I want this to match "pit" but not "spit" in a sentence or as a single word.
E.g. DealTitle might contain "a pit of despair" or "pit your wits" or "a pit" or "a pit." or "pit!" or just "pit".
Full text indexes is the answer.
The poor cousin alternative is
'.' + column + '.' LIKE '%[^a-z]pit[^a-z]%'
FYI unless you are using _CS collation, there is no need for a-zA-Z
you can just use below condition for whitespace delimiters:
(' '+YOUR_FIELD_NAME+' ') like '% doc %'
it works faster and better than other solutions. so in your case it works fine with "a pit of despair" or "pit your wits" or "a pit" or "a pit." or just "pit", but not works for "pit!".
I think the recommended patterns exclude words with do not have any character at the beginning or at the end. I would use the following additional criteria.
where DealTitle like '%[^a-z]pit[^a-z]%' OR
DealTitle like 'pit[^a-z]%' OR
DealTitle like '%[^a-z]pit'
I hope it helps you guys!
Surround your string with spaces and create a test column like this:
SELECT t.DealTitle
FROM yourtable t
CROSS APPLY (SELECT testDeal = ' ' + ISNULL(t.DealTitle,'') + ' ') fx1
WHERE fx1.testDeal LIKE '%[^a-z]pit[^a-z]%'
If you can use regexp operator in your SQL query..
For finding any combination of spaces, punctuation and start/end of string as word boundaries:
where DealTitle regexp '(^|[[:punct:]]|[[:space:]])pit([[:space:]]|[[:punct:]]|$)'
Another simple alternative:
WHERE DealTitle like '%[^a-z]pit[^a-z]%' OR
DealTitle like '[^a-z]pit[^a-z]%' OR
DealTitle like '%[^a-z]pit[^a-z]'
This is a good topic and I want to complement this to someone how needs to find some word in some string passing this as element of a query.
SELECT
ST.WORD, ND.TEXT_STRING
FROM
[ST_TABLE] ST
LEFT JOIN
[ND_TABLE] ND ON ND.TEXT_STRING LIKE '%[^a-z]' + ST.WORD + '[^a-z]%'
WHERE
ST.WORD = 'STACK_OVERFLOW' -- OPTIONAL
With this you can list all the incidences of the ST.WORD in the ND.TEXT_STRING and you can use the WHERE clausule to filter this using some word.
You could search for the entire string in SQL:
select * from YourTable where col1 like '%TheWord%'
Then you could filter the returned rows client site, adding the extra condition that it must be a whole word. For example, if it matches the regex:
\bTheWord\b
Another option is to use a CLR function, available in SQL Server 2005 and higher. That would allow you to search for the regex server-side. This MSDN artcile has the details of how to set up a dbo.RegexMatch function.
Try using charindex to find the match:
Select *
from table
where charindex( 'Whole word to be searched', columnname) > 0

MySQL match existence of a term amongst comma seperated values using REGEXP

I have a MySQL select statement dilemma that has thrown me off course a little. In a certain column I have a category term. This term could look something like 'category' or it could contain multiple CSV's like this: 'category, bank special'.
I need to retrieve all rows containing the term 'bank special' in the comma separated value. Currently I am using the following SQL statement:
SELECT * FROM tblnecklaces WHERE nsubcat REGEXP 'bank special';
Now this works OK, but if I had the category as follows: 'diamond special' for example then the row is still retrieved because the term 'special' in my column seems to be matching up to the term 'bank special' in my REGEXP statement.
How would I go abut checking for the existence of the whole phrase 'bank special' only and not partially matching the words?
Many thanks for your time and help
The simplest solution is to use the LIKE clause (% is wildcard):
SELECT * FROM tblnecklaces WHERE nsubcat LIKE '%bank special%';
Note that LIKE is also a lot faster than REGEXP.
You can prefix the column with comma's, and compare it to the bank special:
SELECT *
FROM tblnecklaces
WHERE ',' + replace(nsubcat,', ','') + ',' LIKE ',bank special,'
I put in a replace to remove optional space after a comma, because your example has one.
Not tested but this RegExp should work (LIKE works too but will match items that starts or ends with the same phrase):
SELECT * FROM tblnecklaces WHERE nsubcat REGEXP '(^|, )bank special($|,)';

SQL (MySQL): Match first letter of any word in a string?

(Note: This is for MySQL's SQL, not SQL Server.)
I have a database column with values like "abc def GHI JKL". I want to write a WHERE clause that includes a case-insensitive test for any word that begins with a specific letter. For example, that example would test true for the letters a,c,g,j because there's a 'word' beginning with each of those letters. The application is for a search that offers to find records that have only words beginning with the specified letter. Also note that there is not a fulltext index for this table.
You can use a LIKE operation. If your words are space-separated, append a space to the start of the string to give the first word a chance to match:
SELECT
StringCol
FROM
MyTable
WHERE
' ' + StringCol LIKE '% ' + MyLetterParam + '%'
Where MyLetterParam could be something like this:
'[acgj]'
To look for more than a space as a word separator, you can expand that technique. The following would treat TAB, CR, LF, space and NBSP as word separators.
WHERE
' ' + StringCol LIKE '%['+' '+CHAR(9)+CHAR(10)+CHAR(13)+CHAR(160)+'][acgj]%'
This approach has the nice touch of being standard SQL. It would work unchanged across the major SQL dialects.
Using REGEXP opearator:
SELECT * FROM `articles` WHERE `body` REGEXP '[[:<:]][acgj]'
It returns records where column body contains words starting with a,c,g or i (case insensitive)
Be aware though: this is not a very good idea if you expect any heavy load (not using index - it scans every row!)
Check the Pattern Matching and Regular Expressions sections of the MySQL Reference Manual.