Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Unique constrain multiple columns performance optimization

I see tons of questions about unique constrains on multiple questions but none that match what I am specifically looking for. If this is a duplicate of one, I apologies.

I have a table that is just: tableA_id tableB_id

My primary key is a unique constraint on both tables, and i have a index on both columns. Both are also primary keys to their respected tables.

If tableA is likely to have say 10,000,000 rows and table B to have say 2,000,000 rows, it is more likely that TableB will be in this constraint far less times. That being sad, is it more optimized when I am making my unique constraint to put TableB as the first column since there are less to search for, TableA (if so why), or it makes no difference as it does not search one first then the other, rather goes 1 by one looking at both.

Thanks in advance

like image 200
Anthony Greco Avatar asked Jun 29 '26 09:06

Anthony Greco


1 Answers

It is usually recommended to put a column with more distinct values on the left in a composite index. That results in a more selective index, which is better for finding a specific value.

A quote form MySQL docs:

To eliminate rows from consideration. If there is a choice between multiple indexes, MySQL normally uses the index that finds the smallest number of rows (the most selective index)

But I have an impression that you seem to be trying to optimize failures on inserts to the table. And if you have more writes to the table than reads and most of the writes are duplicates, then you are probably right. But even in the latter case, MySql will need to check the other column for uniqueness. Thus, it is still better to put first a column with more distinct values.

like image 56
newtover Avatar answered Jul 02 '26 00:07

newtover



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!