SQL SELECT LIKE containing only specific words - sql

I have this query:
SELECT * FROM mytable
WHERE column1 LIKE '%word1%'
AND column1 LIKE '%word2%'
AND column1 LIKE '%word3%'
I need to modify this query to return records for which column1 contains word1 word2 and word3 and nothing else! no other words, just these words.
Example: searching for samsung galaxy s3 should return any combination of samsung s3 galaxy but NOT samsung galaxy s3 lte

Assuming that column1 contains space separated words, and you only want to match on whole words, something like:
SELECT * FROM
(select ' ' + REPLACE(column1,' ',' ') + ' ' as column1 from mytable) t
WHERE
column1 like '% word1 %' AND
column1 like '% word2 %' AND
column1 like '% word3 %' AND
REPLACE(REPLACE(REPLACE(column1,
' word1 ',''),
' word2 ',''),
' word3 ','') = ''
Note that this construction does allow the same word to appear multiple times. It's not clear from the question whether that should be allowed. (Fiddle)
It would be a far better design if these words were stored as separate rows in a separate table that relates back to mytable. We could then use more normal SQL to satisfy this query. Your example looks like it's some kind of tagging example. Having a table storing each tag as a separate row (with an ordinal position also recorded, if required) would turn this into a simple relational division problem.
A way to count how many times a word appears in a column is the expression:
(LEN(column2) - LEN(REPLACE(column2,'word',''))/LEN('word')
but this would again revert back to matching subsequences of larger words as well as the word itself, without more work.

Try This
SELECT * FROM mytable
WHERE column1 LIKE 'word1'
AND column1 LIKE 'word2'
AND column1 LIKE 'word3'

in MySQL you can use regexp as
SELECT * FROM mytable
WHERE column1 regexp '^word[1-3]$';
in postgres you can use 'similar to' key word
i think oracle also has regexp

Related

How do I compare multiple fields to multiple substrings?

I'm working on a Presto query that checks multiple fields against multiple substrings to see if at least one field contains any of the given substrings. For example, let's say I want to check if either column1, column2, or column3 contain test, inactive, or deprecated.
I could write multiple LIKE comparisons for each field and substring, but it seems a bit repetitive.
-- Functional, but cumbersome
SELECT *
FROM table
WHERE
column1 LIKE '%test%' OR column1 LIKE '%inactive%' OR column1 LIKE '%deprecated%'
OR column2 LIKE '%test%' OR column2 LIKE '%inactive%' OR column2 LIKE '%deprecated%'
OR column3 LIKE '%test%' OR column3 LIKE '%inactive%' OR column3 LIKE '%deprecated%'
I can simplify it a bit with regexp_like() but it's still a bit repetitive.
-- Functional, less cumbersome
SELECT *
FROM table
WHERE
REGEXP_LIKE(column1, 'test|inactive|deprecated')
OR REGEXP_LIKE(column2, 'test|inactive|deprecated')
OR REGEXP_LIKE(column3, 'test|inactive|deprecated')
Ideally I'd like to have a single comparison that covers each field and substring.
-- Non functional pseudocode
SELECT *
FROM table
WHERE (column1, column2, column3) LIKE ('%test%', '%inactive%', '%deprecated%')
Is there a simple way to compare multiple fields to multiple substrings?
You could search on a concatenation of the three columns.
SELECT *
FROM table
WHERE
REGEXP_LIKE(column1+' ' + column2+' ' +column3, 'test|inactive|deprecated')
Also you could put the words your matching against as rows in a new MatchWord table, then be able to add/remove words without changing your query.
SELECT
*
FROM
Data d
WHERE
EXISTS(
SELECT
*
FROM MatchWord w
WHERE
d.column1+' ' +d.column2+' ' +d.column3 LIKE '%' + w.word + '%'
)

How to search a row to see if any of the columns contain a certain string? In SQL

I have a table with 10 columns that each contain string values. I want to run a query that will return any of the rows which have any column value that matches a given string or set of strings.
Is there any way to do this?
The DBMS is MsSQL
if you want exact match, you can use IN keyword and check in all columns
SELECT *
FROM tablename
WHERE 'your string' IN (column1, column2, )
if you want partial match then you have to use LIKE
SELECT *
FROM tablename
WHERE column1 LIKE '%your string%' or column2 LIKE '%your string%' ...
or you can add all columns and do one LIKE check
SELECT *
FROM tablename
WHERE CONCAT(column1,'#',column2,'#',column3,'#',...) LIKE '%your string%'

How to check if a string contains exactly two words in an SQL query?

I need to execute a simple SQL query that will only select those names that are made up of exactly two words
SELECT NAME
FROM GROUP
WHERE NAME <Contains exactly two words>
You can use like and not like:
where name like '% %' and not like '% % %'
Another option is using LEN() (of course, I assume there are no trailing spaces):
SELECT [NAME]
FROM [GROUP]
WHERE LEN([NAME]) - LEN(REPLACE([NAME], ' ', '')) = 1
If the data in the NAME column has trailing space, you may use TRIM (for SQL Server 2017+) or a combination of LTRIM() and RTRIM() for earlier versions:
SELECT [NAME]
FROM [GROUP]
WHERE LEN(TRIM([NAME])) - LEN(REPLACE(TRIM([NAME]), ' ', '')) = 1
If you want both words present and exact:
SELECT *
FROM table
WHERE column LIKE '%word1%'
AND column LIKE '%word2%'

How to perform Like in SQL on a column with '%' in the data?

I am using oracle database and writing the likeness filter for the persistence layer and want to perform likeness on a column that can possibly have '%' in it's data.
To filter data I am writing the query for likeness using LIKE clause as
select * from table where columnName like '%%%';
which is returning all the values but I only want the rows that contains '%' in the columnName.
Not sure what escape character to use or what to do to filter on the '%' symbol. Any suggestions??
Also, I have to do the same thing using Criteria api in java and have no clues about putting escape character there.
You can use an escape character.
where columnName like '%$%%' escape '$'
REGEXP_LIKE might help in a rather simple manner.
SQL> with test (col) as
2 (select 'abc%def' from dual union all
3 select '%12345&' from dual union all
4 select '%abc12%' from dual union all
5 select '1234567' from dual
6 )
7 select *
8 from test
9 where regexp_like(col, '%');
COL
-------
abc%def
%12345&
%abc12%
SQL>
If I have understood it correctly the answer from the #Littlefoot is correct(and I will up-vote it now). I will just add more details because you are looking for name of the columns of your table "I only want the rows that contains '%' in the columnName".
Here is the table I have created:
CREATE TABLE "table_WITH%" ("numer%o" number
, name varchar2(50)
, "pric%e" number
, coverage number
, activity_date date);
Then this query gives me the correct answer:
SELECT column_name
FROM ALL_TAB_COLUMNS
WHERE TABLE_NAME = 'table_WITH%'
AND regexp_like(COLUMN_NAME, '%');
Gordon's answer using the escape clause of the like command is correct in the general case.
In your specific case (searching for a single character, anywhere in a string), a simpler method is to use instr, e.g.
where instr(columnname, '%') > 0

T-SQL Using CONTAINS predicate with Hyphen

Imagine a table (table1) with one column (column1) and one record whose value is 'roll-over'. Then use the following SQL query and you will not get any records.
select * from table1 where contains(column1, ' "roll-over" ')
Is there a way to escape the hyphen in the search text? So far I have not been successful trying this (I have tried all below escapes with no success).
select * from table1 where contains(column1, ' "roll\-over" ')
select * from table1 where contains(column1, ' "roll!-over" ')
select * from table1 where contains(column1, ' "roll[-]over" ')
Also, please note that using the LIKE keyword is not possible for my application because I am taking advantage of full-text search indexing.
It looks like you may not be able to do that. Give this article a read:
https://support.microsoft.com/en-us/help/200043/prb-dashes---ignored-in-search-with-sql-full-text-and-msidxs-queries
They suggest searching only alphanumeric values (lame) or using the LIKE Clause (not an option for you).
Partial solution: you can force the query to return records containing hyphens (or any character) by using the charindex function to test that the string contains the character, e.g.:
select * from table1 where contains(column1, ' "roll-over" ')
and charindex('-', column1) > 0