SQL

SQL CONTAINS Function: SQL Server Guide With Examples

intro

Explore the power of SQL CONTAINS function and understand how this function works with real-world examples.

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

Full-text string searching is essential for finding data in the database based on advanced query criteria. This process is complex, which is why SQL Server offers specialized functions to simplify it. The SQL CONTAINS function servers exactly that role, offering a powerful tool designed for full-text search queries.

In this article, you will dig into the world of the CONTAINS SQL Server function. Uncover its syntax, mechanics, and practical applications through several examples.

Embark on a journey to understand the capabilities of CONTAINS in SQL Server!

What Is the SQL CONTAINS Function in SQL Server?

CONTAINS is an SQL Server function to search for a word or phrase in one or more text columns using precise or fuzzy matching. Specifically,CONTAINS in SQL Server is a predicate to use in the WHERE clause to perform full-text search.

The column or columns to search in must be of character-based data types. Also, they must be full-text indexed columns.

In detail, the CONTAINS SQL Server function can search for:

  • A specific word.
  • A particular phrase.
  • The prefix of a word.
  • The prefix of a phrase.
  • A word within a certain distance of another.
  • A word inflectionally generated from another (e.g., the word “query” is the inflectional stem of “queries,” “queried,” and ”querying”).
  • A word that is a synonym of another word based on the specified thesaurus (e.g., the word "discover" can have synonyms such as "find," "uncover," and "reveal").

How to Use CONTAINS in SQL Server

Below is the T-SQL CONTAINS syntax in a sample query:

Copy
        
1 SELECT * 2 FROM TableName 3 WHERE CONTAINS (ColumnName | ( ColumnList ) | *, 'SearchCondition')

The arguments supported by the function are:

  • ColumnName: The name of the full-text indexed column in the <TableName> table to apply SearchCondition to.
  • ColumnList: The list of columns, separated by commas, and enclosed in parentheses to apply SearchCondition to.
  • *: Specifies that the SQL CONTAINS string search query will involve all full-text indexed columns in the <TableName> table.
  • <SearchCondition>: A nvarchar string that contains the text to search for and the conditions for a match. This can also include SQL Server full-text search operators such as OR, AND, and AND NOT. Check out the docs to find out all the full-text search capabilities offered by Transact-SQL.

Note: The first three arguments are connected by a logical OR, so the SQL CONTAINS function can accept as the first argument either a column name, a comma-separated list of columns, or *.

Your First SQL CONTAINS Example

Consider the CONTAINS SQL Server example query below:

Copy
        
1 SELECT Id, Name, Description 2 FROM Product 3 WHERE CONTAINS((Name, Description), 'Laptop');

That will return the products whose Name and Description columns contain the word “Laptop.” Based on your table’s collation, CONTAINS will be case-sensitive or case-insensitive. As you can see from the results below, the result set involves the target keyword regardless of its case:

Executing the SQL CONTAINS query in DbVisualizer
Executing the SQL CONTAINS query in DbVisualizer

If Name and Description columns were not full-text indexed, the query would fail with:

Copy
        
1 Cannot use a CONTAINS or FREETEXT predicate on table or indexed view '<YourTable>' because it is not full-text indexed.

To avoid that, you need to define a FULLTEXT index involving the columns to apply CONTAINS to. Take a look at the SQL Server documentation to learn how. In detail, you would have to launch a query as below:

Copy
        
1 CREATE FULLTEXT CATALOG ProductCatalog AS DEFAULT; 2 3 CREATE FULLTEXT INDEX ON Product(Name, Description) 4 KEY INDEX PK__Product__3214EC07303CD7E1;

Unfortunately, the full-text search component is optional in SQL Server. Thus, your FULLTEXT index creation query may fail with:

Copy
        
1 [Code: 7609, SQL State: S1000] Full-Text Search is not installed, or a full-text component cannot be loaded.

Learn how to install it in the next section. If this is not your case, feel free to skip to the next main chapter.

Add the Full-Text Search Component on SQL Server 2022

Launch the query below to make sure that the Full-Text Search component is installed:

Copy
        
1 SELECT SERVERPROPERTY('IsFullTextInstalled');

If it returns 1, it is already installed. However, if it returns 0, you need to add it to your SQL Server.

Download the installer of the Developer edition of SQL Server. Double-click it, and select the “Custom” option. What for the installer to load and click on the “Installation” menu entry on the right. Next, select “New SQL Server standalone installation or add features to an existing installation” as in the image below:

Click on the first option
Click on the first option

Keep clicking the “Next” button until you reach the following screen:

All operations have been completed and you can click Next
All operations have been completed and you can click “Next”

Click “Next” again and select the second option as follows:

Click Next
Click “Next”

Uncheck the “Azure Extension for SQL Server” option and press the “Next” button:

Make sure to uncheck the first option
Make sure to uncheck the first option

Check the “Full-Text and Semantic Extractions for Search” component, click “Next,” and wait for the installation process to end.

