Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

How to handle a row UPDATE with multiple updateable fields, but only a subset of them need updating #1149

Answered by rhyselsmore
app-o-matix asked this question in Q&A
Discussion options

The only examples I have been able to find are ones where only one field is updated. I expanded the examples for multiple fields, but I'm not sure how to code it to correctly handle when all of the updateable fields are not being updated in a single update, just a subset of those fields.

For example, I have a table where the "name" field and "description" field are both updateable, but in an update I may want to only change the name. Currently, the way I expanded the single field examples, if I don't provide a value for the description, it changes it in the record to empty string rather than retaining the value it had before the update. Now, expand this to a table that might have four or ten or n updateable fields. What is the proper way to implement this? Thanks.

Note: According to spellchecker, updateable doesn't appear to be a real word. Until now. Consider it officially anointed as a full-fledged word and, of course, copyrighted by me, with royalties payable in perpetuity: updateable©

You must be logged in to vote

This is how I do it - based off an excellent blog post by @brandur.

-- name: UpdateWorkspace :exec
UPDATE workspaces
SET
 state = CASE WHEN @state_do_update::boolean
 THEN @state::workspace_state ELSE state END
WHERE
 id = @id::uuid;

Replies: 2 comments

Comment options

This is how I do it - based off an excellent blog post by @brandur.

-- name: UpdateWorkspace :exec
UPDATE workspaces
SET
 state = CASE WHEN @state_do_update::boolean
 THEN @state::workspace_state ELSE state END
WHERE
 id = @id::uuid;
You must be logged in to vote
0 replies
Answer selected by kyleconroy
Comment options

Since this question was posted, there is another way to do partial updates:
https://docs.sqlc.dev/en/latest/howto/named_parameters.html#nullable-parameters

-- name: UpdateAuthor :one
UPDATE author
SET
 name = coalesce(sqlc.narg('name'), name),
 bio = coalesce(sqlc.narg('bio'), bio)
WHERE id = sqlc.arg('id')
RETURNING *;

In this case only the values that are passed to query are updated.

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet

AltStyle によって変換されたページ (->オリジナル) /