title: SQL insert foreign key if not exists
body: <p>Suppose I have a table <code>user</code>:</p>
  <pre><code>PK id: int
  firstname: varchar
  lastname: varchar
  FK group_id: int
  </code></pre>
  <p>And a table <code>group</code>:</p>
  <pre><code>PK id: int
  name: varchar
  </code></pre>
  <p>Now I want to be able to send to the server a student JSON object that contains:</p>
  <pre><code>{
      &quot;firstname&quot;: &quot;john&quot;,
      &quot;lastname&quot;: &quot;doe&quot;,
      &quot;group&quot;: &quot;group_name&quot;
  }
  </code></pre>
  <p>How to insert it in the tables? How can I ensure that a row with &quot;group_name&quot; exists and if not, create it and then and only then insert the student with the corresponding FK group_id?</p>
  <p>What I would do is something like:</p>
  <ol>
  <li>select id from group where name=&quot;group_name&quot;</li>
  <li>if not exists:
  insert into group values (&quot;group_name&quot;)</li>
  <li>insert into user values(&quot;john&quot;, &quot;doe&quot;, the_existing_or_newly_inserted_group_id)</li>
  </ol>
  <p>But it seems a bit overkill in terms of number of requests.</p>