I have a seemingly basic SQL update to perform on a postgreSQL table that takes values from another table, the table structures are as follows…
sessions_table
session_id (PK)
velocity
time
lengths_table
length_id
session_id
length_dist
I want to update the velocity field with the sum of the length_dist values where session_table.session_id = lengths_table.session_id
I am trying the following statement but get ERROR: null value in column "velocity" violates not-null constraint when I run it (it works fine when I specify a single row)
UPDATE sessions_table
SET velocity = ROUND((SELECT SUM(lengths_table.length_dist)
FROM lengths_table
WHERE lengths_table.session_id = sessions_table.session_id)/time,2)
Can anyone suggest where I am going wrong?
Thanks
David
Either:
Your syntax is wrong (there is no lengths_table). Should be:
or, there are some cases where a sessions_table record has no macthing record in lengths_table. So you need to set
velocityto zero in this case to satisfy your non-null constraint:or, there are some matching records in the lengths_table with null values in length_dist, so you need to replace those with zero for the sum to work: