Question

I have a table with exercises inside and for each exercise some illustrations in another table. I would like to insert illustrations and keep it ordered with a 'position' attribute. So when I add an illustration the 'position' attribute is equal to the number of illustrations for the given exercise (because position starts at 0).

So I tried something like that :

INSERT INTO illustrations (path, date_creation, id_exercise, position) 
VALUES (
    "2789c0bdda6981fadd87c30af74dfc5d.jpg", 
    "1384104485", 
    "4",  
    (SELECT COUNT(I.id)  
     FROM illustrations I 
     WHERE I.id_exercise = 4 
     GROUP BY I.id_exercise
    )
)

This query works fine but only if I have already at least one illustration for the exercise. Otherwise the sub-query returns null and I obtain this error : "Column 'position' cannot be null" which is logical. Typically I would put a zero if the select sub-query returns null. I tried with ISNULL() but I don't find a correct syntax. Any suggestion ?

Was it helpful?

Solution

Use COALESCE to change the null result of the subquery to a default value.

INSERT INTO illustrations (path, date_creation, id_exercise, position) 
VALUES (
   "2789c0bdda6981fadd87c30af74dfc5d.jpg", 
   "1384104485", 
   "4",  
   COALESCE((SELECT COUNT(I.id)  
     FROM illustrations I 
     WHERE I.id_exercise = 4 
   ), 0)
)

Also the GROUP BY was unnecessary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top