Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy: does Column with ForeignKey creates index automatically?

Tags:

sqlalchemy

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!

like image 807
Vitalii Ponomar Avatar asked Jan 17 '12 06:01

Vitalii Ponomar


People also ask

Does foreign key automatically create an index?

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.

Do foreign keys get an index?

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.

Does unique constraint create index?

Yes, absolutely. A unique constraint creates a unique index.

Does SQL Server automatically index foreign keys?

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.


2 Answers

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.

like image 180
van Avatar answered Jun 29 '23 03:06

van


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.

like image 32
FluxLemur Avatar answered Jun 29 '23 02:06

FluxLemur