title: How to create FOREIGN KEYS for non-existent table during initial database setup?
body: <p>I have a small database originally developed using SQLite. My desktop application automatically sets-up the database tables when the user initially launches the application.</p>
  
  <p><strong>Problem</strong>
  Several tables have FOREIGN KEY constraints. Assume I have Table A, Table B, and Table C. A has a FOREIGN KEY constraint with C. But as I do the initial table generation, SQLExceptions are thrown each time saying something like:</p>
  
  <blockquote>
    <p>Constraint 'SQL130319142644383' is invalid: referenced table
    PREDICTIONRUN does not exist.</p>
  </blockquote>
  
  <p>(Note: I cannot simply reorganize the tables because of other FOREIGN KEY issues.)</p>
  
  <p>So, how do I create the tables with FOREIGN KEY constraints?</p>
  
  <p>Example</p>
  
  <pre><code>if (! this.checkIfTableExists("DocumentClassification", conn)) {
                  sql.setLength(0) ;
                  sql.append("CREATE TABLE DocumentClassification (  " ) ;
                  if (dbtype.equalsIgnoreCase("javadb")) {
                      sql.append("    classificationid INTEGER PRIMARY KEY NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1) , " ) ; 
  
                  } else {
                      sql.append("    classificationid INTEGER PRIMARY KEY, " ) ; 
                  }
                  sql.append("       classid INTEGER, " ) ;
                  sql.append("       documentid INTEGER,  " ) ;
                  sql.append("       predictionrunid INTEGER, " ) ;
  
                  sql.append("       matterid VARCHAR(512), " ) ;
                  sql.append("       datereadable VARCHAR(2048),  " ) ;
                  sql.append("       date BIGINT,  " ) ;
                  sql.append("       note VARCHAR(" + maxint + "),  " ) ;
                  sql.append("       FOREIGN KEY ( classid) REFERENCES Classes (ClassID)," ) ;
                  sql.append("       FOREIGN KEY ( documentid) REFERENCES MatterDataset (id),  " ) ;
                  sql.append("       FOREIGN KEY (predictionrunid) REFERENCES PredictionRun (predictionrunid)" ) ;
                  sql.append("    )  " ) ;
                  // Create the table
                  sqlstatement.executeUpdate(sql.toString()); 
              }
  </code></pre>
  
  <p><strong>Databases Used</strong>
  JavaDB/Derby
  SQLite (via Xerial Driver) (no problem here because SQLite does not seem to enforce the constraint on creation)</p>
  
  <p><strong>Development</strong>
  Java 7</p>