Search code examples
mysqlsqluniquedistinct-values

How to Generate a Value that is Unique from the Values of Another Table in SQL?


I am trying to generate a value for a column in table 1, but I want it to be distinct from all other values of a certain column in table 2. Is there a way to do this?


Solution

  • An insert using a select may work - Use which ever aggregate function, or custom function is most appropriate, I am using MAX to get MAX ID of an integer column.

    INSERT INTO table1 (id, desc)
    SELECT MAX(id)+1, 'Hello World!' FROM table2
    

    If the field your inserting to is string based you can just insert a UUID

    INSERT INTO table1 VALUES (UUID(), 'Hello World')