The Python Oracle

Why are the foreign keys in a SQLAlchemy Association Object marked as primary keys?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Realization

--

Chapters
00:00 Why Are The Foreign Keys In A Sqlalchemy Association Object Marked As Primary Keys?
00:44 Accepted Answer Score 5
01:55 Thank you

--

Full question
https://stackoverflow.com/questions/4799...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #sqlalchemy #flasksqlalchemy

#avk47



ACCEPTED ANSWER

Score 5


This is not unique to SQLAlchemy. This is how many-to-many relationships are designed, which is based on the principles of Relational Database design.

In a many-to-many relationship, there is a need for an additional table, also called association table, which maps entries from the first table with corresponding entries from the second table.

When the association table is defined, we need some primary key to uniquely identify records in the association table. Having a primary key creates an index, which speeds up joining operations and the search for records.

So, why have all the Foreign keys as a part of the Primary for the association table? This is to make sure there are no duplicate entries of record a of table A and record b of Table B. In other words, to ensure uniqueness in the relationship, thus, avoiding duplication of relationships.

Association table can be created without declaring the Foreign keys as Primary keys. But this is not advisable. By doing so, the join operations become slow unless indexes are created explicitly. And, there is a good chance of having duplicated records of a relationship between Table A and Table B