Search code examples
mysqlsqlsql-inserthostname

INSERT a row only if @@hostname equals a certain value


Is it possible to use a WHERE clause somehow (or any other way) in an INSERT query so it only works if the @@hostname variable is a certain value? For example:

INSERT INTO table_name
    (field_1, field_2)
VALUES
    ('foo', 'bar')
WHERE @@hostname = 'url.to.host.here';

Solution

  • Note: @@hostname is the MySQL hostname.

    You can invalid a select query like this because the MySQL optimizer sees this as an impossible WHERE.

    SELECT
       'field_1'
     , 'field_2'
    FROM
      DUAL
    WHERE 0;
    

    MySQL has an INSERT INTO ... SELECT query so when you use:

    INSERT INTO
       table_name (
         field_1
       , field_2
      )
      SELECT
          'field_1'
        , 'field_2'
       FROM
         DUAL
       WHERE 0
    

    The INSERT INFO will not be executed.

    When you use:

    INSERT INTO
       table_name (
         field_1
       , field_2
      )
      SELECT
          'field_1'
        , 'field_2'
       FROM
         DUAL
       WHERE 1;
    

    The INSERT INTO will be executed. See demo http://sqlfiddle.com/#!9/5623f/1

    With the @@hostname check:

    INSERT INTO
       table_name (
         field_1
       , field_2
      )
      SELECT
          'field_1'
        , 'field_2'
       FROM
         DUAL
       WHERE IF(
         @@hostname = 'ip-10-0-0-15'
         , 1
         , 0
       );
    

    See demo http://sqlfiddle.com/#!9/d9081/4.

    As a sidenote you can also use this to "support" CHECK (MySQL doesn't support CHECK with CREATE TABLE statement) on columns normally you need triggers to do this.

    See demo http://sqlfiddle.com/#!9/9dfa2/1.