SQL Server does not have a single function named CONTAINS for simple substring checks; instead, you use CHARINDEX, LIKE, or PATINDEX to test whether a string contains another string. For example, WHERE CHARINDEX('apple', description) > 0 returns rows where the description contains the word ‘apple’. This article explains each method, when to use it, and common pitfalls.
Why SQL Server Has No CONTAINS Function
Many developers coming from other languages expect a CONTAINS function that returns a Boolean. SQL Server does have a CONTAINS predicate, but it is only used with SQL Server’s Full-Text Search, which is a specialized feature for searching large text columns with linguistic awareness. For ordinary substring checks, the engine provides three main tools: LIKE, CHARINDEX, and PATINDEX. Each has different behavior regarding case sensitivity, wildcards, and performance.
Using LIKE for Substring Matching
The LIKE operator is the simplest way to check if a string contains a substring. It uses the percent sign (%) as a wildcard that matches any sequence of characters (including zero).
Example: find all products whose name contains ‘pro’:
SELECT ProductName FROM Products WHERE ProductName LIKE '%pro%';
This returns any product name with ‘pro’ anywhere in it. You can also use underscores (_) to match a single character, and square brackets to match a set of characters (e.g., [abc]).
Key points:
LIKEis case-insensitive by default with a typical collation (e.g., SQL_Latin1_General_CP1_CI_AS). If you need case-sensitive, use a case-sensitive collation or useCOLLATE.- If the substring you are searching for contains wildcard characters like
%or_, you must escape them using theESCAPEclause. LIKEcan be slower thanCHARINDEXon large tables because it often prevents index seeks unless you use a leading wildcard pattern that is optimized (e.g.,'abc%').
Using CHARINDEX for Position-Based Checks
CHARINDEX returns the starting position of a substring within a string, or 0 if not found. It is a function, not an operator, so you can use it in a WHERE clause or in a CASE expression.
Syntax: CHARINDEX ( expressionToFind , expressionToSearch [ , start_location ] )
Example: check if an email contains ‘@’:
SELECT Email, CASE WHEN CHARINDEX('@', Email) > 0 THEN 'Valid' ELSE 'Invalid' END AS EmailStatus FROM Users;
To filter rows, use WHERE CHARINDEX('@', Email) > 0.
Important details:
- It is case-insensitive under a case-insensitive collation, but you can force case sensitivity by using
COLLATE Latin1_General_CS_ASon either argument. - The third argument is optional; it specifies where to start searching. If omitted, the search starts at position 1.
- If the substring is not found, it returns 0.
Using PATINDEX for Pattern-Based Matching
PATINDEX is similar to CHARINDEX but it uses wildcard patterns (like LIKE) instead of a fixed substring. It returns the starting position of the first match, or 0 if no match.
Example: find rows where the string contains a digit:
SELECT Notes FROM Documents WHERE PATINDEX('%[0-9]%', Notes) > 0;
This is useful when you need to check for a pattern rather than a literal string. Note that PATINDEX uses the same wildcards as LIKE.
Choosing the Right Method
Your choice depends on the exact requirement:
- If you need a simple substring check and want readability,
LIKEis often the clearest. - If you need to use the position of the substring in further logic (e.g., to extract part of the string), use
CHARINDEXorPATINDEX. - If you are searching for a pattern (e.g., any digit, any letter), use
PATINDEX. - For full-text search capabilities (word stemming, proximity, etc.), use the
CONTAINSpredicate with a full-text index.
Performance considerations: LIKE with a leading wildcard ('%abc') cannot use an index, so it performs a full table scan. CHARINDEX also cannot use an index. If you frequently search for substrings, consider full-text indexing or storing a reversed copy of the string for certain patterns.
Case Sensitivity and Collation
All three methods are affected by the collation of the database or column. A case-insensitive collation (e.g., SQL_Latin1_General_CP1_CI_AS) makes LIKE, CHARINDEX, and PATINDEX treat ‘ABC’ and ‘abc’ as equal. To force case sensitivity, you can specify a case-sensitive collation in the comparison:
SELECT * FROM Users WHERE CHARINDEX('Admin', Username COLLATE Latin1_General_CS_AS) > 0;
This is useful for passwords or codes where case matters.
Common Pitfalls and Misconceptions
One common mistake is using CONTAINS without a full-text index. The CONTAINS predicate will fail with an error if the table does not have a full-text index on the column. Another pitfall is forgetting that LIKE treats % and _ as wildcards; if you want to search for a literal percent sign, you must escape it:
SELECT * FROM Products WHERE Description LIKE '%100%%' ESCAPE '';
This searches for the literal string ‘100%’. Also, note that CHARINDEX returns the position starting at 1, not 0, so a result of 1 means the substring is at the beginning.
Another misconception is that LIKE is always slower than CHARINDEX. In practice, the performance difference is negligible for small tables, but for large tables, both will likely use a scan unless you have a full-text index or a computed column trick.
Full-Text Search CONTAINS
If you need to search for words or phrases in large text columns with linguistic features (like word forms, synonyms, or proximity), you should use Full-Text Search. The syntax is:
SELECT * FROM Articles WHERE CONTAINS(Body, 'SQL Server');
This requires a full-text index on the Body column. It is much more powerful than the simple substring methods but also more complex to set up. It is not a replacement for CHARINDEX or LIKE for simple checks.
Frequently Asked Questions
Does SQL Server have a CONTAINS function? Yes, but only for full-text search. For ordinary substring checks, use LIKE, CHARINDEX, or PATINDEX.
How do I check if a string contains a specific word in SQL? Use WHERE column LIKE '%word%' or WHERE CHARINDEX('word', column) > 0. Both work for simple cases.
Is LIKE case-sensitive? By default, it depends on the collation. Most SQL Server installations use a case-insensitive collation, so LIKE is case-insensitive. To make it case-sensitive, use COLLATE Latin1_General_CS_AS.
Can I use CHARINDEX to find multiple occurrences? Yes, by using the start_location parameter repeatedly. For example, to find the second occurrence of ‘a’ in a string, use CHARINDEX('a', str, CHARINDEX('a', str) + 1).
What is the difference between CHARINDEX and PATINDEX? CHARINDEX searches for a literal substring, while PATINDEX uses wildcard patterns. Use PATINDEX when you need to match a pattern like a digit or a range of characters.
Why does my LIKE query return no results when I search for a percent sign? Because % is a wildcard. Use the ESCAPE clause to treat it as a literal character.
Related
- Random Number Generator Google: How to Use It
- Integrate Python into JMP: Step-by-Step Guide
- Close Tab Shortcut Mac: The 2 Keys That Work Everywhere
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel Filter Duplicates: Is Matching Case-Sensitive?No. In Excel for Microsoft 365 on Windows, the regular filter and built-in duplicate tools do not distinguish…
- Trim Function in C++: How to Remove WhitespaceThe C++ standard library does not include a built-in trim function, but you can easily implement one using…
- CHAR Excel Examples: Formulas, Line Breaks, and MoreIn Excel for Microsoft 365, use CHAR(number) to return the character assigned to a numeric code, such as…
- Rank in Excel: Formula Examples, Ties, and Sort OrderTo rank values in Excel, use RANK.EQ: with scores in B2:B6, enter =RANK.EQ(B2,$B$2:$B$6,0) in C2 and fill down.…
- Excel Table: Change a Formula in One Cell Only?Yes. To change a formula in just one Excel table cell, enter the replacement formula in that cell;…
- Excel Formula Bar Not Showing? How to Restore ItIf the formula bar is missing in Excel for Microsoft 365 on Windows, open the View tab and,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.