How to Implement Full-Text Search in SQL Server

Full-text search in SQL Server allows for efficient searching of text data stored in tables. Unlike the traditional LIKE operator, full-text search enables powerful linguistic-based searches, ranking results by relevance and supporting advanced features like inflectional search and proximity queries. In this guide, we will walk through the steps to implement full-text search in SQL Server.

Before using full-text search, ensure that your SQL Server instance supports and has full-text search enabled. You can check this by running:

SELECT SERVERPROPERTY('IsFullTextInstalled') AS FullTextInstalled;

If the result is 1, full-text search is installed; otherwise, you may need to install it.

Step 2: Create a Full-Text Catalog

A full-text catalog is a container for full-text indexes. To create one, use:

CREATE FULLTEXT CATALOG MyFullTextCatalog AS DEFAULT;

Step 3: Create a Full-Text Index

A full-text index is required on the columns you want to search. First, make sure your table has a unique index:

CREATE UNIQUE INDEX UI_MyTable ON MyTable(Id);

Then, create a full-text index:

CREATE FULLTEXT INDEX ON MyTable(
    MyTextColumn LANGUAGE 1033
)
KEY INDEX UI_MyTable
ON MyFullTextCatalog;

The LANGUAGE 1033 specifies English. You can change this according to the language used in your data.

Step 4: Perform Full-Text Searches

Once the index is created, you can perform full-text searches using CONTAINS and FREETEXT.

Using CONTAINS

CONTAINS allows you to search for exact words or phrases:

SELECT * FROM MyTable
WHERE CONTAINS(MyTextColumn, '"search term"');

You can also use logical operators like AND, OR, and NEAR:

SELECT * FROM MyTable
WHERE CONTAINS(MyTextColumn, '"SQL Server" NEAR "Index"');

Using FREETEXT

FREETEXT allows for a broader, natural language search:

SELECT * FROM MyTable
WHERE FREETEXT(MyTextColumn, 'search term');
  • Populate the Full-Text Index: Full-text indexes are updated automatically, but you can manually trigger an update:

    ALTER FULLTEXT INDEX ON MyTable START FULL POPULATION;
    
  • Monitor Full-Text Indexing: Check the status of your full-text population with:

    SELECT * FROM sys.fulltext_indexes;
    
  • Remove a Full-Text Index: If needed, drop the index using:

    DROP FULLTEXT INDEX ON MyTable;
    

Conclusion

Full-text search in SQL Server is a powerful tool for handling complex text-based queries. By enabling full-text search, creating an index, and using CONTAINS or FREETEXT queries, you can significantly improve search performance and relevance in your applications. With proper indexing and management, full-text search can be a game-changer for handling large text-based datasets.

0
29

Related

Closing a SqlDataReader correctly prevents memory leaks, connection issues, and unclosed resources. Here’s the best way to do it.

Use 'using' to Auto-Close

Using using statements ensures SqlDataReader and SqlConnection are closed even if an exception occurs.

Example

using (SqlConnection conn = new SqlConnection(connectionString))
{
    conn.Open();
    using (SqlCommand cmd = new SqlCommand("SELECT * FROM Users", conn))
    using (SqlDataReader reader = cmd.ExecuteReader())
    {
        while (reader.Read())
        {
            Console.WriteLine(reader["Username"]);
        }
    } // ✅ Auto-closes reader here
} // ✅ Auto-closes connection here

This approach auto-closes resources when done and it is cleaner and less error-prone than manual closing.

⚡ Alternative: Manually Close in finally Block

If you need explicit control, you can manually close it inside a finally block.

SqlDataReader? reader = null;
try
{
    using SqlConnection conn = new SqlConnection(connectionString);
    conn.Open();
    using SqlCommand cmd = new SqlCommand("SELECT * FROM Users", conn);
    reader = cmd.ExecuteReader();

    while (reader.Read())
    {
        Console.WriteLine(reader["Username"]);
    }
}
finally
{
    reader?.Close();  // ✅ Closes reader if it was opened
}

This is slightly more error prone if you forget to add a finally block. But might make sense when you need to handle the reader separately from the command or connection.

0
87

When working with URLs in C#, encoding is essential to ensure that special characters (like spaces, ?, &, and =) don’t break the URL structure. The recommended way to encode a string for a URL is by using Uri.EscapeDataString(), which converts unsafe characters into their percent-encoded equivalents.

string rawText = "hello world!";
string encodedText = Uri.EscapeDataString(rawText);

Console.WriteLine(encodedText); // Output: hello%20world%21

This method encodes spaces as %20, making it ideal for query parameters.

For ASP.NET applications, you can also use HttpUtility.UrlEncode() (from System.Web), which encodes spaces as +:

using System.Web;

string encodedText = HttpUtility.UrlEncode("hello world!");
Console.WriteLine(encodedText); // Output: hello+world%21

For .NET Core and later, Uri.EscapeDataString() is the preferred choice.

26
417

Storing passwords as plain text is dangerous. Instead, you should hash them using a strong, slow hashing algorithm like BCrypt, which includes built-in salting and resistance to brute-force attacks.

Step 1: Install BCrypt NuGet Package

Before using BCrypt, install the BCrypt.Net-Next package:

dotnet add package BCrypt.Net-Next

or via NuGet Package Manager:

Install-Package BCrypt.Net-Next

Step 2: Hash a Password

Use BCrypt.HashPassword() to securely hash a password before storing it:

using BCrypt.Net;

string password = "mySecurePassword123";
string hashedPassword = BCrypt.HashPassword(password);

Console.WriteLine(hashedPassword); // Output: $2a$12$...

Step 3: Verify a Password

To check a user's login attempt, use BCrypt.Verify():

bool isMatch = BCrypt.Verify("mySecurePassword123", hashedPassword);
Console.WriteLine(isMatch); // Output: True

Ensuring proper hashing should be at the top of your list when it comes to building authentication systems.

2
226