postgreSQL question…I have an update query below which updates a column with the results from a subquery, however in some cases the subquery will return null which throws the ‘not null’ constraint on the column, how can I get it to NOT update if the subquery returns null?
I have tried EXISTS but this only seems to work on a WHERE clause?
UPDATE user_stats as stats
SET ave_price = (
SELECT AVG(l.price)
FROM lengths as l, user_sessions as us
WHERE l.product_type = 'car'
AND l.session_id = us.session_id
AND stats.user_id = us.user_id
)
coalesce, nvl, ifnull in most db engines will do a conditional statement that says take the first non-null value in the string in this case when the subselect returns null it will set the ave_price = to itself.
This doesn’t prevent the udpate as requested, but it has a similar effect on the data.
For more info on coalesce see: PostgreSQL
To actually prevent the update you would needto add a where clause on the update and re-execute the sub query such as:
Logically executing the subquery twice would impact performance twice; whereas the coalesce only requires execution once. There’s always multiple ways to do things and depending on requirements, one must choose which option serves them best.