1

I have a situation where I update a Postgres table column which is of type bigint[]. This array should have unique numbers inside it whenever an update query is fired.

The query is as given below

UPDATE book_shelf 
SET book_id = book_id || array[CAST(:bookID AS BIGINT)], updated_at = now() 
WHERE user_id = :userID AND shelf_name = :shelfName

When the above query is fired, it simply adds the number into the array which I don't want to happen. It should hold only unique values. Please help me.

1 Answer 1

1

You can check if it exists in the array before adding it:

UPDATE book_shelf 
SET book_id = CASE WHEN CAST(:bookID AS BIGINT) = ANY(book_id) THEN book_id ELSE ARRAY_APPEND(book_id, CAST(:bookID AS BIGINT)) END, updated_at = now() 
WHERE user_id = :userID AND shelf_name = :shelfName

Of course if updated_at should only be set if book_id is actually updated, then put the check in the WHERE clause so it's not updated unnecessarily:

UPDATE book_shelf 
SET book_id = ARRAY_APPEND(book_id, CAST(:bookID AS BIGINT)), updated_at = now() 
WHERE user_id = :userID
AND shelf_name = :shelfName
AND NOT CAST(:bookID AS BIGINT) = ANY(book_id)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. Works like a charm

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.