title: How to do 'if not exists in myql' in function
body: <p>I'm trying to make a function to insert a new table with a function, and for this I need to nest the id of one table with the other, I do this with a select and I store the id in a variable, I want to do that if the searched id does not exist, it returns that it does not exist in the table, but it does not work, it returns any id directly, it returns the id of the previous request that went well.</p>
  <p><strong>Function</strong></p>
  <pre><code>DELIMITER &amp;&amp;
  CREATE FUNCTION db_test.test_function_9( gender VARCHAR( 255 ) ) RETURNS VARCHAR( 255 )
  BEGIN
      IF NOT ( ( SELECT @gender_id := sub FROM db_test.sub WHERE detail = gender ) ) THEN
          BEGIN
              RETURN CONCAT( 'Does not exists: ', gender );
          END;
      ELSE
          BEGIN
              RETURN CONCAT( 'Exists and is: ', gender, ' ' ,@gender_id );
          END;
      END IF;
  END &amp;&amp;
  </code></pre>
  <p>Tests:</p>
  <pre><code>SET @response = db_test.test_function_9( 'male' );
  SELECT @response;
  </code></pre>
  <p>Returns:</p>
  <pre><code>Exists and is: male 7
  </code></pre>
  <p>This test should fail</p>
  <pre><code>SET @response9 = db_test.test_function_9( 'wowwowowow' );
  SELECT @response9;
  </code></pre>
  <p>Returns:</p>
  <pre><code>Exists and is: wowwowowow 7
  </code></pre>
  <p>Next test:</p>
  <pre><code>SET @response9 = '';
  SET @response9 = db_test.test_function_9( 'female' );
  SELECT @response9;
  </code></pre>
  <p>Returns:</p>
  <pre><code>Exists and is: female 8
  </code></pre>
  <p>And last:</p>
  <p><a href="https://i.stack.imgur.com/mrP0a.png" rel="nofollow noreferrer">enter image description here</a></p>
  <p><strong>If I don't use <code>NOT</code>, everything works fine, but I need not to avoid having so much code.</strong></p>