r/learnSQL • u/younesWh • Jul 23 '26
two relations for one column
does it possible to give a column choice to choose between two foreign keys
the case: that I Have comments table that have a parent_id column that could be either from posts table or comments table how I can implment that in sqlite3 .
3
Upvotes
View all comments
Show parent comment
1
u/dastanis2 Jul 24 '26
To help prevent creating orphaned records, you'll definitely want to look up the correct child ID value to insert into the foreign key column either before inserting the record or as part of the INSERT statement.
Once you know the correct logic to use to look up the correct value in the child table, you can determine the correct ID value to insert into the foreign key ID column and use either joins in your INSERT statement or populate variables before executing your INSERT statement to use in your INSERT statement.
I'm not sure the EXISTS clause will help you determine the correct ID value to insert since EXISTS only returns a true or false (boolean/bit) value and is used to help filter in/out entire rows, not determine specific values in columns.