Question

I'm using MySQL with InnoDB.

I don't need a primary key in terms of semantics, so does a primary key (or rather, a unique index) make for faster queries than a non-unique index?

I have two columns that are suitable for indexes but are non-unique. However, combinations of the two columns are always unique. The columns are also non-null.

Is it better to just set the two non-unique columns as indexes, or to instead create a primary key over the combination of the two columns?

The access pattern will normally be modifying two or four rows where the first column is a given value (and the second column will be different, as I mentioned every combination is unique).

For example, col1 and col2 being like

1 1
1 2
1 3
1 5
2 1
2 2
2 3
2 5
3 1
3 2
3 3

an example would be change rows (1, 2) and (1, 3) at a time

A follow up question is about datatypes. col1 fits in a smallint and col2 in a tinyint. However, I'm not sure what the performance implications are of using smaller-than-int types and also different types, when combining into a single index. The manual says multiple columns are concatenated when used for primary key. Is it better to use the same type, smallint? Or even use ints? In terms of memory access, are not aligned, full word accesses the fastest? Does this have an impact here?

Was it helpful?

Solution

Whether you use it or not, InnoDB always has a primary key, kind of. InnoDB uses a clustered index for storing the data, which basically means that primary key and the data are in the same place. If you don't define a suitable index, it creates an internal index. This also means that the primary key is "free"; it doesn't require any extra space since the data is stored in the index. If you always find rows to update by using both columns, you should definitely make a composite primary index. Even if you don't use two columns every time to filter data, you will probably benefit from a composite primary index.

As for the data types, I'd make both as small as possible. I'm not sure about the specifics of how the index is handled in memory, but you're probably not going to be able to measure any significant difference due to memory access differences and the smaller index size wouldn't hurt.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top