How to Perform a Full-Text Search in MySQL?
To use MySQL full text search, you must first create a FULLTEXT index, and then use the MATCH()...AGAINST() syntax to query. 1. Create a full-text index: You can add FULLTEXT indexes to CHAR, VARCHAR, and TEXT columns when creating a table or through ALTER TABLE, supporting MyISAM and InnoDB (MySQL 5.6) engines; 2. Use MATCH()...AGAINST() to perform searches: Basic natural language searches such as SELECT FROM articles WHERE MATCH(title, content) AGAINST('database tutorial' IN NATURAL LANGUAGE MODE), returning results sorted by correlation; 3. Select the appropriate search mode: including IN NATURAL LANGUAGE MODE (default, based on correlation score), IN BOOLEAN MODE (supports, -,, quotes, etc. operators) and WITH QUERY EXPANSION (extended search based on high correlation results); 4. Understand correlation scores: In natural language mode, MySQL returns a correlation score of more than 0, which can be explicitly viewed through SELECT statements and arranged in descending order of scores; 5. Pay attention to limitations and optimization: By default, words with less than 4 characters are ignored (can be adjusted by ft_min_word_len or innodb_ft_min_token_size), and common stop words (such as "the", "and"), and can customize the stop word list. The index should be rebuilt after a large number of data changes, and the columns in MATCH() must belong to the same FULLTEXT index. Correctly setting indexes, selecting appropriate modes and adjusting server parameters can significantly improve text search efficiency and are suitable for text-intensive applications such as blogs and document systems.
Performing a full-text search in MySQL allows you to efficiently search for text within large volumes of string data, especially in CHAR
, VARCHAR
, and TEXT
columns. Unlike basic LIKE
queries, full-text searches use a specialized index and search algorithm that supports relevance ranking and natural language processing. Here's how to set up and use full-text search in MySQL.

1. Create a Full-Text Index
Before you can perform a full-text search, you must create a FULLTEXT
index on the column(s) you want to search. This can be done at table creation or added later.
At table creation:

CREATE TABLE articles ( id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(200), content TEXT, FULLTEXT(title, content) );
Add to existing table:
ALTER TABLE articles ADD FULLTEXT(title, content);
Note: Full-text indexes are supported by the MyISAM and InnoDB storage engines (InnoDB from MySQL 5.6).
2. Use MATCH() ... AGAINST() Syntax
Once the index is in place, use the MATCH() ... AGAINST()
syntax to perform searches.
Basic natural language search:
SELECT * FROM articles WHERE MATCH(title, content) AGAINST('database tutorial' IN NATURAL LANGUAGE MODE);
This returns rows where the search terms appear in either title
or content
, ranked by relevance.
3. Choose the Right Search Mode
MySQL supports three full-text search modes:
-
IN NATURAL LANGUAGE MODE
(default): Treats the input as plain text and returns rows based on relevance score. -
IN BOOLEAN MODE
: Allows advanced operators like-
,*
, and quotes for exact phrases. -
WITH QUERY EXPANSION
: Expands the search using related terms from the most relevant results.
Examples:
Boolean mode – required and excluded terms:
SELECT * FROM articles WHERE MATCH(title, content) AGAINST(' database -mysql' IN BOOLEAN MODE);
Finds articles about "database" but excludes those mentioning "mysql".
Exact phrase search:
SELECT * FROM articles WHERE MATCH(title, content) AGAINST('"learn MySQL"' IN BOOLEAN MODE);
Finds rows containing the exact phrase "learn MySQL".
Wildcard (prefix) search:
SELECT * FROM articles WHERE MATCH(title, content) AGAINST('sql*' IN BOOLEAN MODE);
Matches words like "SQL", "SQLi", "SQLServer", etc.
4. Understand Relevance Scoring
In natural language mode, MySQL returns a relevance score (a positive decimal). You can view it:
SELECT id, title, MATCH(title, content) AGAINST('database' IN NATURAL LANGUAGE MODE) AS score FROM articles WHERE MATCH(title, content) AGAINST('database' IN NATURAL LANGUAGE MODE) ORDER BY score DESC;
Higher scores mean better match.
5. Know the Limitations and Tips
- Minimum word length: By default, words shorter than 4 characters are ignored. Change this via
ft_min_word_len
(MyISAM) orinnodb_ft_min_token_size
(InnoDB). - Stopwords: Common words like "the", "and", "or" are ignored. You can customize the stopword list.
- Rebuild indexes after changes: Large data changes may require rebuilding the full-text index for optimal performance.
- Only works on indexed columns: Ensure all columns in
MATCH()
are part of the sameFULLTEXT
index.
Basically, full-text search in MySQL is powerful for text-heavy applications like blogs or document systems. Set up the index correctly, use the right search mode, and fine-tune server settings for better results.
The above is the detailed content of How to Perform a Full-Text Search in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The answer is: MySQL's CASE statement is used to implement conditional logic in query, and supports two forms: simple and search. Different values can be dynamically returned in clauses such as SELECT, WHERE, and ORDERBY; for example, in SELECT, classification of scores by fractional segments, combining aggregate functions to count the number of states, or prioritizing specific roles in ORDERBY, it is necessary to always end with END and it is recommended to use ELSE to handle the default situation.

