📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Users want to search product descriptions by keyword, and LIKE '%term%' is slow and gives poor results. What is SQL Server full-text search, how do CONTAINS and FREETEXT work, what are its limits, and when would you use Azure AI Search or Elasticsearch instead?

Full-text search in SQL Server and Azure SQL: why LIKE with a leading wildcard fails, full-text catalogs and indexes, word breakers and stemming, CONTAINS, FREETEXT and ranking functions, and when to move to Azure AI Search or Elasticsearch.

Intermediate Theory Intermediate azure-ai-search elasticsearch full-text-search query-performance sargability sql-server

🎯 Key points

  • LIKE '%term%' can't seek an index (leading wildcard) and matches substrings, not words
  • Full-text index: an inverted index of word tokens per row, built by word breakers and stemmers for a language
  • Requires a unique, single-column, non-nullable key index; populated asynchronously (change tracking AUTO), so results lag commits slightly regardless of isolation level
  • CONTAINS: precise words, phrases, prefixes ("run*"), NEAR, inflectional forms; FREETEXT: meaning-based, stems and thesaurus
  • CONTAINSTABLE/FREETEXTTABLE return RANK for relevance ordering
  • Built into SQL Server and Azure SQL Database (all service tiers), but instance-level customisation such as thesaurus files isn't available in Azure SQL Database
  • Limits: basic relevance, no typo tolerance, facets, rich synonyms or semantic/vector ranking; Azure AI Search or Elasticsearch for those, synced via change tracking or an outbox and monitored for lag
  • Row-level permissions are enforced by the database for full-text queries; an external index needs security trimming of its own

⏱ 30-second answer

LIKE '%term%' has a leading wildcard, so it can't seek and scans every row, and it matches substrings, not words ("cat" matches "education"). Full-text search builds an inverted index of word tokens using a language's word breaker and stemmer, populated asynchronously in the background. CONTAINS does precise word, phrase, prefix ("kett*"), proximity (NEAR) and inflectional searches; FREETEXT matches meaning, using stemming and the thesaurus. CONTAINSTABLE/FREETEXTTABLE add a RANK for ordering. It's available in Azure SQL Database with no extra service.

Its limits are basic relevance, no typo tolerance, facets or vector search. When search is a product feature, I'd use Azure AI Search (or Elasticsearch), kept in sync from SQL.

🗣 Full answer (senior)

How I would answer this in an interview

"LIKE with a leading wildcard is the problem. An index on Description is sorted by the start of the value, so '%kettle%' can't seek; SQL Server scans every row and runs a string comparison, which on a few million long descriptions is seconds of CPU. It's also semantically wrong: it matches substrings, so searching 'cat' finds 'education', and it doesn't know 'kettles' and 'kettle' are the same word.

Full-text search solves both. I create a full-text catalog and a full-text index on the column, with a language, say English. A word breaker splits text into tokens, a stemmer understands inflections, a stoplist drops noise words, and the result is an inverted index: for each word, which rows contain it and at which positions. Population is asynchronous, so with change tracking set to AUTO new rows become searchable shortly after commit, not instantly. Then CONTAINS gives me precise searches: exact words, phrases in quotes, prefixes like "kett*", NEAR for proximity, and FORMSOF(INFLECTIONAL, run) to match ran and running. FREETEXT is looser: it breaks my search string into words, stems them and matches on meaning. If I need relevance ordering I use CONTAINSTABLE, which returns a key and a RANK I can join and sort on.

It's a good fit for internal tools, admin search and modest catalogues, and it's built into Azure SQL Database. But relevance tuning is limited, there's no typo tolerance, no facets, no synonyms beyond a thesaurus file, and no vector or semantic ranking. When search is a customer-facing feature, I'd push the data to Azure AI Search, which adds fuzzy matching, facets, scoring profiles and hybrid vector search, and keep it in sync from SQL through change tracking or an outbox. The mistake I see is teams adding more indexes to fix a LIKE '%x%' query, which can't help."


Options

Option Matching Performance Features
LIKE 'term%' Prefix of the whole value Seek Only prefix of the value
LIKE '%term%' Substring Scan None
Full-text CONTAINS Words, phrases, prefixes, proximity, inflections Inverted index RANK via CONTAINSTABLE
Full-text FREETEXT Meaning, stemming, thesaurus Inverted index Looser recall
Azure AI Search / Elasticsearch Analysers, fuzzy, synonyms, vectors Separate service Facets, highlighting, scoring profiles, hybrid search

CONTAINS vs FREETEXT

CONTAINS FREETEXT
Input Search condition syntax Plain text
Precision High Lower, higher recall
Prefix, NEAR, boolean Yes No
Typical use Search box with operators, exact terms Natural-language queries

Production example

