HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Finding entries which have no foreign key mapping in any other table

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
tableanyforeignfindingwhichmappingotherhavekeyentries

Problem

Let's say I have Table A, which has one column id, which is unique within the table. I have multiple other tables: Table B, Table C, ..., Table N. Each of these tables has a column A_id, which is a foreign key to id of Table A.

Is there an elegant way to get all rows of Table A which are not mapped to as a foreign key by any of the other tables? Ideally, I would like to see if there's a way to do this without having to type in a complicated query that involves manually querying each other dependent table, but any approach would be appreciated.

Solution

This can be accomplished with a NOT EXISTS () clause in your WHERE clause.

SELECT id
FROM A
WHERE NOT EXISTS (
SELECT id
FROM B
WHERE A.ID = B.A_id
)
AND NOT EXISTS (
SELECT id
FROM C
WHERE A.ID = C.A_id)
...
...


You could generate this query programmatically by querying the schema for tables that have a foreign key on A.id, and then iterating over them to create the WHERE clause...

Code Snippets

SELECT id
FROM A
WHERE NOT EXISTS (
SELECT id
FROM B
WHERE A.ID = B.A_id
)
AND NOT EXISTS (
SELECT id
FROM C
WHERE A.ID = C.A_id)
...
...

Context

StackExchange Database Administrators Q#211265, answer score: 3

Revisions (0)

No revisions yet.