Searching for specific text within large amounts of data is a common need in modern applications. SQL provides a Full-Text Search (FTS) functionality to efficiently handle such searches. Unlike basic LIKE queries, which scan entire tables, full-text search uses specialized indexes and algorithms to deliver fast and accurate results for text-based data. This chapter provides a comprehensive guide, covering the basics to advanced concepts, with examples to demonstrate the capabilities of full-text search in SQL.
Full-text search is a technique that enables the retrieval of documents or records that match complex textual queries. It is optimized for:
LIKE).Popular databases that support full-text search:
tsvector and tsquery.A full-text index is a special type of index optimized for text searches. It preprocesses data into tokens for efficient retrieval.
TEXT, VARCHAR, CHAR).Enable Full-Text Index: Full-text search is supported for InnoDB and MyISAM storage engines.
Create a Table with Full-Text Index:
CREATE TABLE articles (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255),
content TEXT,
FULLTEXT(title, content)
);
FULLTEXT creates the index on title and content.
INSERT INTO articles (title, content)
VALUES
('SQL Basics', 'Learn the basics of SQL and relational databases.'),
('Advanced SQL', 'Discover advanced SQL techniques and performance optimization.');
Prepare the Text Columns: PostgreSQL uses tsvector to store searchable text.
CREATE TABLE documents (
id SERIAL PRIMARY KEY,
title TEXT,
content TEXT,
search_vector tsvector
);
search_vector:
UPDATE documents
SET search_vector = to_tsvector(title || ' ' || content);
CREATE INDEX idx_search ON documents USING GIN(search_vector);
Enable Full-Text Search: Full-Text Search must be installed and enabled on your SQL Server instance.
Create a Table:
CREATE TABLE books (
id INT PRIMARY KEY,
title NVARCHAR(255),
description NVARCHAR(MAX)
);
CREATE FULLTEXT CATALOG BookCatalog AS DEFAULT;
CREATE FULLTEXT INDEX ON books(title, description)
KEY INDEX PK_books ON BookCatalog;
Use the MATCH() and AGAINST() functions for full-text queries.
Example:
SELECT *
FROM articles
WHERE MATCH(title, content) AGAINST('SQL');
Finds all articles where the title or content contains “SQL”.
Boolean mode allows complex queries with operators (+, -, *, etc.).
SELECT *
FROM articles
WHERE MATCH(title, content) AGAINST('+SQL -Basics' IN BOOLEAN MODE);
+SQL: Must include “SQL”.-Basics: Must not include “Basics”.Use the @@ operator to match queries against a tsvector.
SELECT *
FROM documents
WHERE search_vector @@ to_tsquery('SQL & Basics');
Matches documents containing both “SQL” and “Basics”.
Use the CONTAINS or FREETEXT functions.
SELECT *
FROM books
WHERE CONTAINS(description, 'SQL AND Basics');
SELECT *
FROM books
WHERE FREETEXT(description, 'learn SQL basics');
Databases rank results based on their relevance to the query.
SELECT title, MATCH(title, content) AGAINST('SQL') AS relevance
FROM articles
ORDER BY relevance DESC;
Some databases allow highlighting matched terms.
SELECT ts_headline(content, to_tsquery('SQL')) AS highlighted_content
FROM documents
WHERE search_vector @@ to_tsquery('SQL');
Search for terms within a certain distance of each other.
SELECT *
FROM books
WHERE CONTAINS(description, 'NEAR((SQL, Basics), 5)');
Full-text search is a powerful tool for handling complex text-based queries in SQL databases. By leveraging full-text indexes, you can achieve faster and more accurate search results, especially for large datasets. This chapter has covered the fundamentals, practical implementations, and advanced features of full-text search, equipping you with the knowledge to use this feature effectively in real-world applications. Happy coding !❤️