An admin portal searched 1.2 million support tickets with LIKE '%term%': about 4 seconds and 180,000 logical reads per search, with CPU spikes when several agents searched at once. A full-text index with CONTAINSTABLE and TOP (50) by rank brought searches to around 40 ms.

🔍 What the interviewer is checking

Checks the candidate understands why LIKE fails, how full-text search works and when a dedicated search engine is justified.

Green flags

  • Explains leading-wildcard scans and substring semantics
  • Describes the inverted index, word breakers, stemming and async population
  • Distinguishes CONTAINS and FREETEXT and uses CONTAINSTABLE for ranking
  • Knows when to move to Azure AI Search and how to keep it in sync

Red flags

  • Tries to fix LIKE '%x%' with normal indexes
  • Concatenates user input into search conditions
  • Recommends Elasticsearch for every search box

📚 Learn in depth

1. Why LIKE with a leading wildcard scans

B-tree on Description (sorted):  'Blue kettle...', 'Electric kettle...', 'Kettle, 1.7L...'
LIKE 'Kettle%'   -> seek to 'Kettle' range
LIKE '%kettle%'  -> no starting point -> scan every row, compare strings

Collation also matters: case-insensitive comparisons on long nvarchar values are CPU-heavy.

2. The inverted index

Row 1: "Electric kettle, 1.7 litres"
Row 2: "Stainless kettles for camping"

word breaker + stemmer (English)
   electric -> {1}
   kettle   -> {1, 2}   (kettles stemmed at query time with FORMSOF)
   litre    -> {1}
   stainless-> {2}
   camping  -> {2}

Full-text indexes store word, row key and position. They need a unique, single-column, non-nullable index on the table as the key (an int key is best).

3. Population

  • CHANGE_TRACKING AUTO (default): changes are applied in the background shortly after commit.
  • MANUAL: you run ALTER FULLTEXT INDEX ... START UPDATE POPULATION.
  • OFF: full population only.

So full-text results are eventually consistent with the table. Check FULLTEXTCATALOGPROPERTY(..., 'PopulateStatus') and sys.dm_fts_index_population.

4. Query forms

  • CONTAINS(col, '"electric kettle"'): phrase.
  • CONTAINS(col, '"kett*"'): prefix (must be in double quotes).
  • CONTAINS(col, 'NEAR((kettle, stainless), 5)'): proximity.
  • CONTAINS(col, 'FORMSOF(INFLECTIONAL, run)'): run, ran, running.
  • FREETEXT(col, 'cheap camping kettle'): meaning-based.
  • CONTAINSTABLE(table, col, condition, top_n): returns [KEY] and RANK (0-1000).

User input must be sanitised or quoted, because CONTAINS has its own syntax and stray quotes or operators cause errors.

5. Limits and when to move on

No typo tolerance, limited relevance control, no facets or highlighting, thesaurus files per instance (not configurable in Azure SQL Database), and no vector similarity. Azure AI Search provides analysers, fuzzy search, synonyms, scoring profiles, facets, semantic ranker and vector or hybrid search. Keep the database as the source of truth and push changes with change tracking, CDC or an outbox-driven indexer.

Try it yourself

  1. Load 1 million product descriptions and compare LIKE '%kettle%' with CONTAINS using SET STATISTICS IO, TIME ON.
  2. Create a full-text index, insert a row, and query immediately to observe population delay.
  3. Compare CONTAINS and FREETEXT results for "running shoes".
  4. Use CONTAINSTABLE with top_n_by_rank and join back to the table ordered by RANK.
  5. Look at sys.dm_fts_parser to see how the word breaker tokenises a sentence.

💻 Code

Creating a full-text index and searching with ranking.

CREATE FULLTEXT CATALOG ProductCatalog AS DEFAULT;
GO
-- Needs a unique, single-column, non-nullable key index (the int PK here)
CREATE FULLTEXT INDEX ON dbo.Products (Name LANGUAGE 1033, Description LANGUAGE 1033)
    KEY INDEX PK_Products
    WITH (CHANGE_TRACKING = AUTO, STOPLIST = SYSTEM);
GO

-- Precise: phrase or prefix
SELECT ProductId, Name
FROM dbo.Products
WHERE CONTAINS((Name, Description), N'"electric kettle" OR "kett*"');

-- Meaning-based
SELECT ProductId, Name
FROM dbo.Products
WHERE FREETEXT(Description, N'cheap kettle for camping');

-- Ranked top 50
SELECT TOP (50) p.ProductId, p.Name, ft.[RANK]
FROM CONTAINSTABLE(dbo.Products, (Name, Description), N'FORMSOF(INFLECTIONAL, kettle)', 200) AS ft
JOIN dbo.Products p ON p.ProductId = ft.[KEY]
ORDER BY ft.[RANK] DESC;

