title: Foreign key to table A or table B
body: <p>Consider a situation where I define an object, a group of objects, then a table that links them together:</p>
  
  <pre><code>CREATE TABLE obj (
    id INTEGER PRIMARY KEY,
    name text
  ) ;
  
  CREATE TABLE group (
    id INTEGER PRIMARY KEY ;
    grpname TEXT
  ) ;
  
  CREATE TABLE relation (
    objid INTEGER,
    grpid INTEGER,
    PRIMARY KEY (objid, grpid)
  ) ;
  </code></pre>
  
  <p>I am looking for cascade delete when applicable so I add the foreign key</p>
  
  <pre><code>ALTER TABLE relation
  ADD FOREIGN KEY (objid)
  REFERENCES obj(id)
  ON DELETE CASCADE ;
  
  ALTER TABLE relation
  ADD FOREIGN KEY (grpid)
  REFERENCES group(id)
  ON DELETE CASCADE ;
  </code></pre>
  
  <p>So far is all OK. Now suppose I want to add support for group of groups. I am thinking to change the relation table like this:</p>
  
  <pre><code>CREATE TABLE relation_ver1 (
    parent INTEGER,
    child INTEGER,
    PRIMARY KEY (parent, child)
  ) ;
  ALTER TABLE relation_ver1
  ADD FOREIGN KEY (parent)
  REFERENCES group(id)
  ON DELETE CASCADE ;
  </code></pre>
  
  <p>Here I get to the question: I would like to apply cascade delete to child too, but I do not know here if child refers to a group or object. </p>
  
  <p><em>Can I add a foreign key to table obj or group?</em></p>
  
  <p>The only solution I have found do fare is add child_obj and child_grp fields, add the relative foreign keys and then, when inserting e.g an object use a 'special' (sort of null) group, and do the reverse when inserting subgroup.</p>