Skip to content
Advertisement

PostgreSQL – Does a ‘RETURNING ELSE’ statement exist for an UPDATE?

I have this query:

When the update is successful, it returns the following:

client_id username isSuccess
1 test_name 1

When the update doesn’t execute, it returns client_id, username, and isSuccess, but their values are blank.

What I’m having trouble with is customizing what returns when NO update is performed. If no update is performed, I need the following to return:

client_id username isSuccess
NULL NULL 0

Are there any tricks for writing a RETURNING clause with an ELSE clause to get the above result set when no update is executed? OR are there any other methods to get the result set I need? The following code does not work –

Advertisement

Answer

There is no ELSE statement in the RETURNING clause, but you can do something similar. The basic idea is to take the result from your update, combine it with another row using a UNION and just return the first result.

Postgres doesn’t allow us to use an update statement with a UNION so we have to put the update statement in a CTE:

I added an addition column, result_order so we can manually specify which result to prefer. In this case, if the returning clause returns a result, we want to return that one, so it gets the 1.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement