1

So I have a column named "votes" which have the value "NULL" when the row first gets created. At the end of the day, I will add the votes coming from another table and put all the votes into the correct row. The problem is that if it is the first time the row gets votes, I will have to write SET votes = '$votes' but if it already has votes I will have to write SET votes = votes + '$votes'. Is there any easy way to detect if it is null or if it has an value?

2
  • Do you want to add new votes to previous one ? So it increase each time Commented Jan 6, 2014 at 4:30
  • votes + '$votes' would try to add a string to a number. Just use votes + $votes Commented Jan 6, 2014 at 4:30

4 Answers 4

3

You can use the ifnull MYSQL function, the SQL will be like

UPDATE .... SET votes = IFNULL(votes, 0) + votes
Sign up to request clarification or add additional context in comments.

Comments

2

Use Ifnull

SET votes = IFNULL(votes, 0) + votes

Comments

2

try this, COALESCE or IFNULL.

SET votes = COALESCE(votes, 0) + '$votes'

if the value of votes is null, it will be converted to 0 other wise retain the original value and added it to your $votes.

Comments

2

Initialise the field to 0 instead of NULL.

It makes sense for something to start off with no votes.

In fact, I'd make this column NOT NULL!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.