MySQL tables, keys and InnoDB indexes
What InnoDB is, column types, primary and foreign keys, how InnoDB stores rows in a clustered B+tree, composite indexes and the leftmost-prefix rule, and reading EXPLAIN.
Learning outcomes
- Say what a storage engine is and why every table here uses InnoDB.
- Pick column types for ids, coordinates, money and timestamps, and say why.
- Explain how InnoDB stores a table as a clustered index on the primary key.
- Explain how a secondary index finds a row through the primary key.
- Predict which part of a composite index a query can use.
- Read the type, key, rows and Extra columns of EXPLAIN.
What you're building and why this matters
Before writing SQL queries or Go database code, you need to understand how MySQL represents your data, protects relationships between tables, and finds rows efficiently.
This week, you're building the restaurant and menu portion of a food-ordering backend. The database will store restaurants, menu items, item sizes, configurable options, and their prices. Your Go services will retrieve this data through sqlc-generated queries.
Three decisions will affect almost everything you build:
- How you choose column types and define keys.
- How InnoDB physically organizes rows and indexes.
- How you design indexes around the queries your application actually runs.
The objective isn't just to write a migration that works. You should be able to explain why each column and index exists, what MySQL does internally, and what evidence tells you that a query is using an appropriate access path.
What InnoDB is, and why it matters here
MySQL is split into two layers. The top layer parses your SQL, plans the query and checks permissions. The bottom layer, called a storage engine, decides how rows are laid out on disk, how they are found, and how changes survive a crash. MySQL lets each table pick its engine, and InnoDB has been the default since MySQL 5.5.
You are not choosing InnoDB so much as inheriting it, and that is the right call. It is the engine almost every production MySQL runs, including the Aurora MySQL that large companies such as Zomato use, because it is the one that gives you:
- Transactions with commit and rollback, so a multi-row change either fully happens or does not happen at all.
- Row-level locking, so two requests updating different orders do not block each other.
- Crash recovery through a redo log, so a committed write survives a power cut.
- Foreign keys, which the older MyISAM engine never enforced.
The part that shapes everything in this lesson is how InnoDB stores a table: not as a heap of rows, but as an index ordered by the primary key. Every rule about keys and indexes below follows from that one design decision.
Understanding the restaurant database
Start with the three core tables.
CREATE TABLE restaurants (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(120) NOT NULL,
lat DECIMAL(9,6) NOT NULL,
lng DECIMAL(9,6) NOT NULL,
is_active TINYINT(1) NOT NULL DEFAULT 1,
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
INDEX idx_rest_geo (lat, lng)
) ENGINE=InnoDB;
CREATE TABLE items (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
restaurant_id BIGINT UNSIGNED NOT NULL,
name VARCHAR(120) NOT NULL,
sort INT NOT NULL DEFAULT 0,
FOREIGN KEY (restaurant_id) REFERENCES restaurants(id),
INDEX idx_items_rest (restaurant_id, sort)
) ENGINE=InnoDB;
CREATE TABLE item_sizes (
item_id BIGINT UNSIGNED NOT NULL,
size VARCHAR(8) NOT NULL,
price_paise INT UNSIGNED NOT NULL,
PRIMARY KEY (item_id, size),
FOREIGN KEY (item_id) REFERENCES items(id)
) ENGINE=InnoDB;These tables represent the following relationships:
- A restaurant can have multiple menu items.
- An item can have multiple sizes.
- Each size has its own price, stored in paise.
The menu configurator will extend this model with three more tables:
| Table | Columns | Purpose |
|---|---|---|
option_groups | id, item_id, name, min_select, max_select | Groups of configurable options |
options | id, group_id, name, in_stock | Individual choices within a group |
option_prices | option_id, size, price_paise | Price of an option for a particular size |
The relationships are:


