I have a postgres table (lets call this table Events
) with a composite foreign key to another table (lets call this table Logs
). The Events table looks like this:
CREATE TABLE Events (
ColPrimary UUID,
ColA VARCHAR(50),
ColB VARCHAR(50),
ColC VARCHAR(50),
PRIMARY KEY (ColPrimary),
FOREIGN KEY (ColA, ColB, ColC) REFERENCES Logs(ColA, ColB, ColC)
);
In this case, I know that I can efficiently search for Events by the primary key, and join to Logs.
What I am interested in is if this foreign key creates an index on the Events table which can be useful even without joining. For example, would the following query benefit from the FK?
SELECT * FROM Events
WHERE ColA='foo' AND ColB='bar'
Note: I have run the POSTGRES EXPLAIN for a very similar case to this, and see that the query will result in a full table scan. I am not sure if this is because the FK is not helpful for this query, or if my data size is small and a scan is more efficient at my current scale.
A foreign key is a constraint, a relationship between two tables - that has nothing to do with an index per se.
an index on a table is a data structure that makes random access to the rows fast and efficient. It helps to optimize the internal organization of a table as well. A foreign key is simply a pointer to a corresponding column in another table that forms a referential constraint between the two tables.
PostgreSQL does not automatically create an index on the columns on which a foreign key is defined. If you need such an index, you will have to create it yourself.
It is usually a good idea to have such an index, so that modifications on the parent table that affect the referenced columns are efficient.
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