Find the Full-Text SQL Server component and install it
Find the “Full-Text” SQL Server component and install it

Note that you can follow this procedure to install other essential additional modules such as “SQL Server Replication.”

Now, reconnect to your SQL Server and you are ready to use the SQL CONTAINS function!

CONTAINS SQL Server Use Cases

Learn how to use CONTAINS in SQL Server by exploring the most common possible scenarios through real-world examples.

Note: The SQL CONTAINS queries below will be executed in DbVisualizer, a fully-featured, powerful, multi-database client with the highest user satisfaction in the market

In particular, the queries will be run on the following Product table:

The data in the Product table as presented by DbVisualizer
The data in the Product table as presented by DbVisualizer

As you can see, it stores information about some products.

Search for a Single Term

The following example finds all products with a price of more than 40 units of value that contain the word “wireless” in their description:

Copy
        
1 SELECT Id, Name, Description 2 FROM Product 3 WHERE Price > 40 AND CONTAINS(Description, 'wireless');

Execute the query, and you will get the following result:

Two products contain the word wireless in their description, but only one has a price higher than 40
Two products contain the word “wireless” in their description, but only one has a price higher than 40

Search for a Phrase

The SQL CONTAINS example below returns all products that contain the “designed for” phrase:

Copy
        
1 SELECT Id, Name, Description 2 FROM Product 3 WHERE CONTAINS(Description, '"designed for"');

The result of the above CONTAINS SQL Server query will be:

Two products contain the desired phrase
Two products contain the desired phrase

Note the use of the double quotes. Without them the query will fail with:

Copy
        
1 Syntax error near 'for' in the full-text search condition 'designed for-'.

This is because double quotes are required on Transact-SQL full-text search conditions involving multiple words or special operators.

Keep in mind that different database management systems may interpret special characters differently. For example, in MySQL:

  • + means “must contain.”
  • - means “must not contain.”
  • * denotes a wildcard.
  • Any text wrapped in double quotes ("") means “give me an exact match.”

Search for the Prefix of a Word

This query retrieves all products whose name contains at least one word starting with the “W” character:

Copy
        
1 SELECT Id, Name, Description 2 FROM Product 3 WHERE CONTAINS(Description, '"W*"');

The above query that show the usage of wildcards with CONTAINS in SQL Server will produce:

Note the wildcard * operator
Note the wildcard * operator

Notice the use of the double quotes and the * character to specify the prefix syntax in the CONTAINS SQL function. The double quotes are required; without them, the query won't fail but will return no results, as the * will be interpreted as a regular asterisk rather than a wildcard:

See that this time you get no results
See that this time you get no results

Word Proximity Search

The following SQL CONTAINS example query searches for all products whose description contains the word ”device” within 5 search terms of the word "smartphone" in the specified order (“device” must precede “smartphone”):

Copy
        
1 SELECT Id, Name, Description 2 FROM Product 3 WHERE CONTAINS(Description, 'NEAR((device , smartphone), 5)');

The resulting dataset will be:

The description of the matching product contains the two words within the specified distance
The description of the matching product contains the two words within the specified distance

Find out more about the NEAR full-text operator.

Search for Inflectional Forms

This query searches for all products with words of the form work (e.g. worked, working, and so on).

Copy
        
1 SELECT Id, Name, Description 2 FROM Product 3 WHERE CONTAINS(Description, 'FORMSOF (INFLECTIONAL, work)');

The result will be:

The resulting products containing the inflectional forms of the word work in their description
The resulting products containing the inflectional forms of the word “work” in their description

Note that the product “Smartwatch” contains the word “working” but not “work.” That is still a match as “working” is an inflectional form of “work.”

Search Through Logical Operators

The CONTAINS predicate in the query below will search for descriptions that contain both the word “comfortable” and the word “long:”

Copy
        
1 SELECT Id, Name, Description 2 FROM Product 3 WHERE CONTAINS(Description, 'comfortable AND long');

The result will be:

Note that the resulting product contains the two words as desired
Note that the resulting product contains the two words as desired

Notice the use of the AND operator. Similarly, you can use OR and AND NOT.

Search for Opposite Match

You can use CONTAINS to get all records that do not match some criteria with:

Copy
        
1 SELECT Id, Name, Description 2 FROM Product 3 WHERE NOT CONTAINS(*, 'Laptop');

The above SQL NOT CONTAINS query would produce:

image.png
image.png

Note that the “Laptop” device has been excluded by the results.

Et voilà! You are now a SQL CONTAINS master. For more use cases, take a look at the “Examples” section on the official documentation.

Conclusion

In this guide to using CONTAINS in SQL Server, you learned what this function is and how it works. This powerful full-text search function helps you search for strings in text columns. Thanks to the many real-world examples shown above, you know how to use it in different scenarios.

