SQL SERVER

SQL Server CHARINDEX Function (Find Substring Position)

intro

Learn how to use the SQL Server CHARINDEX function to locate substrings, handle case sensitivity, specify start positions, and streamline string manipulation in your T-SQL queries.

Tools used in the tutorial
Tool Description Link
Dbvisualizer DBVISUALIZER
TOP RATED DATABASE MANAGEMENT TOOL AND SQL CLIENT

Searching for a substring within a string is a common operation when working with strings in databases. To support that, SQL Server provides the CHARINDEX function, which allows you to locate substrings and perform advanced string manipulation in your T-SQL queries.

In this guide, you'll learn what the SQL Server CHARINDEX function is, how it works, and how to use it in real-world scenarios.

What Is CHARINDEX in SQL Server?

In SQL Server, CHARINDEX is a function used to search for a substring within a string and return the position (index) where that substring starts. This function is very handy for string processing tasks, such as finding the location of a certain character or word in a text.

How to Use the SQL Server CHARINDEX Function?

Below is the syntax of the CHARINDEX SQL Server function:

Copy
        
1 CHARINDEX(search_expression, target_expression [, start_location])

Where:

  • search_expression is the substring you are looking for.
  • target_expression is the larger string in which you want to search for the substring for.
  • start_location is optional. It is an integer specifying where to start the search starting from the value of 1. In other words, if omitted, it defaults to 1 (beginning of the string).

CHARINDEX SQL Server Examples

This is a quick example of how to use CHARINDEX in SQL Server:

Copy
        
1 SELECT CHARINDEX('world', 'Hello world') AS position;

Executing the above query in a powerful SQL Server database client like DbVisualizer will result in an output of “7” in the position column:

Executing the CHARINDEX query in DbVisualizer
Executing the CHARINDEX query in DbVisualizer

As you can see, the result will be 7. That’s because the word "world" starts at the 7th character of "Hello world" if we count from 1 (spaces also count as a character.)

Note: If the substring is not found, CHARINDEX returns 0.

Another example:

Copy
        
1 SELECT CHARINDEX('SQL', 'Learn SQL on SQLServer', 1) AS firstOccur, 2 CHARINDEX('SQL', 'Learn SQL on SQLServer', 8) AS secondOccur;

In this case:

  • firstOccur will look for "SQL" starting from position 1, finding it at position number 7 ("Learn[space]SQL…").
  • secondOccur starts searching from position 8 (skipping the first occurrence), so it should find the second "SQL" (in "SQL Server") at position 14.

Verify that by executing the query:

Note the result 7 and 14, as expected
Note the result 7 and 14, as expected

Now, suppose you want to run:

Copy
        
1 SELECT CHARINDEX('sql', 'I love SQL Server') AS pos1, 2 CHARINDEX('SQL', 'I love SQL Server') AS pos2;

The result—assuming default case-insensitive collation—will be:

  • pos1 = 8 as the function will find "sql" starting at the 8th character matching "SQL" because it is case-insensitive.
  • pos2 = 8 as well because it is the same substring.

If case-sensitive collation, pos1 might be 0 if the case doesn't match exactly and pos2 = 8.

Another popular example is the use of CHARINDEX with an SQL variable as below:

Copy
        
1 DECLARE @name NVARCHAR(100) = 'John Doe'; 2 SELECT SUBSTRING(@name, 1, CHARINDEX(' ', @name) - 1) AS FirstName, 3 SUBSTRING(@name, CHARINDEX(' ', @name) + 1, 100) AS LastName;

This uses the space position to separate first and last name.

Key Notes About the SQL Server CHARINDEX Function

  • Return Value: It returns an integer. If the substring is found, it returns the 1-based position of the first character of the first occurrence of the substring. If not found, it returns 0. If you search for an empty string '', CHARINDEX will return 1 (it finds an empty string at the start by definition). However, you wouldn’t do that.
  • Not found vs found at start: If substring is found at the very beginning, it returns 1. If not found at all, 0 (which is distinct, since valid positions are 1 and up).
  • Case sensitivity: This depends on the collation of the strings. By default, SQL Server string comparisons are case-insensitive if you use a case-insensitive collation (like the typical SQL_Latin1_General_CI_AS). In a case-insensitive collation, CHARINDEX('abc', 'ABC') would return 1 (it finds the target string by ignoring case). If the collation is case-sensitive, it would return 0 in that scenario. So be aware that the CHARINDEX SQL Server function obeys collation rules.
  • Start position: If you specify a start position beyond the length of the string, CHARINDEX returns 0 (can’t find anything if starting past end).
  • Handling NULL: If either the search string or target string is NULL, the result is NULL (not 0). So, CHARINDEX('a', NULL) yields NULL, and CHARINDEX(NULL, 'abc') yields NULL. Only when both are non-null and substring not found do you get 0. Learn more about the SQL Server NULL value.

