title: MySQL trigger to update a field to the value of id
body: <p>I would like to have a trigger to perform following operation for inserted records:</p>
  
  <pre><code> # pseudocode
   if new.group_id is null
      set new.group_id = new.id
   else
      # don't touch it
   end
  </code></pre>
  
  <p>More clearly: say I have one table with three columns: <code>id</code> primary key, <code>group_id</code> int, <code>value</code> varchar.</p>
  
  <p>When I insert with <code>group_id</code> like that:</p>
  
  <pre><code>INSERT INTO table(value, group_id) VALUES ('a', 10)
  </code></pre>
  
  <p>I'd like to have:</p>
  
  <pre><code>id | group_id | value
  ---+----------+------
   1 |       10 | a
  </code></pre>
  
  <p>but when I omit <code>group_id</code>:</p>
  
  <pre><code>INSERT INTO table(value) VALUES ('b')
  </code></pre>
  
  <p>it should be automatically set to the <code>id</code> of this record:</p>
  
  <pre><code>id | group_id | value
  ---+----------+------
   2 |        2 | b
  </code></pre>
  
  <p>Is it possible with a trigger? (I know I can update the record after inserting but having the trigger would be nicer.)</p>