Search code examples
sqloracle-databasesubquerycasesql-insert

How to write a query so that I can insert a row based on another row value


Can someone help me please to frame a SQL query so that I can insert a new row based on CONDITION. Say if there is any row with a Property as "Name" then I need to insert a new row PROPERTY, VALUE --> ("Boss", "Is present") else PROPERTY, VALUE -->("Boss", "Is Absent"). Kindly note that I don't want to use "dual" table as I am not using oracle DB. Thank you in advance. Below is my DB table structure.

enter image description here

EDIT 1: Property is the primary key.


Solution

  • You can use a case expression and an exists condition:

    insert into mytable (property, value)
    select 'Boss',
        case when exists(select 1 from mytable where property = 'name') 
            then 'isPresent' 
            else 'isAbsent' 
        end
    from dual