Tip of the Day : SQL Server 2012 Management Studio Keyboard Shortcuts - Microsoft IntelliSense

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]

Location
----------------
1

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

Location
----------------
32

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

Location
----------------
0

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

DECLARE @FullName  VARCHAR(100)
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:

DECLARE @URL   VARCHAR(100)
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]

Website
---------------------------
www.sql-server-helper.com

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:

SELECT *
FROM [dbo].[Customers]
ORDER BY CHARINDEX([State], 'CA-FL-TX-NY')
Back to Tip of the Day List Next Tip