Finding relevant text data efficiently requires full-text search capabilities. SQL Server’s CONTAINS
function allows searching for words, phrases, and synonyms in indexed columns.
How to use CONTAINS in SQL Server
Basic syntax and setup for using CONTAINS
.
SELECT *
FROM Product
WHERE CONTAINS((Name, Description), 'Laptop');
This filters results where "Laptop" appears in either column.
Use CONTAINS for various text searches
Find a word.
WHERE CONTAINS(Description, 'powerful')
Exact phrase search.
WHERE CONTAINS(Description, '"with high-"')
Prefix search.
WHERE CONTAINS(Description, '"W*"')
Proximity search.
WHERE CONTAINS(Description, 'NEAR((headphones, technology), 5)')
FAQ
How is CONTAINS different from LIKE?
LIKE
is for pattern matching; CONTAINS
provides full-text search.
LIKE
doesn’t require an index; CONTAINS
does.
Can CONTAINS search multiple columns?
Yes, specify them in parentheses.
WHERE CONTAINS((Column1, Column2), 'search_term')
How can I check if a column contains a substring?
Use CHARINDEX
.
WHERE CHARINDEX('substring', ColumnName) > 0
Does CONTAINS require a full-text index?
Yes, without a full-text index, the query will not work.
Conclusion
The SQL Server CONTAINS
function is a powerful tool for text-based search queries. It allows advanced filtering beyond LIKE
, supporting proximity searches, word inflections, and synonyms.
However, it requires a full-text index, so ensure your SQL Server setup includes this feature.
For more details and real-world applications, read the article SQL CONTAINS Function: SQL Server Guide With Examples.
Top comments (0)