Tip of the Day : 2 Ways to Execute Operating System Commands From SQL Server Management Studio

SQL Server Helper - Tip of the Day

Example Uses of the CHARINDEX Function

The CHARINDEX string function returns the starting position of the specified expression in a character string.  It accepts three parameters with the third parameter being optional.

CHARINDEX ( expression1, expression2, [ , start_location ] )

The first parameter is the expression that contains the sequence of characters to be found.  The second parameter is the expression searched for the specified sequence.  This is typically a column from a table.  The third parameter, which is optional, is the character position to start searching expression1 in expression2.

SELECT CHARINDEX('the', 'the quick brown fox jumps over the lazy dog') AS [Location]


SELECT CHARINDEX('the', 'the quick brown fox jumps over the lazy dog', 10) AS [Location]


SELECT CHARINDEX('jumped', 'the quick brown fox jumps over the lazy dog') AS [Location]


One useful use of the CHARINDEX is in getting the first name and last name from a full name:

SET @FullName = 'Mickey Mouse'
SELECT LEFT(@FullName, CHARINDEX(' ', @FullName) - 1) AS [FirstName],
RIGHT(@FullName, CHARINDEX(' ', REVERSE(@FullName)) - 1) AS [LastName]

First Name Last Name
---------- ----------
Mickey Mouse

The CHARINDEX function can also be used to extract the website from a full URL:

SET @URL = 'http://www.sql-server-helper.com/tips/tip-of-the-day.aspx'
SELECT SUBSTRING(@URL, CHARINDEX('http://', @URL) + 7, CHARINDEX('/', @URL, 8) - 8) AS [Website]


Another use of the CHARINDEX string function, which is not too obvious, is in sorting a result set.  Let’s assume you have a table which contains a U.S. State Code and instead of sorting the result alphabetically based on the U.S. State Code you want it sorted by certain states, like CA, FL, TX, NY in that order.  This can be accomplished using the CHARINDEX string function:

FROM [dbo].[Customers]

Back to Tip of the Day List Next Tip