0

What I have:

ALTER TABLE countryb
ADD gnppercap real
;


INSERT INTO countryb (gnppercap)
    SELECT gnp/population
    FROM countryb
;

I successfully created the column "gnppercap", now I want to populate values in every row with the variable. The new variable is the product of gnp and 1/population, with variables gnp and population already in the table I'm altering, countryb.

Here's the error:

ERROR: null value in column "code" violates not-null constraint
SQL state: 23502
Detail: Failing row contains (null, null, null, null, null, null, null, null, null, null, null, >null, null, null, null, 0.000263028).

I know that the table, countryb has a ton of non-null vars in it, so that's what those nulls are, I think. I thought that since I specified the column I am inserting values into, it wouldn't matter...?

I'm lost. Help appreciated!

2
  • You added a column. It got whatever default value it should. Now you want to change this value in already existing row. Commented May 16, 2013 at 17:31
  • Hence the use of "update", makes sense now. Thanks Commented May 16, 2013 at 18:00

1 Answer 1

3

You want to update the table, not insert a new row.

update countryb set gnppercap = gnp/population

As an aside: You probably don't want to store a calculated value in a separate column. What happens if you update gnp or population? Your gnppercap column will be inaccurate.

Sign up to request clarification or add additional context in comments.

2 Comments

Wow yeah that was too easy, can't believe I missed it. Another question, sometimes the values are 0 in the numerator and denominator, I want to set these equal to null. How can I do that?
That would give you a null gnppercap. Your new column is probably null by default so there is no need to re-update that value to null. I would do this instead: update countryb set gnppercap = gnp/population where gnp <> 0 and population <> 0

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.