2

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

2
  • Just wanted to make sure if it is a typing mistake or not. In your query above, you have SELECT SUM(lengths_table.length_dist) FROM lengths. Shouldn't it be FROM lengths_table. Commented Sep 13, 2011 at 10:27
  • ah yes, just a typo, will change that Commented Sep 13, 2011 at 10:31

1 Answer 1

2

Either:

Your syntax is wrong (there is no lengths_table). Should be:

UPDATE sessions_table 
SET velocity = ROUND((SELECT SUM(lengths.length_dist) 
                      FROM lengths_table 
                      WHERE lengths.session_id = sessions_table.session_id)/time,2)

or, there are some cases where a sessions_table record has no macthing record in lengths_table. So you need to set velocity to zero in this case to satisfy your non-null constraint:

UPDATE sessions_table 
SET velocity = coalesce(ROUND((SELECT SUM(lengths_table.length_dist) 
                               FROM lengths 
                               WHERE lengths_table.session_id = sessions_table.session_id)/time,2),0)

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:

UPDATE sessions_table 
SET velocity = ROUND((SELECT SUM(coalesce(lengths_table.length_dist,0)) 
                      FROM lengths_table 
                      WHERE lengths_table.session_id = sessions_table.session_id)/time,2)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.