The important point is that these aren't independent collections. Their relationships are enforced by the database, not merely assumed by your Go code.
Choosing the right column types
Column types determine what values a database can represent, how much space they consume, and which operations can be performed accurately.
Choosing an unnecessarily small type creates future limits. Choosing an unnecessarily large or imprecise type wastes resources or introduces correctness problems.
Identifiers: BIGINT UNSIGNED
Every entity in this schema uses BIGINT UNSIGNED for its identifier.
A BIGINT occupies 8 bytes. Its unsigned range is:
0 to 18,446,744,073,709,551,615This provides a very large identifier space for restaurants, menu items, and configurable options.
AUTO_INCREMENT instructs MySQL to generate an identifier when a row is inserted without an explicitly supplied ID.
For example:
INSERT INTO restaurants (name, lat, lng)
VALUES ('Central Kitchen', 12.9352, 77.6245);MySQL generates the ID automatically.
Every column participating in a relationship must have compatible types. In particular, signedness matters.
A BIGINT and a BIGINT UNSIGNED are not interchangeable definitions. Your referencing and referenced columns should match.
Coordinates: DECIMAL(9,6)
Latitude and longitude are stored as:
lat DECIMAL(9,6) NOT NULL,
lng DECIMAL(9,6) NOT NULLThe first number represents total precision, meaning the total number of digits. The second represents scale, meaning the number of digits after the decimal point.
Therefore, DECIMAL(9,6) provides:
- Three digits before the decimal point.
- Six digits after the decimal point.
- A signed range of approximately -999.999999 to 999.999999.
This is sufficient for geographic coordinates, whose valid ranges are -90 to 90 for latitude and -180 to 180 for longitude.
Why not FLOAT?
Floating-point numbers use binary approximations. Many decimal fractions cannot be represented exactly in binary floating-point arithmetic.
For example, a decimal coordinate such as 12.935200 may be stored internally as a nearby representable value when using a floating-point type.
DECIMAL is fixed-point and provides exact decimal representation within its declared precision.
That makes it a sensible choice when coordinates are supplied as decimal values and you want predictable persistence and comparisons.
Six decimal places represent roughly 0.11 metres of latitude resolution. Longitude resolution varies with latitude.
One distinction: exact decimal storage does not automatically make geographic distance calculations exact. Trigonometric calculations and geographic approximations have their own precision considerations.
Money: integer paise
Notice that menu prices are not stored as FLOAT or DECIMAL.
price_paise INT UNSIGNED NOT NULLThe application stores prices in the smallest currency unit.
For example:
| Rupee amount | Stored value |
|---|---|
| ₹49.00 | 4900 |
| ₹99.50 | 9950 |
| ₹125.75 | 12575 |
This avoids floating-point rounding problems in monetary arithmetic.
An unsigned INT can store up to 4,294,967,295 paise, or ₹42,949,672.95.
That is a deliberate range limit. If the domain eventually requires larger values, the type must be reconsidered.
The same principle applies to option_prices.price_paise.
Other column types worth understanding
| Column | Type | Reason |
|---|---|---|
name | VARCHAR(120) | Variable-length text with a defined maximum |
size | VARCHAR(8) | Short textual size identifier |
sort | INT | Integer ordering value |
is_active | TINYINT(1) | Small integer used conventionally as a boolean |
in_stock | TINYINT(1) | Same boolean convention |
created_at | DATETIME(3) | Date and time with millisecond precision |
A small but important detail: TINYINT(1) does not enforce a strict true/false constraint. It is still an integer type. If you need to prohibit values other than 0 and 1, that requires an explicit constraint.
DATETIME(3) stores three fractional-second digits, giving millisecond precision.
The default:
DEFAULT CURRENT_TIMESTAMP(3)automatically populates the creation time when one isn't supplied.
Unlike TIMESTAMP, DATETIME does not automatically convert values between the session time zone and UTC. Establish a consistent timezone convention for your application, normally UTC, and configure database sessions accordingly.
MySQL documentation: Numeric data types and Date and time types.
Keys and referential integrity
A relational database is useful because it can enforce relationships between entities rather than relying entirely on application code.
Primary keys
A primary key uniquely identifies a row in a table.
For restaurants:
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEYThis guarantees that two restaurants cannot have the same ID and that the ID cannot be NULL.
The items table also has its own primary key.
However, look at item_sizes:
PRIMARY KEY (item_id, size)This is a composite primary key: uniqueness is determined by the combination of both columns.
Consider these records:
| item_id | size | price_paise |
|---|---|---|
| 10 | Small | 9900 |
| 10 | Large | 13900 |
| 11 | Small | 11900 |
All three records are valid because the combinations are unique.
However, inserting another row with (10, Small) would violate the primary key, even if its price were different.
This is exactly what we want: an item can have multiple sizes, but it cannot have two prices for the same size in this table.
A composite primary key is particularly useful when the identity of a record naturally comes from multiple existing identifiers.
It also creates an index ordered by those columns, which will become important when we discuss InnoDB.
Foreign keys
A foreign key ensures that a relationship between two tables is valid.
Consider:
FOREIGN KEY (restaurant_id) REFERENCES restaurants(id)This declaration makes items.restaurant_id reference an existing restaurant.
What does InnoDB actually enforce?
On insert:
Suppose you insert an item with restaurant_id = 9999, but no restaurant with ID 9999 exists.
MySQL rejects the insert because it would create an invalid relationship.
On delete:
Suppose a restaurant has associated menu items.
Attempting to delete that restaurant while its child records still exist is rejected under the default restrictive behaviour.
The database does not silently delete the items.
Your schema does not declare ON DELETE CASCADE, so you should not assume cascading deletion.
The same logic applies to item sizes, option groups, options, and their associated prices.
An important detail: foreign keys need indexes
InnoDB requires an index on the referencing columns so that it can efficiently check and enforce relationships.
If a suitable index doesn't exist, InnoDB creates one automatically.
Look at:
CREATE TABLE items (
...
restaurant_id BIGINT UNSIGNED NOT NULL,
...
FOREIGN KEY (restaurant_id) REFERENCES restaurants(id),
INDEX idx_items_rest (restaurant_id, sort)
);The explicit index begins with restaurant_id, so it already supports the foreign-key lookup. InnoDB doesn't need to maintain another equivalent index solely for that constraint.
Similarly, the primary key on item_sizes begins with item_id, which supports its foreign-key relationship.
This is an important design principle: a suitable existing index can serve multiple purposes.
See MySQL 8.4 Foreign Key Constraints.
How InnoDB stores rows
This is one of the most important concepts in understanding MySQL performance.
In InnoDB, a table is organized around an index structure rather than being a simple collection of unrelated rows.
The clustered structure
A clustered index stores the table's actual row data in primary-key order.
When you define a primary key, InnoDB uses it to organize the table.
Consider these restaurant records:
| id | name |
|---|---|
| 101 | Central Kitchen |
| 105 | North Cafe |
| 108 | South Diner |
| 115 | East Restaurant |
The rows are organized according to their primary-key values.
The index is a B-tree, commonly explained using a root, intermediate nodes, and leaf nodes.
The internal nodes guide the search. The leaf pages contain the actual records for the clustered structure.
A simplified representation:


