Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update with Case Statement fails because of nulls

I have a column in a table of which I would like to swap the current value with another for particular entries. I am getting a no null constraint when clearly I am not leaving it empty.

UPDATE bet.betEntry
SET direction= 
            CASE 
                WHEN (direction = '599065F7-96A9-4DF5-8577-2203BE9AA2E0') THEN  'ABD92DB9-58D8-4C60-8A34-4C00EBBAB4A5'
                WHEN (direction = 'ABD92DB9-58D8-4C60-8A34-4C00EBBAB4A5') THEN '599065F7-96A9-4DF5-8577-2203BE9AA2E0'
         END    
FROM bet.betEntry be JOIN bet.fixture f ON  be.fixtureId = f.fixtureId
WHERE f.fixtureDate > '2019-01-12 13:29:00.000'
like image 755
Chanter128 Avatar asked Mar 04 '23 11:03

Chanter128


1 Answers

Add a where clause:

UPDATE bet.betEntry
    SET direction = (CASE WHEN direction = '599065F7-96A9-4DF5-8577-2203BE9AA2E0'
                          THEN  'ABD92DB9-58D8-4C60-8A34-4C00EBBAB4A5'
                          WHEN direction = 'ABD92DB9-58D8-4C60-8A34-4C00EBBAB4A5'
                          THEN '599065F7-96A9-4DF5-8577-2203BE9AA2E0'
                     END)   
FROM bet.betEntry be JOIN
     bet.fixture f
     ON  be.fixtureId = f.fixtureId
WHERE f.fixtureDate > '2019-01-12 13:29:00.000' AND
      direction IN ('599065F7-96A9-4DF5-8577-2203BE9AA2E0', '599065F7-96A9-4DF5-8577-2203BE9AA2E0');

You could also solve this with ELSE direction. However, that is not as good because it attempts to update rows that do not need to be updated.

like image 125
Gordon Linoff Avatar answered Mar 27 '23 07:03

Gordon Linoff