Stuck at inserting records into MariaDB conditionally



  • I know about insert ignore. That's of no use, because MariaDB does not consider NULL to be part of the uniqude index.

    Therefore I have to use if ... else.

    But this code does not run:

    select *
    from Nodes 
    where `Key` = 'FAQPage';
    

    if not found_row() then
    insert into Nodes (Key, ParentId)
    values ('FAQPage', null)
    end if;

    How can I use if ... else to conditionally insert data in MariaDB?



  • INSERT INTO Nodes (`Key`, ParentId)
    SELECT @key, @parentid
    WHERE NOT EXISTS ( SELECT NULL
                       FROM Nodes
                       WHERE `Key`  @key
                         AND ParentId  @parentid )
    

    @key and @parentid are placeholders for the values to be inserted.

    So if the row with the values to be inserted already exists then the subquery detects this, and none rows is inserted.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2