Does Column with ForeignKey creates index automatically?
Or I need to do that manually adding index=True
?
some_field = Column(Integer, ForeignKey(SomeModel.id))
Thanks!
When you define a foreign key constraint in your database table, an index will not be created automatically on the foreign key columns, as in the PRIMARY KEY constraint situation in which a clustered index will be created automatically when defining it.
MySQL requires that foreign key columns be indexed; if you create a table with a foreign key constraint but no index on a given column, an index is created. Information about foreign keys on InnoDB tables can also be found in the INNODB_FOREIGN and INNODB_FOREIGN_COLS tables, in the INFORMATION_SCHEMA database.
Yes, absolutely. A unique constraint creates a unique index.
SQL Server will not automatically create an index on a foreign key. Also from MSDN: A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.
You do need to either specify index=True
or create an Index
object explicitly:Index('myindex', mytable.c.col1, mytable.c.col2, unique=True)
, which allows more control over other parameters of the index, such as the name and support for more than one column.
See Indexes for more information.
As van's answer indicates, you should explicitly add an index as indicated by the docs.
The implementation of foreign keys is database specific, and some DBs such as MySQL will still automatically create an index for foreignkey column, but others will not. See discussion in comments above.
e.g from MySQL docs:
MySQL requires that foreign key columns be indexed; if you create a table with a foreign key constraint but no index on a given column, an index is created.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With