Jump to content

MySQL Insert with SELECT statement. If result of select is NULL, then a value else result


Jagand

Recommended Posts

I am trying to write a MySQL INSERT statement which has a SELECT query. Select query can result in NULL. If result is NULL, I want to 1 to be the value for the field. If result is not NULL, I want retrieved value. Below is the MySQL I have coded but it seems wrong. What would be the right statement

 

INSERT  
INTO table        
(         
primary_id        
,sequence_number        
,text        
,text2        
,text3      
)select          
30         
,((SELECT 
MAX(sequence_number) + 1 FROM table     
WHERE primary_id = 30) 
AS seq_num 
IF (seq_num 
= NULL,1,seq_num))         
,'text'         
,'text2'
,'text3
 

 

Thank you. That worked. So, the script that worked is below, for other's reference.

 

INSERT
  INTO table        (
         primary_id
        ,sequence_number
        ,text

        ,text2

        ,text3
      )
select
          30
         ,(SELECT ifnull ((MAX(sequence_number) + 1), 1)
      FROM table
     WHERE primary_id = 30)
         ,'text'

         ,'text2'

         ,'text3

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.