Searching for restaurant ID 108 means navigating the index to the corresponding leaf page.
The actual restaurant row is stored there.
This is why primary-key lookups are efficient: the index directly leads to the row.
An important consequence follows.
Choosing a primary key isn't just choosing a unique identifier. You're choosing the structure around which the table's records are organized.
For this course, the auto-incrementing IDs provide a predictable, stable ordering.
Secondary indexes
A secondary index provides another way to find records without searching the clustered structure from the beginning.
Your restaurants table has:
INDEX idx_rest_geo (lat, lng)This index is organized using latitude and longitude rather than the restaurant ID.
A simplified view:


Notice something important.
The secondary index stores the primary-key columns alongside its indexed columns.
In this case, the effective ordering includes:
(lat, lng, id)The ID acts as the logical locator for retrieving the actual row from the clustered structure.
When MySQL finds a matching entry in the secondary index, it can use that ID to locate the full row in the primary index.
This is commonly called a secondary-index lookup followed by a clustered-index lookup.
There is an important optimization called a covering index.
If the secondary index already contains every column required by a query, MySQL may satisfy that query directly from the index without fetching the complete row.
For example, a query that only needs lat, lng, and id can potentially be covered by idx_rest_geo.
However, a query that also needs name cannot be fully covered by that index.
Why primary-key size matters
Because InnoDB includes primary-key columns in secondary-index records, a larger primary key increases the storage requirements of every secondary index.
That is why short, stable primary keys are generally preferable.
It is also why modifying a primary-key value can be expensive: it affects the clustered organization and the corresponding secondary-index entries.
Composite indexes and column order
Your restaurant index is:
INDEX idx_rest_geo (lat, lng)This is a composite index because it contains more than one column.
The order is meaningful.
Think of the index as a sorted list of tuples:
(lat, lng)
(12.90, 77.60)
(12.90, 77.65)
(12.95, 77.55)
(12.95, 77.70)
(13.00, 77.60)
(13.00, 77.75)The database sorts by latitude first. When two records have the same latitude, longitude determines their relative order.
This is lexicographical ordering, similar to sorting words alphabetically by their first character and then by subsequent characters.
The leftmost-prefix rule
The leftmost-prefix rule describes which parts of a composite index can be used to locate rows efficiently.
Given:
INDEX idx_rest_geo (lat, lng)These predicates can make use of the index:
WHERE lat = ?WHERE lat = ? AND lng = ?WHERE lat BETWEEN ? AND ?WHERE lat = ? AND lng BETWEEN ? AND ?But this predicate cannot use the same index as an efficient lookup by longitude alone:
WHERE lng = ?Why?
Because the index is primarily ordered by latitude. All matching longitude values are not necessarily adjacent in the index.
To search efficiently by longitude independently, you would generally need an index beginning with longitude.
The important case: a range on latitude
Now consider:
WHERE lat BETWEEN 12.90 AND 13.10
AND lng BETWEEN 77.50 AND 77.80At first glance, it might seem that MySQL can use both columns equally to narrow the range.
It cannot do that in this case.
The first column, latitude, has a range condition rather than a single equality value.
Once MySQL enters a range of latitude values, the matching longitude values are spread across the corresponding latitude groups.
There is no single contiguous interval in the (lat, lng) ordering that independently represents both rectangular coordinate ranges.
Therefore:
- Latitude defines the principal index range.
- Longitude cannot further narrow that range into an equally selective contiguous interval.
- Longitude can still be evaluated as an additional index condition or filter.
This distinction is extremely important.
The second column is not useless. It simply cannot narrow the index range in the same way it could when latitude had an equality condition.
InnoDB can use Index Condition Pushdown in appropriate cases to evaluate conditions using indexed values before fetching full rows.
This can reduce unnecessary clustered-index lookups even when those conditions don't narrow the initial range.
Reading EXPLAIN for the restaurant listing query
Now let's connect these concepts to the query you will implement later this week.
The first restaurant-listing endpoint will support geographic filtering and cursor pagination.
Its query shape is:
SELECT id, name, lat, lng
FROM restaurants
WHERE is_active = 1
AND lat BETWEEN ? AND ?
AND lng BETWEEN ? AND ?
AND id > ?
ORDER BY id
LIMIT ?;There are four relevant conditions:
- Only active restaurants should be returned.
- Latitude must be within the requested range.
- Longitude must be within the requested range.
- Only IDs greater than the cursor should be returned.
The results must be ordered by ID.
You already have two useful indexes:
| Index | Column order | Primary purpose |
|---|---|---|
| PRIMARY | id | Cursor filtering and ID ordering |
| idx_rest_geo | lat, lng | Geographic filtering |
Neither index solves every part of the query equally well.
The primary index can efficiently scan IDs greater than the cursor and preserve the required ordering. It must then filter the geographic conditions.
The geographic index can efficiently narrow the latitude range and evaluate other indexed conditions. However, its ordering is by latitude and longitude, not restaurant ID. Returning rows in ID order can require an additional sorting operation.
This is an optimizer trade-off.
What EXPLAIN tells you
EXPLAIN shows the execution plan MySQL intends to use for a query.
Run:
EXPLAIN
SELECT id, name, lat, lng
FROM restaurants
WHERE is_active = 1
AND lat BETWEEN 12.90 AND 13.10
AND lng BETWEEN 77.50 AND 77.80
AND id > 1000
ORDER BY id
LIMIT 50;The literal values make this example directly executable. Your application will use prepared parameters.
The traditional output contains several columns. Focus on these first:
| Column | Meaning |
|---|---|
type | How MySQL accesses the table |
possible_keys | Indexes that could potentially be used |
key | The index actually selected |
rows | Estimated number of rows MySQL expects to examine |
Extra | Additional information about query execution |
Understanding type
The type column describes the access method.
Some common values:
| Type | Meaning |
|---|---|
const | A single row found using a unique lookup |
eq_ref | A unique lookup for each preceding row in a join |
ref | Lookup using a non-unique index |
range | Scan of one or more index ranges |
index | Full scan of an index |
ALL | Full table scan |
For this exercise, pay particular attention to range.
A range scan means MySQL can use an index interval to retrieve a subset of records rather than scanning the entire table.
It is often a useful sign, but don't automatically assume that every range scan is efficient. The number of candidate rows still matters.
Worked example: inspecting the geographic index
To isolate the geographic access path, run a diagnostic version using FORCE INDEX.
EXPLAIN
SELECT id, name, lat, lng
FROM restaurants FORCE INDEX (idx_rest_geo)
WHERE is_active = 1
AND lat BETWEEN 12.90 AND 13.10
AND lng BETWEEN 77.50 AND 77.80
AND id > 1000
ORDER BY id
LIMIT 50;A possible illustrative plan is:
| Field | Illustrative value |
|---|---|
| table | restaurants |
| type | range |
| key | idx_rest_geo |
| rows | 1200 |
| Extra | Using index condition; Using where; Using filesort |
The estimated row count is illustrative, not a prediction for your database.
Let's interpret it.
1. type = range
MySQL is scanning a range of index entries.
Here, the principal range comes from the latitude condition.
2. key = idx_rest_geo
MySQL is accessing the geographic index.
This tells you that the index is actually being selected, rather than merely appearing in possible_keys.
3. rows = 1200
The optimizer estimates that approximately 1200 index entries will need to be examined.
This is an estimate, not an actual measurement.
4. Using index condition
MySQL can evaluate eligible conditions using values available in the index before retrieving the full row.
For example, longitude can be checked against the indexed value.
5. Using where
Additional filtering is applied to determine which rows satisfy the complete condition.
6. Using filesort
MySQL needs an additional sorting operation to produce the required ID ordering.
Despite its name, filesort does not necessarily mean data is written to disk. It describes an additional sorting operation.
What if MySQL chooses PRIMARY instead?
This is not necessarily wrong.
The optimizer may choose the primary index because:
- The cursor condition
id > ?defines a range. - The index already produces rows in the required ID order.
- It may be cheaper to scan in ID order and filter coordinates than to scan the geographic index and sort the matching records.
In that case, you might see:
| Field | Illustrative value |
|---|---|
| type | range |
| key | PRIMARY |
| Extra | Using where |
This plan uses the primary-key range for cursor pagination.
It does not mean the geographic index is being used.
The optimizer makes its decision based on statistics, estimated selectivity, query conditions, and sorting costs.
Do not use FORCE INDEX as your default production solution. It is useful for investigating a candidate index, but forcing an access path can make performance worse when data distribution changes.
For more realistic estimates, load representative data and ensure statistics are current.
MySQL also provides EXPLAIN ANALYZE, which actually executes a query and reports iterator-level timing and row information. Use it when you need to compare estimated execution with observed execution.
Putting the ideas together
Before you write the migration, make sure you can reason through the following:
- The primary identifiers use
BIGINT UNSIGNEDbecause they need a large, consistent identifier space. - Geographic coordinates use
DECIMAL(9,6)to preserve exact decimal values. - Prices use integer paise to avoid floating-point monetary arithmetic.
DATETIME(3)preserves millisecond precision.- Primary keys establish row identity and, in InnoDB, determine clustered row organization.
- Foreign keys prevent invalid relationships and require suitable supporting indexes.
- Composite indexes are ordered structures whose column order determines which searches they support.
- A range on the first indexed column limits how the next column can narrow the access range.
- EXPLAIN provides evidence about the optimizer's chosen access path, estimates, filtering, and sorting.
The larger lesson is that database design and query design cannot be treated independently.
You should understand the queries your application will execute before deciding which indexes are worth maintaining.
Knowledge assessment
Why does the schema use DECIMAL(9,6) for coordinates and integer paise for menu prices instead of using FLOAT for both?
Practical applications
Exercise 2.3: Write the restaurant and menu migrations
In this exercise, you'll translate the restaurant and menu data model into versioned MySQL migrations using golang-migrate.
You'll apply everything from this lesson:
- Choose the specified column types.
- Define primary and composite primary keys.
- Declare foreign-key relationships.
- Create the geographic and menu-item indexes.
- Ensure the schema matches the expected relationships exactly.
The objective is to make the database enforce the structure your application depends on.
Later in Module 3: Keyset pagination
You'll return to idx_rest_geo when implementing the first restaurant-listing endpoint.
That lesson will build on composite-index ordering, range access, deterministic pagination, and EXPLAIN to understand the trade-offs between geographic filtering and ID-based ordering.
By then, you should be able to explain not only how to write the query, but also why MySQL might choose one index over another.
References
Everything above is explained on this page; these are where it comes from (MySQL 8.4, InnoDB).
- MySQL 8.4: Introduction to InnoDB
- MySQL 8.4: Clustered and Secondary Indexes
- MySQL 8.4: Multiple-Column Indexes
- MySQL 8.4: EXPLAIN Output Format
- MySQL 8.4: FOREIGN KEY Constraints
- MySQL 8.4: Fixed-Point Types (DECIMAL)
- MySQL 8.4: Physical Structure of an InnoDB Index
- MySQL 8.4: Range Optimization (incl. skip scan)
- MySQL 8.4: Index Condition Pushdown