При работе с базой данных SQL вам может понадобиться найти записи, содержащие определенные строки. В этой статье мы разберем, как искать строки и подстроки в MySQL и SQL Server.
Содержание
- Использование операторов WHERE и LIKE для поиска подстроки
- Поиск подстроки в SQL Server с помощью функции CHARINDEX
- Поиск подстроки в SQL Server с помощью функции PATINDEX
- MySQL-запрос для поиска подстроки с применением функции SUBSTRING_INDEX()
Я буду использовать таблицу products_data
в базе данных products_schema
. Выполнение команды SELECT * FROM products_data
покажет мне все записи в таблице:
Поскольку я также буду показывать поиск подстроки в SQL Server, у меня есть таблица products_data
в базе данных products
:
Поиск подстроки при помощи операторов WHERE и LIKE
Оператор WHERE позволяет получить только те записи, которые удовлетворяют определенному условию. А оператор LIKE позволяет найти определенный шаблон в столбце. Эти два оператора можно комбинировать для поиска строки или подстроки.
Например, объединив WHERE с LIKE, я смог получить все товары, в которых есть слово «computer»:
SELECT * FROM products_data WHERE product_name LIKE '%computer%'
Знаки процента слева и справа от «computer» указывают искать слово «computer» в конце, середине или начале строки.
Если поставить знак процента в начале подстроки, по которой вы ищете, это будет указанием найти такую подстроку, стоящую в конце строки. Например, выполнив следующий запрос, я получил все продукты, которые заканчиваются на «er»:
SELECT * FROM products_data WHERE product_name LIKE '%er'
А если написать знак процента после искомой подстроки, это будет означать, что нужно найти такую подстроку, стоящую в начале строки. Например, я смог получить продукт, начинающийся на «lap», выполнив следующий запрос:
SELECT * FROM products_data WHERE product_name LIKE 'lap%'
Этот метод также отлично работает в SQL Server:
Поиск подстроки в SQL Server с помощью функции CHARINDEX
CHARINDEX() — это функция SQL Server для поиска индекса подстроки в строке.
Функция CHARINDEX() принимает 3 аргумента: подстроку, строку и стартовую позицию для поиска. Синтаксис выглядит следующим образом:
CHARINDEX(substring, string, start_position)
Если функция находит совпадение, она возвращает индекс, по которому найдено совпадение, а если совпадение не найдено, возвращает 0. В отличие от многих других языков, отсчет в SQL начинается с единицы.
Пример:
SELECT CHARINDEX('free', 'free is the watchword of freeCodeCamp') position;
Как видите, слово «free» было найдено на позиции 1. Это потому, что на позиции 1 стоит его первая буква — «f»:
Можно задать поиск с конкретной позиции. Например, если указать в качестве позиции 25, SQL Server найдет совпадение, начиная с текста «freeCodeCamp»:
SELECT CHARINDEX('free', 'free is the watchword of freeCodeCamp', 25);
При помощи CHARINDEX можно найти все продукты, в которых есть слово «computer», выполнив этот запрос:
SELECT * FROM products_data WHERE CHARINDEX('computer', product_name, 0) > 0
Этот запрос диктует следующее: «Начиная с индекса 0 и до тех пор, пока их больше 0, ищи все продукты, названия которых содержат слово «computer», в столбце product_name». Вот результат:
Поиск подстроки в SQL Server с помощью функции PATINDEX
PATINDEX означает «pattern index», т. е. «индекс шаблона». Эта функция позволяет искать подстроку с помощью регулярных выражений.
PATINDEX принимает два аргумента: шаблон и строку. Синтаксис выглядит следующим образом:
PATINDEX(pattern, string)
Если PATINDEX находит совпадение, он возвращает позицию этого совпадения. Если совпадение не найдено, возвращается 0. Вот пример:
SELECT PATINDEX('%ava%', 'JavaScript is a Jack of all trades');
Чтобы применить PATINDEX к таблице, я выполнил следующий запрос:
SELECT product_name, PATINDEX('%ann%', product_name) position FROM products_data
Но он только перечислил все товары и вернул индекс, под которым нашел совпадение:
Как видите, подстрока «ann» нашлась под индексом 3 продукта Scanner. Но скорее всего вы захотите, чтобы выводился только тот товар, в котором было найдено совпадение с шаблоном.
Чтобы обеспечить такое поведение, можно использовать операторы WHERE и LIKE:
SELECT product_name, PATINDEX('%ann%', product_name) position FROM products_data WHERE product_name LIKE '%ann%'
Теперь запрос возвращает то, что нужно.
MySQL-запрос для поиска строки с применением функции SUBSTRING_INDEX()
Помимо решений, которые я уже показал, MySQL имеет встроенную функцию SUBSTRING_INDEX(), с помощью которой можно найти часть строки.
Функция SUBSTRING_INDEX() принимает 3 обязательных аргумента: строку, разделитель и число. Числом обозначается количество вхождений разделителя.
Если вы укажете обязательные аргументы, функция SUBSTRING_INDEX() вернет подстроку до n-го разделителя, где n — указанное число вхождений разделителя. Вот пример:
SELECT SUBSTRING_INDEX("Learn on freeCodeCamp with me", "with", 1);
В этом запросе «Learn on freeCodeCamp with me» — это строка, «with» — разделитель, а 1 — количество вхождений разделителя. В этом случае запрос выдаст вам «Learn on freeCodeCamp»:
Количество вхождений разделителя может быть как положительным, так и отрицательным. Если это отрицательное число, то вы получите часть строки после указанного числа разделителей. Вот пример:
SELECT SUBSTRING_INDEX("Learn on freeCodeCamp with me", "with", -1);
От редакции Techrocks: также предлагаем почитать «Индексы и оптимизация MySQL-запросов».
Заключение
Из этой статьи вы узнали, как найти подстроку в строке в SQL, используя MySQL и SQL Server.
CHARINDEX() и PATINDEX() — это функции, с помощью которых можно найти подстроку в строке в SQL Server. Функция PATINDEX() является более мощной, так как позволяет использовать регулярные выражения.
Поскольку в MySQL нет CHARINDEX() и PATINDEX(), в первом примере мы рассмотрели, как найти подстроку в строке с помощью операторов WHERE и LIKE.
Перевод статьи «SQL Where Contains String – Substring Query Example».
This should ideally be done with the help of SQL Server full text search if using that.
However, if you can’t get that working on your DB for some reason, here is a performance-intensive solution:
-- table to search in
CREATE TABLE dbo.myTable
(
myTableId int NOT NULL IDENTITY (1, 1),
code varchar(200) NOT NULL,
description varchar(200) NOT NULL -- this column contains the values we are going to search in
) ON [PRIMARY]
GO
-- function to split space separated search string into individual words
CREATE FUNCTION [dbo].[fnSplit] (@StringInput nvarchar(max),
@Delimiter nvarchar(1))
RETURNS @OutputTable TABLE (
id nvarchar(1000)
)
AS
BEGIN
DECLARE @String nvarchar(100);
WHILE LEN(@StringInput) > 0
BEGIN
SET @String = LEFT(@StringInput, ISNULL(NULLIF(CHARINDEX(@Delimiter, @StringInput) - 1, -1),
LEN(@StringInput)));
SET @StringInput = SUBSTRING(@StringInput, ISNULL(NULLIF(CHARINDEX
(
@Delimiter, @StringInput
),
0
), LEN
(
@StringInput)
)
+ 1, LEN(@StringInput));
INSERT INTO @OutputTable (id)
VALUES (@String);
END;
RETURN;
END;
GO
-- this is the search script which can be optionally converted to a stored procedure /function
declare @search varchar(max) = 'infection upper acute genito'; -- enter your search string here
-- the searched string above should give rows containing the following
-- infection in upper side with acute genitointestinal tract
-- acute infection in upper teeth
-- acute genitointestinal pain
if (len(trim(@search)) = 0) -- if search string is empty, just return records ordered alphabetically
begin
select 1 as Priority ,myTableid, code, Description from myTable order by Description
return;
end
declare @splitTable Table(
wordRank int Identity(1,1), -- individual words are assinged priority order (in order of occurence/position)
word varchar(200)
)
declare @nonWordTable Table( -- table to trim out auxiliary verbs, prepositions etc. from the search
id varchar(200)
)
insert into @nonWordTable values
('of'),
('with'),
('at'),
('in'),
('for'),
('on'),
('by'),
('like'),
('up'),
('off'),
('near'),
('is'),
('are'),
(','),
(':'),
(';')
insert into @splitTable
select id from dbo.fnSplit(@search,' '); -- this function gives you a table with rows containing all the space separated words of the search like in this e.g., the output will be -
-- id
-------------
-- infection
-- upper
-- acute
-- genito
delete s from @splitTable s join @nonWordTable n on s.word = n.id; -- trimming out non-words here
declare @countOfSearchStrings int = (select count(word) from @splitTable); -- count of space separated words for search
declare @highestPriority int = POWER(@countOfSearchStrings,3);
with plainMatches as
(
select myTableid, @highestPriority as Priority from myTable where Description like @search -- exact matches have highest priority
union
select myTableid, @highestPriority-1 as Priority from myTable where Description like @search + '%' -- then with something at the end
union
select myTableid, @highestPriority-2 as Priority from myTable where Description like '%' + @search -- then with something at the beginning
union
select myTableid, @highestPriority-3 as Priority from myTable where Description like '%' + @search + '%' -- then if the word falls somewhere in between
),
splitWordMatches as( -- give each searched word a rank based on its position in the searched string
-- and calculate its char index in the field to search
select myTable.myTableid, (@countOfSearchStrings - s.wordRank) as Priority, s.word,
wordIndex = CHARINDEX(s.word, myTable.Description) from myTable join @splitTable s on myTable.Description like '%'+ s.word + '%'
-- and not exists(select myTableid from plainMatches p where p.myTableId = myTable.myTableId) -- need not look into myTables that have already been found in plainmatches as they are highest ranked
-- this one takes a long time though, so commenting it, will have no impact on the result
),
matchingRowsWithAllWords as (
select myTableid, count(myTableid) as myTableCount from splitWordMatches group by(myTableid) having count(myTableid) = @countOfSearchStrings
)
, -- trim off the CTE here if you don't care about the ordering of words to be considered for priority
wordIndexRatings as( -- reverse the char indexes retrived above so that words occuring earlier have higher weightage
-- and then normalize them to sequential values
select s.myTableid, Priority, word, ROW_NUMBER() over (partition by s.myTableid order by wordindex desc) as comparativeWordIndex
from splitWordMatches s join matchingRowsWithAllWords m on s.myTableId = m.myTableId
)
,
wordIndexSequenceRatings as ( -- need to do this to ensure that if the same set of words from search string is found in two rows,
-- their sequence in the field value is taken into account for higher priority
select w.myTableid, w.word, (w.Priority + w.comparativeWordIndex + coalesce(sequncedPriority ,0)) as Priority
from wordIndexRatings w left join
(
select w1.myTableid, w1.priority, w1.word, w1.comparativeWordIndex, count(w1.myTableid) as sequncedPriority
from wordIndexRatings w1 join wordIndexRatings w2 on w1.myTableId = w2.myTableId and w1.Priority > w2.Priority and w1.comparativeWordIndex>w2.comparativeWordIndex
group by w1.myTableid, w1.priority,w1.word, w1.comparativeWordIndex
)
sequencedPriority on w.myTableId = sequencedPriority.myTableId and w.Priority = sequencedPriority.Priority
),
prioritizedSplitWordMatches as ( -- this calculates the cumulative priority for a field value
select w1.myTableId, sum(w1.Priority) as OverallPriority from wordIndexSequenceRatings w1 join wordIndexSequenceRatings w2 on w1.myTableId = w2.myTableId
where w1.word <> w2.word group by w1.myTableid
),
completeSet as (
select myTableid, priority from plainMatches -- get plain matches which should be highest ranked
union
select myTableid, OverallPriority as priority from prioritizedSplitWordMatches -- get ranked split word matches (which are ordered based on word rank in search string and sequence)
),
maximizedCompleteSet as( -- set the priority of a field value = maximum priority for that field value
select myTableid, max(priority) as Priority from completeSet group by myTableId
)
select priority, myTable.myTableid , code, Description from maximizedCompleteSet m join myTable on m.myTableId = myTable.myTableId
order by Priority desc, Description -- order by priority desc to get highest rated items on top
--offset 0 rows fetch next 50 rows only -- optional paging
SQL contains string — In this blog, I will explain how to check a specific word or character in a given statement in SQL Server, using CHARINDEX function or SQL Server and check if the string contains a specific substring with CHARINDEX function.
Alternative to CHARINDEX() is using LIKE predicate.
Method 1 — Using CHARINDEX() function
CHARINDEX()
This function is used to search for a specific word or a substring in an overall string and returns its starting position of match. In case no word is found, then it will return 0 (zero).
Let us understand this with examples.
Syntax
CHARINDEX ( SearchString,WholeString[ , startlocation ] )
Example
Declare @mainString nvarchar(100)='Amit Kumar Yadav'
---Check here @mainString contains Amit or not, if it contains then retrun greater than 0 then print Find otherwise Not Find
if CHARINDEX('Amit',@mainString) > 0
begin
select 'Find' As Result
end
else
select 'Not Find' As Result
Output
Method 2 — Using LIKE Predicate
The LIKE predicate operator can be used to find a substring into a string or content. The LIKE operator combined with % and _ (underscore) is used to look for one more characters and a single character respectively. You can use % operator to find a sub-string.
In the following SQL query, we will look for a substring, ‘Kumar» in the string.
DECLARE @WholeString VARCHAR(50)
DECLARE @ExpressionToFind VARCHAR(50)
SET @WholeString = 'Amit Kumar Yadav'
SET @ExpressionToFind = 'Kumar'
IF @WholeString LIKE '%' + @ExpressionToFind + '%'
PRINT 'Yes it is find'
ELSE
PRINT 'It doesn''t find'
Output
This method can also be used in the WHERE clause of SELECT, UPDATE, and DELETE statements. The following SELECT satement selects records from Employees table of Northwind database where Employee’s Title contains a substring, ‘Sales’.
SELECT [EmployeeID]
,[LastName]
,[FirstName]
,[Title]
FROM [NORTHWND].[dbo].[Employees]
WHERE Title LIKE '%Sales%'
The output of the above query returns the following results.
Summary
In this blog, we saw how to get data with substrings in a column.
In SQL Server, you can use the T-SQL CHARINDEX()
function or the PATINDEX()
function to find a string within another string. Here’s a quick overview of each function.
The CHARINDEX() Function
This function accepts 3 arguments; the string to find, the string to search, and an optional start position.
The CHARINDEX()
syntax goes like this:
CHARINDEX ( expressionToFind , expressionToSearch [ , start_location ] )
Where expressionToFind is the expression you want to find in the other string, and expressionToSearch is the other string. The optional start_location can be used to specify a position within expressionToSearch for which to start searching.
Note that only the position of the first occurrence is returned.
Example
Here’s an example:
SELECT CHARINDEX('Bob', 'Bob likes beer. Bob also likes beef.');
Result:
1
In this example, the first argument is Bob
, which means that we’re searching the second argument for Bob
. The result is 1 because that’s the position where Bob
first appears in the second argument.
You might also notice that Bob
actually appears twice in the string, but only the position of the first match is returned.
No Match
If the second argument didn’t contain Bob
the result would’ve been 0
.
SELECT CHARINDEX('Kate', 'Bob likes beer. Bob also likes beef.');
Result:
0
Specifying a Starting Position
You can specify a starting position for where to start searching. This means that SQL Server will skip any occurrence that comes before that starting position. However, the results are still reported based on its position within the string (not from the start position).
If this sounds confusing, the following example should help:
SELECT CHARINDEX('Bob', 'Bob likes beer. Bob also likes beef.', 16);
Result:
17
So in this example we start searching at position 16 (which happens to be the space before the 2nd Bob
). The result is that the first occurrence of Bob
is skipped, and the second one’s position is returned. And we can see that its position is 17 characters from the start of the string (even though it’s only one character from where we started searching).
Case-Sensitivity
You can explicitly perform a case-sensitive search by adding the COLLATE clause to your SELECT statement:
Case-Sensitive
Here’s a case-sensitive search:
SELECT CHARINDEX('Beer', 'Bob likes beer.' COLLATE Latin1_General_CS_AS);
Result:
0
This is case-sensitive because _CS
stands for Case-Sensitive.
Case-Insensitive
And here’s a case-insensitive search:
SELECT CHARINDEX('Beer', 'Bob likes beer.' COLLATE Latin1_General_CI_AS);
Result:
11
This is case-insensitive because _CI
stands for Case-Insensitive.
The PATINDEX() Function
The PATINDEX()
function does a similar job to CHARINDEX()
. You basically have a choice of which one to use. The main difference is in the syntax.
The PATINDEX()
function’s syntax goes like this:
PATINDEX ( '%pattern%' , expression )
Where pattern is a character expression that contains the sequence to be found, and expression is the expression to be searched (typically a column).
The PATINDEX()
accepts wildcard characters, but not a starting position. CHARINDEX()
on the other hand accepts a starting position, but not wildcard characters.
Examples
Here’s an example:
SELECT PATINDEX('%eer%', 'Bob likes beer.');
Result:
12
However, here’s what happens when we don’t include the wildcard characters:
SELECT PATINDEX('eer', 'Bob likes beer.');
Result:
0
Here’s another example where we introduce another wildcard character:
SELECT PATINDEX('%b_er%', 'Bob likes beer.');
Result:
11
In this case, the underscore (_
) which is a wildcard for any single character.
If you’re working with a database, whether large or small, there might be occasions when you need to search for some entries containing strings.
In this article, I’ll show you how to locate strings and substrings in MySQL and SQL Server.
I‘ll be using a table I call products_data
in a products_schema
database. Running SELECT * FROM products_data
shows me all the entries in the table:
Since I’ll be showing you how to search for a string in SQL Server too, I have the products_data
table in a products
database:
What We’ll Cover
- How to Query for Strings in SQL with the
WHERE
Clause andLIKE
Operator - How to Query for Strings in SQL Server with the
CHARINDEX
Function - How to Query for Strings in SQL Server with the
PATINDEX
Function - How to Query for Strings in MySQL with the
SUBSTRING_INDEX()
Function - Conclusion
How to Query for Strings in SQL with the WHERE
Clause and LIKE
Operator
The WHERE
clause lets you get only the records that meet a particular condition. The LIKE
operator, on the other hand, lets you find a particular pattern in a column. You can combine these two to search for a string or a substring of a string.
I was able to get all the products that have the word “computer” in them by combining the WHERE
clause and LIKE
operator by running the query below:
SELECT * FROM products_data
WHERE product_name LIKE '%computer%'
The percentage sign before and after the word “computer” means, find the word “computer” whether it’s in the end, middle, or start.
So, if you put the percentage sign at the start of a substring you’re searching by, it means, find that substring at the end of a string. For Example, I got every product that ends with “er” by running this query:
SELECT * FROM products_data
WHERE product_name LIKE '%er'
And if it’s at the end of a string, it means, find that substring at the start of a string. For example, I was able to get the product that starts with “lap” with this query:
SELECT * FROM products_data
WHERE product_name LIKE 'lap%'
This method also works fine in SQL Server:
How to Query for Strings in SQL Server with the CHARINDEX
Function
CHARINDEX() is an SQL server function for finding the index of a substring in a string.
The CHARINDEX()
function takes 3 arguments – the substring, the string, and the starting position. The syntax looks like this:
CHARINDEX(substring, string, start_position)
If it finds a match, it returns the index where it finds the match, but if it doesn’t find a match, it returns 0. Unlike many other languages, counting in SQL is 1-based.
Here’s an example:
SELECT CHARINDEX('free', 'free is the watchword of freeCodeCamp') position;
You can see the word free was found in position 1. That’s because ‘f’ itself is at position 1:
If I specify 25 as the position, SQL Server would find a match starting from the “freeCodeCamp” text:
SELECT CHARINDEX('free', 'free is the watchword of freeCodeCamp', 25);
I was able to use the CHARINDEX
function to search for all products that have the word “computer” in them by running this query:
SELECT * FROM products_data WHERE CHARINDEX('computer', product_name, 0) > 0
That query is saying, start from index 0, as long as they’re more than 0, get me every product that has the word “computer” in them in the product_name
column. This is the result:
How to Query for Strings in SQL Server with the PATINDEX
Function
PATINDEX
stands for “pattern index”. So, with this function, you can search for a substring with regular expressions.
PATINDEX
takes two arguments – the pattern and the string. The syntax looks like this:
PATINDEX(pattern, string)
If PATINDEX
finds a match, it returns the position of that match. If it doesn’t find a match, it returns 0. Here’s an example:
SELECT PATINDEX('%ava%', 'JavaScript is a Jack of all trades');
To apply PATINDEX
to the example table, I ran this query:
SELECT product_name, PATINDEX('%ann%', product_name) position
FROM products_data
But it only listed every product and returned the index where it found the match:
You can see it found the word “ann” at index 3 of the product Scanner. On many occasions, you might not want this behavior because you would want it to show only the item matched.
I made it return only what gets matched by using the WHERE
clause and LIKE
operator:
SELECT product_name, PATINDEX('%ann%', product_name) position
FROM products_data
WHERE product_name LIKE '%ann%'
Now it’s behaving as you would want.
How to Query for Strings in MySQL with the SUBSTRING_INDEX()
Function
Apart from the solutions I’ve already shown you, MySQL has an inbuilt SUBSTRING_INDEX()
function with which you can find a part of a string.
The SUBSTRING_INDEX()
function takes 3 compulsory arguments – the string, the substring to search for, and a delimiter. The delimiter has to be a number.
When you specify the compulsory arguments, the SUBSTRING_INDEX()
function will get you every part of the string that occurs before the delimiter you specify. Here’s an example:
SELECT SUBSTRING_INDEX("Learn on freeCodeCamp with me", "with", 1);
In the query above, «Learn on freeCodeCamp with me» is the string, «with» is the substring and 1 is the delimiter. In this case, the query will get you “Learn on freeCodeCamp”:
The delimiter can also be a negative number. If it’s a negative number, it gets you each part of the string that occurs after the delimiter you specify. Here’s an example:
SELECT SUBSTRING_INDEX("Learn on freeCodeCamp with me", "with", -1);
Conclusion
This article showed you how to locate a substring in a string in SQL using both MySQL and SQL Server.
CHARINDEX()
and PATINDEX()
are the functions with which you can search for a substring in a string inside SQL Server. PATINDEX()
is more powerful because it lets you use regular expressions.
Since CHARINDEX()
and PATINDEX()
don’t exist in MySQL, the first example showed you how you can find a substring in a string with the WHERE
clause and LIKE
operator.
Thank you for reading!
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
The SQL contains is the SQL predicate Boolean function used with WHERE clause in the SQL Select statement to perform full-text search operations like search for a word, the prefix of a word, a word near another word, synonym of a word, etc… On full-text indexed columns containing character-based data types like string, char, and so on
Although SQL contains is not a standard SQL function, many of the database SQL Contains function argument depending on which database system we are using with,
For Microsoft SQL Server, SQL Contains function used to searches a text search in text column value-based criteria that are specified in a search argument and returns a number with either a true or false result, it will be 1 (true) if it finds a match and 0 (false) if it doesn’t. The first argument is the name of the table column you want to be searched; the second argument is the substring you want to find in the first argument column value
SQL Contains | SQL LIKE |
---|---|
SQL Contains is a predicate that can be used to search for a word, the prefix of a word, a word near another word, synonym of a word, etc. | SQL LIKE is an operator which is used to find whether a text string matches with a specified pattern or substring |
SQL Contains performs full-text search only on full-text indexed columns. | SQL LIKE search by matching regular expression Patten in the text column |
SQL Contains supports only wildcard character asterisk (*) | SQL LIKE supports all regular characters or wildcard characters like %, _, [] and [^] in a pattern |
SQL Contain operator searched in the expression or condition in nvarchar datatype | SQL LIKE perform the matching operation with a string that can have a maximum of eight thousand bytes |
Consider an eCommerce shopping system with three tables’ product, customer, and order for performing practical examples of SQL contains
Customer Table
productid | productname | category | tags | price | attribute |
---|---|---|---|---|---|
10001 | bluetooth | electronic | electronic,wired | 600 | blur color,wired,intel |
10002 | television | electronic | electronic,colored | 30000 | LED screen,unbrealable,balck |
10003 | iphone | electronic | electronic,apple | 25000 | 5.4-inch(13.7 cm diagonal) |
10004 | smart watch | electronic,watch | electronic, apple | 5000 | Apple Watch Series 7 |
orderid | orderdate | productid | custid | quntity | shippingaddress | shippingdate | amount |
---|---|---|---|---|---|---|---|
111 | 02-02-1990 | 10001 | 101 | 2 | althan,canal road,surat | 12-02-1990 | 1500 |
112 | 03-03-1991 | 10002 | 102 | 1 | ambe nagar,delhi | 20-03-1991 | 28000 |
113 | 05-05-2000 | 10001 | 102 | 3 | bhatar,surat | 15-05-2000 | 2000 |
114 | 04-04-2000 | 10002 | 103 | 1 | bandra,mumbai | 10-04-2000 | 28000 |
115 | 05-04-2000 | 10003 | 104 | 2 | bhatar,mumbai | 10-04-2000 | 20000 |
Search for a single word in a single column
Example 1: Write SQL query to display those customer data whose address contains ‘surat’
select custid as 'Customer ID' , custname as 'Customer Name',custaddress as 'Address' , custcity as 'City',custpincode as 'Pincode',custemail as 'Email',custcontactno as 'Customer Contact No' from tblcustomer
where contains(custaddress,'surat');
- In the above query, SQL Contains is used to search for the word ‘surat’ in the full-text index column custaddress
- The first argument in contains function is the columnname custadress and the second argument is the word to be search
ALSO READ: SQL Time Functions Explained [Easy Examples]
OUTPUT:
Search for a single word in multiple columns
Example 2: Write a SQL query to display all customer data that has the ‘surat’ word in the address or city column
select custid as 'Customer ID' , custname as 'Customer Name',custaddress as 'Address' , custcity as 'City',custpincode as 'Pincode',custemail as 'Email',custcontactno as 'Customer Contact No' from tblcustomer
where contains((custaddress,custcity),'surat');
- In the above query, SQL Contains is used to search for a word ‘surat’ in two columns custaddress and custcity
- The first argument in contains operator is two column names in the small bracket and the second argument is a word to be searched, SQL will search for a word in both columns and if found in either of the column value, it will be in the resulting recordset
OUTPUT:
Search for a word in all full-text indexed columns
Example 3: Write a SQL query to display products details which has a word ‘electronic’ in any of the column value
select productid as'ID',productname as 'Product Name',category as 'Product Category', tags as 'Product Tags',price as 'Price',attribute as 'Product Attribute' from tblproduct
where contains(*,'electronic');
- In the above query, SQL contains is used to search for a word ‘electronic’ in all column values
- The first argument of SQL Contain operator is the asterisk (*), it specified all searches in all full-text index columns, and the second argument is the ‘electronic’ word to be search
ALSO READ: SQL select first row in GROUP [SOLVED]
OUTPUT:
Search for two conditions with logical OR
Example 4: Write SQL query to display customer details who has ‘bharat’ or ‘surat’ word in the address value
select custid as 'Customer ID' , custname as 'Customer Name',custaddress as 'Address' , custcity as 'City',custpincode as 'Pincode',custemail as 'Email',custcontactno as 'Customer Contact No' from tblcustomer
where contains(custaddress,'"surat" or "bhatar"');
- In the above query, SQL contains is used to search for two words ‘surat’ and ‘bhatar’ in the custaddress column
- The First argument in the contains operator is the name of full-text indexed column name custaddress and the second argument is two words to be searched separated by logical operator OR, both words are enclosed in the double quotation mark
OUTPUT:
Search for two conditions with logical AND
Example 5: Write SQL query to display products information which are having ‘black’ and ‘LED’ as attribute value
select productid as'ID',productname as 'Product Name',category as 'Product Category', tags as 'Product Tags',price as 'Price',attribute as 'Product Attribute' from tblproduct
where contains(attribute,'"black" AND "LED"');
- In the above query, SQL Contains is used to search for two words with logical AND operator
- The first argument is full-text index column name attribute and the second argument is the two words ‘black’ and ‘LED’ enclosed in double quotation separated with AND, that means if any records have both words in the attribute column value then it will in the result set
ALSO READ: How to alter table and add column SQL [Practical Examples]
OUTPUT:
Search for two conditions with logical AND NOT
Example 6: Write SQL query to display customer information whose address contains ‘surat’ word but not contains ‘pal’ word
select custid as 'Customer ID' , custname as 'Customer Name',custaddress as 'Address' , custcity as 'City',custpincode as 'Pincode',custemail as 'Email',custcontactno as 'Customer Contact No' from tblcustomer
where contains(custaddress,'"surat" and not "pal"');
OUTPUT:
SQL Contains with NEAR | ~
The NEAR|~ is the operator used with SQL Contains to predicate for the search text with a WHERE clause or the CONTAINSTABLE function, it is also used for exact or fuzzy searches of a search term in the text, a search term can be either a single word or a phrase delimited by double quotation marks
We must specify two search terms with NEAR, the word or phrase on each side of the NEAR or ~ operator must occur in a document for a match to be returned, A given search term can be either a single word or a phrase that is delimited by double quotation marks
Example 6: Write SQL query to search for a word electronic in all columns near around the word wired
select productid as'ID',productname as 'Product Name',category as 'Product Category', tags as 'Product Tags',price as 'Price',attribute as 'Product Attribute' from tblproduct
where contains(*,'NEAR((electronic, wired))');
- In the above query, SQL contains is used to find word electronic in any of the column values near to the word wired either before word wired or after the word wired
- The first argument in the SQL contains function is the * which indicated search in the all column values, the second argument is the NEAR operator with two arguments words to be search column and the second is the word which around the given word is to be searched
ALSO READ: SQL LEFT OUTER JOIN Explained with Examples
OUTPUT:
Summary
In this article, we have covered the SQL Contains which is used to do the searching operation for a word or phrase or nearby word on a full-text index, we have started with an overview of SQL Contains, the difference between SQL LIKE and SQL Contains, define the syntax of SQL Contains with an explanation of syntax argument, also covered practical examples of SQL Contains with the search of a word in a single column and multiple columns, a search of more than one word in single, multiple and all columns values, also covered example of more than one search condition combined with logical operators, and in the ending section we have covered the SQL NEAR operator used with SQL Contains
References
CONTAINS (Transact-SQL)
Skip to content
I’ll be discussing two ways by which you can search for a string in a SQL Server variable:
Using CHARINDEX() Method:
This function is used to return the position of a substring in string. It’ll return 0 if the substring is not found.
This start position value of the word can be useful for other calculations as well.
DECLARE @strWord nvarchar(50)='My Test String'
IF CHARINDEX('Test String',@strWord) > 0
PRINT 'Found'
ELSE
PRINT 'Not Found'
Output:
Found
Use the Index value in another variable for other calculations with CHARINDEX as below:
DECLARE @iDex INT
SELECT @iDex=CHARINDEX('Test String',@strWord)
Another way is to use the LIKE operator in SQL Server. This operator is also used in SQL queries’ WHERE clause e.g.
SELECT * FROM Tbl_Name WHERE mainStringCol LIKE '%Test String%'
The above query will fetch all rows where the mainStringCol contains the text “Test String”.
Now, to find a string in a Varchar variable using the LIKE operator, e.g. below:
DECLARE @txtMailBody nvarchar(MAX)=' Hello Mr Anderson...'
IF @txtMailBody LIKE '%Hello Mr%'
PRINT 'Hello'
ELSE IF @txtMailBody LIKE '%Wad Up%'
PRINT 'Wad Up'
ELSE
PRINT 'Goof Up!'
Output:
Hello