Use Cases of CHARINDEX in SQL Server

Simple Search

Find if a substring exists and where. E.g., find the position of '@' in an email to separate username and domain:

Copy
        
1 SELECT CHARINDEX('@', email) as atPos FROM Users;

If atPos is 0, you know the email string had no '@' (which would be invalid email format).

Extracting Substrings

Often used with other functions like SUBSTRING to extract text around a found position. For example, you can obtain the text before a comma:

Copy
        
1 DECLARE @txt NVARCHAR(100) = 'LastName, FirstName'; 2 SELECT SUBSTRING(@txt, 1, CHARINDEX(',', @txt) - 1) AS LastName; 3 -- This takes everything from the start up to just before the comma.

Above, we used the SQL Server CHARINDEX function to find the comma, then SUBSTRING from 1 to the found position - 1.

Searching After a Certain Point

The third argument allows you to find subsequent occurrences. For instance, to find the second occurrence of a substring, you can use a CHARINDEX function starting after the first occurrence:

Copy
        
1 DECLARE @str NVARCHAR(50) = 'abc abc abc'; 2 -- Find first space: 3 SELECT CHARINDEX(' ', @str) AS firstSpace; -- returns 4 4 -- Find second space by starting just after first: 5 SELECT CHARINDEX(' ', @str, CHARINDEX(' ', @str) + 1) AS secondSpace; -- returns 8

This will yield the position of the second space.

Usage in the WHERE Clause

Last but not least, you can filter rows based on the output of CHARINDEX, e.g.:

Copy
        
1 SELECT * FROM Products 2 WHERE CHARINDEX('XL', product_name) > 0;

This finds all products where the name contains "XL". (Note: Using CHARINDEX like this will scan the text of every product_name. If you need fast searches inside text, consider a full-text search or at least indexing if possible on patterns, but simple CHARINDEX is fine for moderate scenarios.)

CHARINDEX In Other Databases

While CHARINDEX is specific to T-SQL, other databases have similar functions:

Understanding the SQL Server CHARINDEX function helps with string parsing tasks in T-SQL. For more complex scenarios, it’s often used alongside SUBSTRING, LEN, PATINDEX (which is like CHARINDEX but for patterns/wildcards).

Conclusion

In summary, CHARINDEX is your go-to function in SQL Server for finding a substring’s position within a larger string. It returns an integer location, or 0 if not found. It’s straightforward to use and very useful for string manipulation tasks in T-SQL. Keep in mind the 1-based indexing and the effect of collation on case sensitivity when using it. Also keep in mind that CHARINDEX can assist you in a wide variety of use cases ranging from simple search queries to searches after a certain point.

As shown here, running queries becomes easier with a visual database client like DbVisualizer. This is a fully-featured database client that supports multiple DBMS technologies, offers advanced query optimization capabilities, and can generate ERD-type schemas with a few clicks. Try it for free, and until next time.

Dbvis download link img
About the author
TheTable
TheTable

The Table by DbVisualizer is where we gather together to learn about and simplify the complexity of working with database technologies.

The Table Icon
Sign up to receive The Table's roundup
More from the table
Title Author Tags Length Published
title

How to Compare Datetimes in SQL: Multiple Approaches

author TheTable tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 5 min 2025-06-04
title

The Complete Guide to CONCAT in SQL Queries: Syntax, Examples, and Best Practices

author Leslie S. Gyamfi tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 7 min 2025-06-03
title

How Often Should SQL Transaction Logs Be Backed Up?

author Antonello Zanini tags MySQL POSTGRESQL SQL SQL SERVER 7 min 2025-06-02
title

What Is a Database Catalog?

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 6 min 2025-05-27
title

SQL Server Temp Table Mechanism: Complete Guide

author Antonello Zanini tags SQL SERVER 9 min 2025-05-20
title

Check If A Table Exists in SQL: Multiple Approaches

author Antonello Zanini tags MySQL POSTGRESQL SQL SQL SERVER 6 min 2025-05-14
title

A Complete Guide to NOT EXISTS in SQL

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2025-05-12
title

SQL DROP TABLE IF EXISTS Statement: Complete Guide

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 6 min 2025-05-05
title

TRUNCATE vs DELETE: SQL Comparison of the Two Statements

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 9 min 2025-04-23
title

How to Extract the Year from a Date in SQL

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 5 min 2025-04-21

The content provided on dbvis.com/thetable, including but not limited to code and examples, is intended for educational and informational purposes only. We do not make any warranties or representations of any kind. Read more here.