Is it possible for a single API PUT endpoint to use dynamic UPDATE/INSERT queries?
Example:
We have a patient table patient
that has a first_name
and last_name
column. Sometimes we want to update the first name for a patient using a PUT http request but other times we want to update both first_name
and last_name
using that same PUT http request.
The first update query would like this:
UPDATE patient
SET first_name = "new first name"
WHERE id = 1
The second query would like this:
UPDATE patient
SET
first_name = "new first name",
last_name = "new last name"
WHERE id = 1
We would like to combine this query to support both use cases without having to do a bunch of js gymnastics to inject sql into the query. We use pg-promise to support our psql/express integration.
2
Answers
You can use the COALESCE function.
COALESCE returns the first non-null value it encounters. So if your new last name is null, it will preserve the original value of the column and likewise.
Your last comment indicates you may want to use NULL to two diametrically opposed purposes, you cannot do that. It would seem you have two options:
Assuming you want to avoid separate queries try something like: (see demo)
The above uses the nullif() function to test the resulting value from
coalesce()
for a specific value. If those values match the result of the expression is NULL.