1

I'm relatively new to sqlite and databases in general. I've successfully setup a schema of 4 tables, each having a foreign key pointing to its parent table. The schema also has the foreign key constraint set on the child keys.

Performing a query where every table is joined with the SELECT * FROM...JOIN...ON ......... works without issue, but it is laborious manually connecting the keys.

My question is: Is it possible to perform a query/join of the tables without the ON statement which links each parent/child key relationship? Since this was already established in the schema definition, this seems to be redundant. I'm trying to simplify the sql command and make use of the parent/child relationship already defined. When I perform said query but omit the ON statements, the results are not what I expected. Any guidance is appreciated.

1 Answer 1

1

A foreign key constraint is just a constraint, i.e., it prevents you from inserting data that would violate the constraint.

Foreign key constraints have no effect on queries; if you want to join tables through these values, you still have to write the join. (Why? Because the SQL standard has always said so, so changing it would break backwards compatibility.)

The only way to avoid the ON is by giving the columns the same name in the parent and child tables so that you can use the USING clause instead:

SELECT ... FROM ParentTable JOIN ChildTable USING (ParentID);

(And this is less typing than a hypothetical ... JOIN ... USING FOREIGN KEY ConstraintName.)

1
  • Thank you for your comments and suggestions, I think it's the right answer despite what I was hoping for, there's no free lunch as the saying goes.
    – Bill
    Commented May 26, 2020 at 0:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.