6

In Postgres 9.3 when a field in a table has a null value the following expression doesn't work:

update table_statatistic set members = members + 1 WHERE user_id = $1; 

However when the field has an integer value then this query increments it by 1 without a problem.

The questions are:

  1. Why is this happening.
  2. How to fix it.
2
  • Why? Because every expression involving null yields null. That's how SQL is specified. modern-sql.com/concept/null Commented Mar 23, 2018 at 7:22
  • 4
    I think you have that problem because you abuse SQL NULL. The correct semantics are "unknown", but you want to treat it as 0. Maybe you should add a DEFAULT 0 clause to the column definition (and add a NOT NULL while you're at it). Not only will that make your problem go away, it will also make all queries simpler. Commented Mar 23, 2018 at 8:02

2 Answers 2

14

you need to use coalesce for checking null values

update table_statatistic set members = coalesce(members, 0) + 1 WHERE user_id = $1
Sign up to request clarification or add additional context in comments.

Comments

2

Use COALESCE() instead: The COALESCE function returns the first of its arguments that is not null. Null is returned only if all arguments are null. It is often used to substitute a default value for null values when data is retrieved for display

UPDATE table_statatistic SET members = COALESCE(members,0) + 1 WHERE user_id = $1; 

6 Comments

Why do I need to use coalesce. Nothing + 1 = 1. Why is this happening.
A field with a NULL value is a field with no value. So you can't add 1 with no value Null is not a value.
This is counter intuitive and doesn't make logical sense, null means nothing. In many programming languages you can add integer to null just fine.
can you tell me the names of programming languages?
@Jimski null is not 0 those are two very different things. null is the absence of any information. What if I asked you to add a chair to your spaceship. How many chairs would your spaceship have after that?
|

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.