Sql Server

Sql Server | Find String | CHARINDEX, LIKE

Sql Server | Find String | CHARINDEX, LIKE

Check If A String in Sql

SQL provide CHARINDEX() function Or LIKE Predicate to  check if the string contains a specific substring


CHARINDEX() function
used to find a certain word or substring within a larger text and returns the first match it found.
It will return 0 if no words are detected (zero).

CHARINDEX ( SearchString,WholeString[ , startlocation ] )

Declare @mainString nvarchar(100)='Deepak Kmr Talwar'
if CHARINDEX('Kmr',@mainString) > 0
begin
   select 'Found' As Result
end
else
    select 'Not Found' As Result





LIKE Predicate

You can search within a string or content for a substring using the LIKE predicate operator.
The LIKE operator in SQL Server is used to search for character string with the specified pattern using wildcards in the column.
Using ‘%’ wildcard, before, after or both side of character.

DECLARE @WholeString VARCHAR(50)
DECLARE  @ExpressionToFind VARCHAR(50)
SET @WholeString = 'Deepak Talwar'
SET @ExpressionToFind = 'Talwar'

IF @WholeString LIKE '%' + @ExpressionToFind + '%'
    PRINT 'Found'
ELSE
    PRINT 'Not Found'


The WHERE clause of SELECT, UPDATE, and DELETE queries can also use this LIKE technique.

SELECT [EmployeeID]
,[LastName]
,[FirstName]
,[Title]
FROM [Employees]
WHERE [FirstName] LIKE '%Deepak%'


Understanding the WildCard Characters:
You can use the following wildcard characters with the LIKE operator in SQL Server.
% symbol represents any no of characters in the expression.
_ will represent a single character in the expression.
The [] symbol indicates a set of characters in the expression.
[^] will represent any single character, not within the specified range


display user details whose name contains 3 characters.
SELECT * FROM User WHERE Name LIKE '___'

display User details whose name contains 'A' character.
SELECT  * FROM User WHERE Name LIKE '%A%'

display User details whose name starts with 'D' character and ends with 'R' character.
SELECT * FROM User WHERE Name LIKE 'D%R'

display User details whose name starts with D, S, K, U characters.
SELECT * FROM User WHERE Name LIKE '[D, S, K, U]%'

display User details whose names start with A to Z characters.
SELECT * FROM User WHERE Name LIKE '[A-Z]%'

display User details whose name not start with A to Z characters.
SELECT * FROM User WHERE Name NOT LIKE '[A-Z]%'






Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.

Instagram