Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL: update with left outer self join ignored

I want to update the column leaf_category with TRUE where the category is not a parent category. It works as a select statement:

 select 
     c1.id, c1.name, c1.slug, c1.level, c2.parent_id, c2.name, c2.slug, c2.level 
 from
     catalog_category c1 
 left outer join 
     catalog_category c2 on 
     (c1.id = c2.parent_id)
 where 
     c2.parent_id is null;

However, the corresponding UPDATE sets all the columns to TRUE.

update catalog_category 
set leaf_category = True
from
    catalog_category c1 
left outer join 
    catalog_category c2 on 
    (c1.id = c2.parent_id)
 where 
     c2.parent_id is null;

Is an UPDATE like that possible at all?

like image 667
slooow Avatar asked Oct 15 '25 13:10

slooow


1 Answers

You are just missing a connecting WHERE clause:

UPDATE catalog_category c
SET    leaf_category = true
FROM   catalog_category c1 
LEFT   JOIN catalog_category c2 ON c1.id = c2.parent_id
WHERE  c.id = c1.id
AND    c2.parent_id IS NULL;

This form with NOT EXISTS is probably faster, doing the same:

UPDATE catalog_category c
SET    leaf_category = true
WHERE  NOT EXISTS (
    SELECT FROM catalog_category c1
    WHERE  c1.parent_id = c.id
    );

The manual for UPDATE.

Related:

  • Select rows which are not present in other table
like image 82
Erwin Brandstetter Avatar answered Oct 18 '25 07:10

Erwin Brandstetter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!