In PostgreSQL, I have a table named users with data that looks like so:
| id | favorites |
|---|---|
| 1 | { "shapes": ["Triangle", "Square", "Rectangle", "Circle"] } |
| 2 | { "shapes": ["Rectangle", "Triangle", "Circle"] } |
| ... | ... |
Where favorites is a JSONB column.
I want to remove shapes "Square" and "Circle" to all users' favorite shapes. This is a list of shapes to remove which can be of variable length. The output table should look like so:
| id | favorites |
|---|---|
| 1 | { "shapes": ["Triangle", "Rectangle"] } |
| 2 | { "shapes": ["Rectangle", "Triangle"] } |
| ... | ... |
How do I do that in one query?
Limitations:
- The array of shapes to remove may contain elements that do not exist in certain rows. In this case, the shapes that are not in the row should be ignored, while the shapes that do exist should be removed.
- The
favoritesobject contains other fields thanshapesand therefore cannot be converted into an array of strings. - The update must be in one query