Full-text searching is tricky! To better understand how to use the SQL CONTAINS function, you need a tool to visualize the data in the database. This is precisely the purpose of a powerful database client such as DbVisualizer! In addition to presenting data visually, it supports several DBMS technologies, offers advanced query optimization capabilities, and can generate ERD-like schemas. Try DbVisualizer for free today!

Appendix: Conditions Required by CONTAINS in SQL Server

  1. The SQL CONTAINS function works on columns of the following types: char, varchar, nchar, nvarchar, text, ntext, image, xml, varbinary, and varbinary(max).
  2. The columns in the CONTAINS clause must come from a single table and be full-text indexed.

FAQ

What is the difference between LIKE vs CONTAINS in SQL Server?

The LIKE vs CONTAINS SQL Server comparison boils down to a few facts:

  • LIKE is a pattern-matching operator used for simple string matching, while CONTAINS is used for more advanced full-text searching.
  • LIKE performs partial matching with wildcards, whereas CONTAINS considers word forms, synonyms, and allows weighted searches.
  • CONTAINS requires a full-text index, while LIKE does not.
  • LIKE is typically case-insensitive, while CONTAINS behavior depends on column collation.

Below is a summary table comparing LIKE and CONTAINS in SQL Server:

FeatureLIKECONTAINS
Type of MatchingSimple string matchingAdvanced full-text search
Pattern MatchingUses wildcards (e.g., %, _) for partial matchingSupports word forms, synonyms, and weighted searches
Index RequirementNo index requiredRequires a full-text index
Case SensitivityTypically case-insensitive (depends on collation)Depends on column collation (can be case-sensitive or case-insensitive)
PerformanceGenerally slower for large datasetsOptimized for large text-based datasets with full-text indexing
Use CaseBasic searches (e.g., LIKE '%word%')Complex searches involving words and their variations (e.g., CONTAINS('word'))

Can I apply the SQL Server CONTAINS function on multiple columns?

Yes, you can use the CONTAINS function on multiple columns by concatenating them with commas in the search condition as in the example below:

Copy
        
1 SELECT * 2 FROM TableName 3 WHERE CONTAINS((Column1, ..., ColumnN), 'SearchCondition');

How to check that a SQL string contains a substring?

To check if a SQL string contains a substring, you can use the CHARINDEX function as follows:

Copy
        
1 SELECT * 2 FROM TableName 3 WHERE CHARINDEX('substring', ColumnName) > 0;

This query returns rows where the specified substring is found within the specified column. Thus, you do not need CONTAINS to achieve the desired result.

Does the CONTAINS SQL Server function work on columns that do not have a full-text index?

No, the CONTAINS SQL Server function requires all columns mentioned in the predicate to have a full-text index. Otherwise, the query will fail with the following error:

Copy
        
1 Cannot use a CONTAINS or FREETEXT predicate on table or indexed view '<YourTable>' because it is not full-text indexed.

What is the full T-SQL CONTAINS syntax?

You can find the full syntax of the  SQL CONTAINS on the documentation. To view the Transact-SQL syntax of that function for SQL Server 2014 and earlier versions, explore the documentation of the previous versions.

What is the difference between using AND NOT in the CONTAINS operator and using the SQL NOT CONTAINS?

Using AND NOT with the CONTAINS operator means you are combining two conditions: one where the CONTAINS condition is true, and the other where a term or phrase is excluded. For example, CONTAINS(Name, 'laptop') AND NOT CONTAINS(Description, 'tablet'). On the other hand, the SQL NOT CONTAINS function excludes results based on a full-text search.

Dbvis download link img
About the author
Antonello Zanini

Antonello is a software engineer, and often refers to himself as a technology bishop. His mission is to spread knowledge through writing.

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

MySQL Indexing Mistakes 101

author Lukas Vileikis tags MySQL Search SQL 10 min 2025-03-27
title

SQL TRUNCATE TABLE: A Complete Guide

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

A Complete Guide to SQL Window Functions

author Lukas Vileikis tags DATA TYPES DbVisualizer MySQL SQL 5 min 2025-03-25
title

A Complete Guide to the FULL OUTER JOIN SQL Operation

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 7 min 2025-03-24
title

How to Use JOIN in a DELETE Query in SQL

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2025-03-20
title

What Is the MySQL DSN Format for Golang?

author Lukas Vileikis tags DbVisualizer MySQL SQL 4 min 2025-03-19
title

Operations Across Entire Columns: SQL Aggregate Functions Explained

author Lukas Vileikis tags DbVisualizer MySQL SQL Transaction 8 min 2025-03-18
title

A Guide to the SQL CREATE TABLE Statement

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 7 min 2025-03-17
title

Clustered Indexes in PostgreSQL: What They Are and How to Use Them

author Lukas Vileikis tags DbVisualizer POSTGRESQL SQL 5 min 2025-03-13
title

How to Deal With a Swollen SQL Transaction Log

author Antonello Zanini tags SQL SQL SERVER 7 min 2025-03-12

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.