-- See how text is tokenised
SELECT display_term, occurrence
FROM sys.dm_fts_parser(N'"Stainless kettles for camping"', 1033, 0, 0);
namespace Catalogue.Search;

public static class FullTextQuery
{
    // CONTAINS has its own syntax: quote user terms so operators and quotes can't break the query.
    public static string ToPrefixCondition(string userInput)
    {
        var terms = userInput
            .Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
            .Select(t => t.Replace("\"", ""))
            .Where(t => t.Length > 0)
            .Select(t => $"\"{t}*\"");
        return string.Join(" AND ", terms); // still passed as a parameter, never concatenated into SQL
    }
}

⚠ Common mistakes

  • Mistake: Adding a normal index to speed up LIKE '%term%'. Why it is wrong: A leading wildcard can't seek a B-tree. Instead: Use full-text search or an external search service.
  • Mistake: Expecting new rows to be searchable immediately. Why it is wrong: Full-text population is asynchronous. Instead: Design the UX for slight delay, or check population status in tests.
  • Mistake: Passing raw user input as a CONTAINS condition. Why it is wrong: Quotes and operators cause syntax errors or odd matches. Instead: Sanitise and quote terms, and always pass the condition as a parameter.
  • Mistake: Writing CONTAINS(col, 'kett*') without double quotes. Why it is wrong: The asterisk is treated literally; prefix search needs '"kett*"'. Instead: Wrap prefix terms in double quotes.
  • Mistake: Using full-text as a full product search engine. Why it is wrong: No typo tolerance, facets or tunable relevance. Instead: Use Azure AI Search or Elasticsearch for customer-facing search.
  • Mistake: Ignoring synonym and meaning requirements until late. Why it is wrong: Users search "jug" for "kettle" or describe what they want in sentences; SQL full-text's thesaurus is limited (and not customisable in Azure SQL Database) and it has no semantic or vector ranking. Instead: Capture these needs early; if they matter, plan for Azure AI Search with synonym maps and semantic or hybrid vector ranking.
  • Mistake: Moving search to an external index and forgetting permissions. Why it is wrong: The index returns documents the user isn't allowed to see. Instead: Store security fields in the index and filter on them (security trimming), or re-check access in SQL.
  • Mistake: Forgetting stoplists. Why it is wrong: Domain words that look like noise (or noise words that matter) give confusing results. Instead: Create a custom stoplist when needed.

🏛 Senior insight: trade-offs

Full-text search is the cheapest real improvement over LIKE because it's already in SQL Server and Azure SQL: no new service, no sync pipeline. The judgement is recognising when search becomes a product feature: typo tolerance, facets, synonyms and relevance tuning are where a dedicated engine earns its operating cost.

Option Fits when Cost Not when
LIKE 'prefix%' Autocomplete on the start of a value None Words inside text
SQL full-text Internal search, modest catalogues Async population, limited relevance Customer-facing search with facets and typos
Azure AI Search Product search, facets, vectors, Australia East region Separate service and sync pipeline, cost per unit Tiny internal lookups
Elasticsearch/OpenSearch Self-managed, heavy customisation Operating a cluster Small teams without ops capacity

Measure logical reads and CPU per search with SET STATISTICS IO, TIME ON, and search latency in Application Insights.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says a leading wildcard prevents an index seek Why: Checks the broader SARGability rules.
    How to answer

    A predicate is SARGable (Search ARGument-able) when the optimiser can turn it into a seek range on an index. The rule: leave the column bare and put any calculation on the other side.

    • YEAR(OrderDate) = 2026 scans; OrderDate >= '2026-01-01' AND OrderDate < '2027-01-01' seeks.
    • Price * 1.1 > 100 scans; Price > 100 / 1.1 seeks.
    • An implicit conversion of the column (e.g. varchar column vs nvarchar parameter) often scans; match types.
    • LIKE 'abc%' seeks; LIKE '%abc' cannot.
    • ISNULL(col, 0) = 0 scans; col = 0 OR col IS NULL seeks.

    When the expression is unavoidable, index a persisted computed column. Trade-off: the rewrite is free; the computed column costs storage and writes.

  2. When: Candidate suggests moving search to Azure AI Search Why: Checks understanding of sync mechanisms, consistency and failure handling.
    How to answer

    Keep SQL as the source of truth. Options: the Azure SQL indexer with change tracking (integrated change detection) pulls changes on a schedule, deletes via a soft-delete column; or push from the app with an outbox table processed by a background worker calling the Search API in batches; or CDC into a stream. Accept eventual consistency (seconds to minutes), make updates idempotent by document key, handle deletes explicitly, monitor indexer failures and lag, and support a full reindex into a new index with alias swap for schema changes.

↩ Usually asked after

More in SQL Features

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me