Create a shell script containing the database configuration and mysqldump command and save it as mysql_backup.sh; 2. Store MySQL credentials by creating ~/.my.cnf file and set 600 permissions to improve security, modify the script to use configuration file authentication; 3. Use chmod x to make the script executable and manually test whether the backup is successful; 4. Add timed tasks through crontab-e, such as 02/path/to/mysql_backup.sh>>/path/to/backup/backup.log2>&1, realize automatic backup and logging at 2 a.m. every day; 5.

Use the DISTINCT keyword to remove duplicate values from the specified column and return unique values. 1. The basic syntax is SELECTDISTINCTcolumn_nameFROMtable_name; 2. Query the unique value of a single column, such as SELECTDISTINCTcityFROMcustomers; 3. Query the unique combination of multiple columns, such as SELECTDISTINCTcity, stateFROMcustomers; 4. Filter with the WHERE clause and get the unique value, such as SELECTDISTINCTproduct_nameFROMordersWHEREorder_date>'202

INSERT...ONDUPLICATEKEYUPDATE implementation will be updated if it exists, otherwise it will be inserted, and it requires unique or primary key constraints; 2. Reinsert after deletion of REPLACEINTO, which may cause changes in the auto-increment ID; 3. INSERTIGNORE only inserts and does not repetitive data, and does not update. It is recommended to use the first implementation of upsert.

EXPLAINinMySQLrevealsqueryexecutionplans,showingindexusage,tablereadorder,androwfilteringtooptimizeperformance;useitbeforeSELECTtoanalyzesteps,checkkeycolumnsliketypeandrows,identifyinefficienciesinExtra,andcombinewithindexingstrategiesforfasterqueri

Subqueries can be used in WHERE, FROM, SELECT, and HAVING clauses to implement filtering or calculation based on the result of another query. Operators such as IN, ANY, ALL are commonly used in WHERE; alias are required as derivative tables in FROM; single values must be returned in SELECT; related subqueries rely on outer query to execute each row. For example, check employees whose average salary is higher than the department, or add the company average salary list. Subqueries improve logical clarity, but performance may be lower than JOIN, so you need to ensure that you return the expected results.

MySQL can calculate geographical distances through the Haversine formula or the ST_Distance_Sphere function. The former is suitable for all versions, and the latter provides easier and more accurate spherical distance calculations since 5.7.

Use UTC to store time, set the MySQL server time zone to UTC, use TIMESTAMP to realize automatic time zone conversion, adjust the time zone according to user needs in the session, display the local time through the CONVERT_TZ function, and ensure that the time zone table is loaded.
