On this page
- Why does every InnoDB table need a primary key?
- When should you use a composite key or index?
- How do you model a many-to-many relationship?
- How do you read EXPLAIN output?
- How do you add, test and remove indexes safely?
- How do you add FULLTEXT search to a table?
- Why does FULLTEXT search miss some words?
- What else keeps queries fast as tables grow?
- Questions
Why does every InnoDB table need a primary key?
InnoDB stores rows in primary key order (a clustered index), and every secondary index holds a copy of the primary key, so a short, steadily increasing key keeps the whole table small and fast. A BIGINT UNSIGNED AUTO_INCREMENT column is the usual choice.
Open a client on your server (installation is in the MySQL 8 guide) and create a practice schema:
mysql -u root -p
CREATE DATABASE lab CHARACTER SET utf8mb4;
USE lab;
CREATE TABLE customers (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(190) NOT NULL,
country CHAR(2) NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY uq_email (email)
) ENGINE=InnoDB;If a table has no primary key, InnoDB invents a hidden one, which you cannot use in queries and which makes replication slower. Random UUID strings as primary keys scatter inserts across the index; if you need UUIDs, store them as BINARY(16) with UUID_TO_BIN(UUID(), 1) so they sort roughly by time.
When should you use a composite key or index?
Use a composite index when queries filter or sort on several columns together. MySQL can use it for any leftmost prefix of its columns, so the column order should follow how you query.
CREATE TABLE orders (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
customer_id BIGINT UNSIGNED NOT NULL,
status ENUM('pending','paid','shipped') NOT NULL,
total DECIMAL(10,2) NOT NULL,
placed_at DATETIME NOT NULL,
KEY idx_cust_placed (customer_id, placed_at),
KEY idx_status_placed (status, placed_at),
CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id) REFERENCES customers(id)
) ENGINE=InnoDB;idx_cust_placed serves WHERE customer_id = 7, WHERE customer_id = 7 AND placed_at >= '2026-11-01' and WHERE customer_id = 7 ORDER BY placed_at DESC, but not a filter on placed_at alone. Put equality columns first and the range or sort column last.
A composite primary key, made of two or more columns, fits tables where the combination is the natural identity, as in the link table below.
How do you model a many-to-many relationship?
Create a link table with one foreign key to each side and make the pair its primary key. Add a reverse index so lookups work in both directions.
CREATE TABLE products (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(120) NOT NULL
);
CREATE TABLE tags (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(60) NOT NULL UNIQUE
);
CREATE TABLE product_tags (
product_id INT UNSIGNED NOT NULL,
tag_id INT UNSIGNED NOT NULL,
PRIMARY KEY (product_id, tag_id),
KEY idx_tag_product (tag_id, product_id),
FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE,
FOREIGN KEY (tag_id) REFERENCES tags(id) ON DELETE CASCADE
);
SELECT p.name FROM products p
JOIN product_tags pt ON pt.product_id = p.id
JOIN tags t ON t.id = pt.tag_id
WHERE t.name = 'nvme';The composite primary key stops duplicate pairs, and ON DELETE CASCADE removes links when a product or tag goes away. Extra facts about the relationship, such as the date a tag was added, belong as columns in the link table.
How do you read EXPLAIN output?
Prefix a query with EXPLAIN and look at type, key, rows and Extra: you want a named key, a small row estimate and no surprise temporary tables or file sorts on large tables.
EXPLAIN SELECT id, total FROM orders
WHERE customer_id = 7 ORDER BY placed_at DESC LIMIT 10\G- type:
constandeq_refare ideal,refandrangeare good,indexmeans a full index scan andALLmeans every row is read. - key: the index chosen;
NULLmeans none. - rows: the optimizer's estimate of rows examined.
- Extra:
Using indexmeans the index alone answered the query (covering index);Using filesortorUsing temporarypoint to sorting or grouping work you might avoid with a better index.
For measured numbers rather than estimates, run the query for real with timing on each step:
EXPLAIN ANALYZE SELECT c.email, COUNT(*) FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'paid' AND o.placed_at >= NOW() - INTERVAL 30 DAY
GROUP BY c.email;EXPLAIN ANALYZE executes the statement, so use it on SELECTs, not on writes you do not want applied. Pick candidates from the slow query log described in the install guide.
How do you add, test and remove indexes safely?
Add indexes online with ALTER TABLE ... ADD INDEX, check the plan, and before dropping an index make it invisible first to see whether anything slows down.
ALTER TABLE orders ADD INDEX idx_placed (placed_at), ALGORITHM=INPLACE, LOCK=NONE;
SHOW INDEX FROM orders;
ALTER TABLE orders ALTER INDEX idx_placed INVISIBLE;
-- watch the slow log for a while, then either:
ALTER TABLE orders ALTER INDEX idx_placed VISIBLE;
ALTER TABLE orders DROP INDEX idx_placed;Every index speeds reads but costs disk space and slows inserts and updates, so remove ones that no query uses. The sys schema lists them:
SELECT * FROM sys.schema_unused_indexes WHERE object_schema = 'lab';
SELECT * FROM sys.schema_redundant_indexes WHERE table_schema = 'lab';The unused list is only meaningful after the server has run normal traffic for a while since its last restart.
How do you add FULLTEXT search to a table?
Create a FULLTEXT index on the text columns and query them with MATCH (...) AGAINST (...), listing exactly the columns of the index.
CREATE TABLE docs (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(200) NOT NULL,
body TEXT NOT NULL,
FULLTEXT KEY ft_title_body (title, body)
) ENGINE=InnoDB;
INSERT INTO docs (title, body) VALUES
('Nightly backups', 'Use mysqldump with single-transaction for consistent InnoDB backups.'),
('Tuning InnoDB', 'The buffer pool size matters most for read heavy workloads.');
SELECT id, title, MATCH (title, body) AGAINST ('innodb backups') AS score
FROM docs
WHERE MATCH (title, body) AGAINST ('innodb backups')
ORDER BY score DESC;
SELECT title FROM docs
WHERE MATCH (title, body) AGAINST ('+buffer -backup' IN BOOLEAN MODE);Natural language mode ranks by relevance. Boolean mode adds + (must contain), - (must not), quoted phrases and the * wildcard at the end of a word.
Why does FULLTEXT search miss some words?
InnoDB skips words shorter than three characters and words on its stopword list, and terms that appear in half the rows rank low in natural language mode.
SHOW VARIABLES LIKE 'innodb_ft_min_token_size';
SELECT * FROM INFORMATION_SCHEMA.INNODB_FT_DEFAULT_STOPWORD LIMIT 10;To index two-letter terms such as "io", set innodb_ft_min_token_size = 2 under [mysqld], restart, and rebuild the index with ALTER TABLE docs DROP INDEX ft_title_body, ADD FULLTEXT ft_title_body (title, body);. For Chinese, Japanese or Korean text, which has no spaces between words, create the index WITH PARSER ngram. Larger catalogues with facets and typo tolerance usually move to a search server like Apache Solr.
What else keeps queries fast as tables grow?
Keep statistics fresh, avoid functions on indexed columns in WHERE clauses, and select only the columns you need.
ANALYZE TABLE orders;
-- slow: the function hides placed_at from the index
SELECT COUNT(*) FROM orders WHERE YEAR(placed_at) = 2026;
-- fast: a range the index can use
SELECT COUNT(*) FROM orders WHERE placed_at >= '2026-01-01' AND placed_at < '2027-01-01';If you really need to filter on an expression, MySQL 8 supports functional indexes such as ALTER TABLE customers ADD INDEX idx_email_lower ((LOWER(email)));. Watch memory too: indexes are cached in the InnoDB buffer pool, so a pool smaller than your hot indexes turns fast lookups into disk reads. JSON columns, views and procedures are covered in the next MySQL guide.
Plans that fit this guide
Base city prices. Every plan includes a dedicated IPv4 address, IPv6, full root and all 18 images.
Questions about MySQL keys, indexes and full-text search
How many indexes should a table have?
As many as your frequent queries need and no more. Each index speeds certain reads but slows every write. Review sys.schema_unused_indexes now and then and drop what is never used.
Does column order in a composite index matter?
Yes. MySQL can use the index for the leftmost columns only. Put columns compared with = first and the range or ORDER BY column last.
Should I use foreign keys in MySQL?
With InnoDB, yes for most apps. They keep data consistent and create the needed index on the child column automatically. Some very high write systems skip them and check in code instead.
Can FULLTEXT search work in MariaDB too?
Yes, MariaDB supports FULLTEXT on InnoDB with the same MATCH ... AGAINST syntax, though some variable names and the ngram parser differ. See the MariaDB guide.
What does Using filesort mean?
MySQL had to sort rows after reading them because no index delivered them in the requested order. On small result sets it is harmless; on large ones, an index that ends with the ORDER BY column removes it.
More in Databases
- Install MySQL 8
- Install MariaDB
- Install PostgreSQL
- Install MongoDB
- PostgreSQL JSON, arrays and special types
- PostgreSQL views, triggers and CTEs
- PostgreSQL full-text search and encryption
- MySQL JSON, views and stored procedures
- Apache Solr search server
- Install Redis or Valkey
- Install Memcached
- Apache Cassandra cluster
- Install Apache CouchDB
- InfluxDB for time series
- Install Elasticsearch
- Back up and restore MySQL and MariaDB
- Back up and restore PostgreSQL
- MySQL users, roles and passwords
- PostgreSQL roles and permissions
- Repair a crashed MySQL table
- PostgreSQL streaming replication
- MongoDB replica set
- PostGIS for location data
- Database insight with PgHero
- Couchbase Server
- ArangoDB multi-model database
- Remote database access over SSH